/**
 * Handles resizing of the main application layout panes.
 */
export function initResizer(containerSelector, resizerSelector, variableName) {
    const container = document.querySelector(containerSelector);
    const resizer = document.querySelector(resizerSelector);
    
    if (!container || !resizer) return;

    const storageKey = 'nexus-sidebar-width';
    let isResizing = false;

    // Load initial width
    const savedWidth = localStorage.getItem(storageKey);
    if (savedWidth) {
        container.style.setProperty(variableName, savedWidth);
        // Delay a bit to ensure components are mounted before triggering resize
        setTimeout(() => window.dispatchEvent(new Event('resize')), 100);
    }

    resizer.addEventListener('mousedown', (e) => {
        isResizing = true;
        document.body.style.cursor = 'col-resize';
        container.classList.add('is-resizing');
        e.preventDefault();
    });

    document.addEventListener('mousemove', (e) => {
        if (!isResizing) return;

        // Calculate new width for the right panel
        // container width - mouse X position
        const containerRect = container.getBoundingClientRect();
        const newWidth = containerRect.right - e.clientX;

        // Constraints
        const minWidth = 300;
        const maxWidth = containerRect.width * 0.7;

        if (newWidth >= minWidth && newWidth <= maxWidth) {
            container.style.setProperty(variableName, `${newWidth}px`);
        }
    });

    document.addEventListener('mouseup', () => {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = '';
            container.classList.remove('is-resizing');
            
            // Save width
            const currentWidth = container.style.getPropertyValue(variableName);
            localStorage.setItem(storageKey, currentWidth);

            // Dispatch a window resize event to notify components like D3
            window.dispatchEvent(new Event('resize'));
        }
    });
}
