//layout.js
let leftPanel, rightPanel, dragBar;
let isDragging = false;
let pendingX = null;

export function initResize() {
    leftPanel = document.getElementById("leftPanel");
    rightPanel = document.getElementById("rightPanel");
    dragBar = document.getElementById("dragBar");

    if (!leftPanel || !rightPanel || !dragBar) return;

    const savedRatio = localStorage.getItem('layoutRatio');
    if (savedRatio) {
        applyRatio(parseFloat(savedRatio));
    }

    dragBar.addEventListener("mousedown", (e) => {
        if (rightPanel.classList.contains("hidden")) return;

        isDragging = true;
        document.body.style.cursor = "col-resize";
        e.preventDefault();
    });

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

        isDragging = false;
        document.body.style.cursor = "default";

        if (!rightPanel.classList.contains("hidden")) {
            const total = window.innerWidth;
            const leftWidth = leftPanel.getBoundingClientRect().width;
            localStorage.setItem('layoutRatio', leftWidth / total);
        }
    });

    document.addEventListener("mousemove", (e) => {
        if (!isDragging) return;
        if (rightPanel.classList.contains("hidden")) return;

        pendingX = e.clientX;

        requestAnimationFrame(() => {
            if (pendingX === null) return;

            const total = window.innerWidth;
            let leftWidth = pendingX;

            const min = 300;
            if (leftWidth < min) leftWidth = min;
            if (leftWidth > total - min) leftWidth = total - min;

            const rightWidth = total - leftWidth - dragBar.offsetWidth;

            leftPanel.style.flex = `0 0 ${leftWidth}px`;
            rightPanel.style.flex = `0 0 ${rightWidth}px`;

            pendingX = null;
        });
    });
}

function applyRatio(ratio) {
    const total = window.innerWidth;
    const leftWidth = Math.floor(total * ratio);
    const rightWidth = total - leftWidth;

    leftPanel.style.flex = `0 0 ${leftWidth}px`;
    rightPanel.style.flex = `0 0 ${rightWidth}px`;
}

export function updateResizerVisibility() {
    if (!dragBar || !rightPanel) return;

    if (rightPanel.classList.contains("hidden")) {
        dragBar.classList.add("hidden");
        leftPanel.style.flex = "1";
    } else {
        dragBar.classList.remove("hidden");
    }
}