/**
 * Popover Drag Manager
 *
 * Handles drag-to-reposition for the popover panel mode.
 * Position persists in localStorage so it stays where the user left it.
 *
 * Used by WPBridgeHost — not standalone.
 */

/* global zipwpMcpBridge */

(function() {
    'use strict';

    var STORAGE_KEY = 'zipwp-popover-position';
    var SIZE_STORAGE_KEY = 'zipwp-popover-size';
    var CONTAINER_ID = 'zip-ai-assistant-container';
    var DRAG_HANDLE_SELECTOR = '[data-popover-drag]';
    var RESIZE_HANDLE_SELECTOR = '[data-popover-resize]';
    var INTERACTIVE_SELECTOR = 'button, input, textarea, a, [role="menuitem"], [data-radix-collection-item]';
    var DRAG_THRESHOLD = 4; // px — ignore tiny accidental drags
    var MIN_WIDTH = 360;
    var MIN_HEIGHT = 400;
    var MAX_WIDTH_MARGIN = 40; // min margin from viewport edge
    var MAX_HEIGHT_MARGIN = 60;

    /**
     * Sets up drag listeners on the container.
     * Called once from WPBridgeHost.setup().
     */
    function setupPopoverDrag(getBridgeLayout) {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;

        injectResizeHandles(container);

        var isDragging = false;
        var didMove = false;
        var startX, startY, startLeft, startTop;
        var isResizing = false;
        var resizeEdges = null;
        var startWidth, startHeight;

        function onMouseMove(e) {
            var dx = e.clientX - startX;
            var dy = e.clientY - startY;

            // Ignore until threshold is met
            if (!didMove && Math.abs(dx) + Math.abs(dy) < DRAG_THRESHOLD) return;
            didMove = true;

            var newLeft = startLeft + dx;
            var newTop = startTop + dy;

            // Clamp to viewport
            var cw = container.offsetWidth;
            var ch = container.offsetHeight;
            newLeft = Math.max(0, Math.min(newLeft, window.innerWidth - cw));
            newTop = Math.max(0, Math.min(newTop, window.innerHeight - ch));

            container.style.left = newLeft + 'px';
            container.style.top = newTop + 'px';
            container.style.right = 'auto';
            container.style.bottom = 'auto';
        }

        function onMouseUp() {
            if (!isDragging) return;
            isDragging = false;
            document.body.style.userSelect = '';
            container.style.transition = '';
            document.removeEventListener('mousemove', onMouseMove);
            document.removeEventListener('mouseup', onMouseUp);
            // Persist position only if the user actually moved
            if (didMove) {
                savePosition();
            }
        }

        container.addEventListener('mousedown', function(e) {
            if (getBridgeLayout() !== 'popover') return;

            // Resize takes priority over drag
            var resizeHandle = e.target.closest(RESIZE_HANDLE_SELECTOR);
            if (resizeHandle) {
                isResizing = true;
                resizeEdges = resizeHandle.getAttribute('data-popover-resize');
                var rect = container.getBoundingClientRect();
                startX = e.clientX;
                startY = e.clientY;
                startLeft = rect.left;
                startTop = rect.top;
                startWidth = rect.width;
                startHeight = rect.height;

                document.body.style.userSelect = 'none';
                container.style.transition = 'none';
                e.preventDefault();
                e.stopPropagation();

                document.addEventListener('mousemove', onResizeMove);
                document.addEventListener('mouseup', onResizeEnd);
                return;
            }

            // Only drag from header area
            var dragHandle = e.target.closest(DRAG_HANDLE_SELECTOR);
            if (!dragHandle) return;
            // Don't drag when clicking interactive elements
            if (e.target.closest(INTERACTIVE_SELECTOR)) return;

            isDragging = true;
            didMove = false;
            var dragRect = container.getBoundingClientRect();
            startX = e.clientX;
            startY = e.clientY;
            startLeft = dragRect.left;
            startTop = dragRect.top;

            document.body.style.userSelect = 'none';
            container.style.transition = 'none';
            e.preventDefault();

            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });

        function onResizeMove(e) {
            var dx = e.clientX - startX;
            var dy = e.clientY - startY;
            var maxW = window.innerWidth - MAX_WIDTH_MARGIN;
            var maxH = window.innerHeight - MAX_HEIGHT_MARGIN;
            var newWidth = startWidth;
            var newHeight = startHeight;
            var newLeft = startLeft;
            var newTop = startTop;

            if (resizeEdges.indexOf('e') !== -1) {
                newWidth = clamp(startWidth + dx, MIN_WIDTH, maxW);
            }
            if (resizeEdges.indexOf('w') !== -1) {
                newWidth = clamp(startWidth - dx, MIN_WIDTH, maxW);
                newLeft = startLeft + (startWidth - newWidth);
            }
            if (resizeEdges.indexOf('s') !== -1) {
                newHeight = clamp(startHeight + dy, MIN_HEIGHT, maxH);
            }
            if (resizeEdges.indexOf('n') !== -1) {
                newHeight = clamp(startHeight - dy, MIN_HEIGHT, maxH);
                newTop = startTop + (startHeight - newHeight);
            }

            container.style.setProperty('--zipwp-popover-w', newWidth + 'px');
            container.style.setProperty('--zipwp-popover-h', newHeight + 'px');
            container.style.setProperty('--zipwp-popover-max-h', 'none');
            if (resizeEdges.indexOf('w') !== -1 || resizeEdges.indexOf('n') !== -1 || container.style.left) {
                container.style.left = newLeft + 'px';
                container.style.top = newTop + 'px';
                container.style.right = 'auto';
                container.style.bottom = 'auto';
            }
        }

        function onResizeEnd() {
            if (!isResizing) return;
            isResizing = false;
            resizeEdges = null;
            document.body.style.userSelect = '';
            container.style.transition = '';
            document.removeEventListener('mousemove', onResizeMove);
            document.removeEventListener('mouseup', onResizeEnd);
            saveSize();
            if (container.style.left) savePosition();
        }
    }

    function clamp(v, lo, hi) {
        return Math.max(lo, Math.min(hi, v));
    }

    /**
     * Inject resize handle DOM elements — 4 edges + 4 corners.
     * Only visible in popover mode (CSS-gated by body class).
     */
    function injectResizeHandles(container) {
        if (container.querySelector(RESIZE_HANDLE_SELECTOR)) return;
        var edges = ['n', 's', 'e', 'w', 'nw', 'ne', 'sw', 'se'];
        edges.forEach(function(edge) {
            var el = document.createElement('div');
            el.setAttribute('data-popover-resize', edge);
            el.className = 'zipwp-popover-resize zipwp-popover-resize--' + edge;
            container.appendChild(el);
        });
    }

    function saveSize() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        try {
            localStorage.setItem(SIZE_STORAGE_KEY, JSON.stringify({
                width: container.offsetWidth,
                height: container.offsetHeight
            }));
        } catch (e) {}
    }

    function restoreSize() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        try {
            var raw = localStorage.getItem(SIZE_STORAGE_KEY);
            if (!raw) return;
            var size = JSON.parse(raw);
            if (!size || typeof size.width !== 'number' || typeof size.height !== 'number') return;
            var maxW = window.innerWidth - MAX_WIDTH_MARGIN;
            var maxH = window.innerHeight - MAX_HEIGHT_MARGIN;
            var w = clamp(size.width, MIN_WIDTH, maxW);
            var h = clamp(size.height, MIN_HEIGHT, maxH);
            container.style.setProperty('--zipwp-popover-w', w + 'px');
            container.style.setProperty('--zipwp-popover-h', h + 'px');
            container.style.setProperty('--zipwp-popover-max-h', 'none');
        } catch (e) {}
    }

    function clearSize() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        container.style.removeProperty('--zipwp-popover-w');
        container.style.removeProperty('--zipwp-popover-h');
        container.style.removeProperty('--zipwp-popover-max-h');
        try { localStorage.removeItem(SIZE_STORAGE_KEY); } catch (e) {}
    }

    /**
     * Save current container position to localStorage.
     */
    function savePosition() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container || !container.style.left) return;
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify({
                left: parseInt(container.style.left, 10),
                top: parseInt(container.style.top, 10)
            }));
        } catch (e) {}
    }

    /**
     * Restore saved position from localStorage, clamped to current viewport.
     */
    function restorePosition() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        // Restore size first so clamping uses the restored dimensions
        restoreSize();
        try {
            var raw = localStorage.getItem(STORAGE_KEY);
            if (!raw) return;
            var pos = JSON.parse(raw);
            if (!pos || typeof pos.left !== 'number' || typeof pos.top !== 'number') return;

            var left = pos.left;
            var top = pos.top;
            var cw = container.offsetWidth || 420;
            var ch = container.offsetHeight || 620;

            // Clamp to viewport
            if (left + cw > window.innerWidth) left = window.innerWidth - cw;
            if (top + ch > window.innerHeight) top = window.innerHeight - ch;
            if (left < 0) left = 0;
            if (top < 0) top = 0;

            container.style.left = left + 'px';
            container.style.top = top + 'px';
            container.style.right = 'auto';
            container.style.bottom = 'auto';
        } catch (e) {}
    }

    /**
     * Clear saved position and inline styles from the container.
     */
    function clearPosition() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        container.style.left = '';
        container.style.top = '';
        container.style.right = '';
        container.style.bottom = '';
        try { localStorage.removeItem(STORAGE_KEY); } catch (e) {}
        // Note: size intentionally NOT cleared here — user's custom popover
        // size persists across mode switches. Only resetLayout() wipes size.
    }

    /**
     * Reset popover to default size and position.
     * Removes CSS vars + inline position styles + clears storage.
     */
    function resetLayout() {
        var container = document.getElementById(CONTAINER_ID);
        if (!container) return;
        container.style.left = '';
        container.style.top = '';
        container.style.right = '';
        container.style.bottom = '';
        container.style.removeProperty('--zipwp-popover-w');
        container.style.removeProperty('--zipwp-popover-h');
        container.style.removeProperty('--zipwp-popover-max-h');
        try {
            localStorage.removeItem(STORAGE_KEY);
            localStorage.removeItem(SIZE_STORAGE_KEY);
        } catch (e) {}
    }

    // Expose for WPBridgeHost
    window.zipwpPopoverDrag = {
        setup: setupPopoverDrag,
        restorePosition: restorePosition,
        clearPosition: clearPosition,
        resetLayout: resetLayout
    };

})();
