window.uiResizer = {
    controller: null,

    init: function (dotnetRef) {
        if (this.controller) {
            this.dispose();
        }
        this.controller = new AbortController();
        const signal = { signal: this.controller.signal };

        let isResizingSidebar = false;
        let isResizingOutput = false;
        let isResizingChart = false;
        let isResizingSettings = false;
        let isResizingCol = false;
        let currentColId = null;
        let startX = 0;
        let startY = 0;
        let startHeight = 0;

        document.addEventListener('mousedown', e => {
            const sidebarHandle = e.target.closest('.sidebar-resizer');
            const outputHandle = e.target.closest('.output-resizer');
            const chartHandle = e.target.closest('.chart-resizer');
            const settingsHandle = e.target.closest('.settings-resizer');
            const colHandle = e.target.closest('.col-resizer');

            if (sidebarHandle) isResizingSidebar = true;
            if (outputHandle) isResizingOutput = true;
            if (chartHandle) {
                isResizingChart = true;
                const chartContainer = chartHandle.closest('.chart-container');
                startHeight = chartContainer.offsetHeight;
                startY = e.clientY;
            }
            if (settingsHandle) isResizingSettings = true;
            if (colHandle) {
                isResizingCol = true;
                currentColId = colHandle.dataset.colId;
                startX = e.clientX;
                startWidth = colHandle.parentElement.offsetWidth;
            }

            if (isResizingSidebar || isResizingOutput || isResizingChart || isResizingSettings || isResizingCol) {
                document.body.classList.add('resizing');
                document.body.style.userSelect = 'none';

                // Prevent iframe events from interfering
                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(iframe => iframe.style.pointerEvents = 'none');
            }
        }, signal);

        document.addEventListener('mousemove', e => {
            if (isResizingSidebar) {
                const width = Math.max(150, Math.min(600, e.clientX));
                document.documentElement.style.setProperty('--sidebar-width', width + 'px');
            } else if (isResizingSettings) {
                const width = Math.max(200, Math.min(600, window.innerWidth - e.clientX));
                document.documentElement.style.setProperty('--settings-width', width + 'px');
            } else if (isResizingOutput) {
                // Constants
                const MIN_LOG_HEIGHT = 100;
                const TOOLBAR_HEIGHT = 40; // Approx

                // Get Current Chart Height
                const chartContainer = document.querySelector('.chart-container');
                const chartHeight = (chartContainer && chartContainer.offsetHeight > 0) ? chartContainer.offsetHeight : 0;

                // Calculate Max Allowed Output Height
                const maxOutputHeight = window.innerHeight - TOOLBAR_HEIGHT - chartHeight - MIN_LOG_HEIGHT;

                // Calculate New Height (Mouse from bottom)
                const height = Math.max(40, Math.min(maxOutputHeight, window.innerHeight - e.clientY));
                document.documentElement.style.setProperty('--output-height', height + 'px');

            } else if (isResizingChart) {
                // Constants
                const MIN_LOG_HEIGHT = 100;
                const TOOLBAR_HEIGHT = 40;

                // Get Current Output Height
                const outputResizer = document.querySelector('.output-resizer'); // Only exists if not collapsed
                let outputHeight = 0;
                if (outputResizer) {
                    outputHeight = outputResizer.parentElement.offsetHeight;
                } else {
                    // If collapsed or not found, try to get from CSS var or assume 0 if collapsed
                    // If collapsed, the resizer is not there, so height is likely 0 logic in Razor
                    // But we should double check if the panel exists
                    const outputPanel = document.querySelector('.bg-neutral-800.border-t.border-neutral-700.relative.flex-none.flex.flex-col');
                    if (outputPanel) outputHeight = outputPanel.offsetHeight;
                }

                // Calculate Max Allowed Chart Height
                const maxChartHeight = window.innerHeight - TOOLBAR_HEIGHT - outputHeight - MIN_LOG_HEIGHT;

                const diff = e.clientY - startY;
                const newHeight = Math.max(100, Math.min(maxChartHeight, startHeight + diff));
                document.documentElement.style.setProperty('--chart-height', newHeight + 'px');
            } else if (isResizingCol && currentColId && dotnetRef) {
                const diff = e.clientX - startX;
                const newWidth = Math.max(40, startWidth + diff);
                dotnetRef.invokeMethodAsync('UpdateColumnWidth', currentColId, newWidth + 'px');
            }
        }, signal);

        document.addEventListener('mouseup', () => {
            if (isResizingSidebar || isResizingOutput || isResizingChart || isResizingSettings || isResizingCol) {
                isResizingSidebar = false;
                isResizingOutput = false;
                isResizingChart = false;
                isResizingSettings = false;
                isResizingCol = false;
                currentColId = null;
                document.body.classList.remove('resizing');
                document.body.style.userSelect = '';

                // Restore iframe events
                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(iframe => iframe.style.pointerEvents = '');
            }
        }, signal);

        // Click outside to hide menu
        document.addEventListener('mousedown', e => {
            if (dotnetRef) {
                const menu = document.getElementById('col-config-menu');
                const btn = document.getElementById('col-config-btn');
                if (menu && !menu.contains(e.target) && btn && !btn.contains(e.target)) {
                    dotnetRef.invokeMethodAsync('HideColumnMenu');
                }
            }
        }, signal);
    },

    adjustOnResize: function () {
        if (!this.controller) this.controller = new AbortController();
        const signal = { signal: this.controller.signal };

        const handleResize = () => {
            const MIN_LOG_HEIGHT = 100;
            const TOOLBAR_HEIGHT = 40;

            const totalH = window.innerHeight;
            const rootStyle = getComputedStyle(document.documentElement);

            let currentChartH = parseFloat(rootStyle.getPropertyValue('--chart-height'));
            if (isNaN(currentChartH)) currentChartH = 0;

            let currentOutputH = parseFloat(rootStyle.getPropertyValue('--output-height'));
            if (isNaN(currentOutputH)) currentOutputH = 160;

            const chartContainer = document.querySelector('.chart-container');
            const isChartVisible = chartContainer && chartContainer.offsetHeight > 0;
            if (!isChartVisible) currentChartH = 0;

            const outputPanel = document.querySelector('.bg-neutral-800.border-t.border-neutral-700.relative.flex-none.flex.flex-col');
            const isOutputVisible = outputPanel && outputPanel.offsetHeight > 0;
            if (!isOutputVisible) currentOutputH = 0;

            const maxCombined = totalH - TOOLBAR_HEIGHT - MIN_LOG_HEIGHT;

            if (maxCombined < 50) return;

            if (currentChartH + currentOutputH > maxCombined) {
                if (currentChartH > maxCombined - currentOutputH) {
                    currentChartH = Math.max(100, maxCombined - currentOutputH);
                }

                if (currentChartH + currentOutputH > maxCombined) {
                    currentOutputH = Math.max(40, maxCombined - currentChartH);
                }

                if (isChartVisible)
                    document.documentElement.style.setProperty('--chart-height', currentChartH + 'px');

                if (isOutputVisible)
                    document.documentElement.style.setProperty('--output-height', currentOutputH + 'px');
            }
        };

        window.addEventListener('resize', handleResize, signal);
        requestAnimationFrame(handleResize);
    },
    dispose: function () {
        if (this.controller) {
            this.controller.abort();
            this.controller = null;
        }
    }
};
