/**
 * Draggable splitter handle for resizing the left panel.
 *
 * Attaches mousedown/mousemove/mouseup listeners to the splitter handle
 * element. On drag, adjusts the width of the left panel. No Dash callback
 * needed — this runs entirely in the browser.
 */
(function () {
    "use strict";

    function initSplitter() {
        var handle = document.getElementById("splitter-handle");
        var leftPanel = document.getElementById("left-panel");

        if (!handle || !leftPanel) {
            // Elements not yet in DOM — retry shortly
            setTimeout(initSplitter, 200);
            return;
        }

        var isDragging = false;
        var startX = 0;
        var startWidth = 0;

        handle.addEventListener("mousedown", function (e) {
            isDragging = true;
            startX = e.clientX;
            startWidth = leftPanel.offsetWidth;

            // Prevent text selection during drag
            document.body.style.userSelect = "none";
            document.body.style.cursor = "col-resize";
            handle.style.backgroundColor = "#adb5bd";

            e.preventDefault();
        });

        document.addEventListener("mousemove", function (e) {
            if (!isDragging) return;

            var delta = e.clientX - startX;
            var newWidth = startWidth + delta;

            // Respect min/max from the CSS
            var minWidth = parseInt(leftPanel.style.minWidth) || 200;
            var maxWidth = parseInt(leftPanel.style.maxWidth) || 600;
            newWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));

            leftPanel.style.width = newWidth + "px";
        });

        document.addEventListener("mouseup", function () {
            if (!isDragging) return;

            isDragging = false;
            document.body.style.userSelect = "";
            document.body.style.cursor = "";
            handle.style.backgroundColor = "#e9ecef";

            // Trigger a window resize event so Plotly graphs reflow
            window.dispatchEvent(new Event("resize"));
        });

        // Hover effect
        handle.addEventListener("mouseenter", function () {
            if (!isDragging) {
                handle.style.backgroundColor = "#ced4da";
            }
        });

        handle.addEventListener("mouseleave", function () {
            if (!isDragging) {
                handle.style.backgroundColor = "#e9ecef";
            }
        });
    }

    // Wait for DOM ready
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", initSplitter);
    } else {
        initSplitter();
    }
})();
