/**
 * Arrastre en grid: preview, soltar para reordenar o fusionar en carpeta (overlap).
 */
(function (global) {
    'use strict';

    var OVERLAP_RATIO = 0.35;

    function getGridItemAtPoint(appGrid, clientX, clientY, excludeEl) {
        if (!appGrid) return null;
        var prev = excludeEl && excludeEl.style ? excludeEl.style.pointerEvents : '';
        if (excludeEl) excludeEl.style.pointerEvents = 'none';
        var el = null;
        try {
            el = document.elementFromPoint(clientX, clientY);
        } finally {
            if (excludeEl) excludeEl.style.pointerEvents = prev || '';
        }
        if (!el) return null;
        return el.closest ? el.closest('#appGrid .app-item') : null;
    }

    function rectOverlapRatio(a, b) {
        var x1 = Math.max(a.left, b.left);
        var y1 = Math.max(a.top, b.top);
        var x2 = Math.min(a.right, b.right);
        var y2 = Math.min(a.bottom, b.bottom);
        if (x2 <= x1 || y2 <= y1) return 0;
        var inter = (x2 - x1) * (y2 - y1);
        var areaA = (a.right - a.left) * (a.bottom - a.top);
        if (areaA <= 0) return 0;
        return inter / areaA;
    }

    function shouldMergeFolder(dragRect, targetRect) {
        return rectOverlapRatio(dragRect, targetRect) >= OVERLAP_RATIO;
    }

    /**
     * Crea ghost flotante y gestiona z-index del tile original.
     */
    function createDragGhost(sourceEl, appGrid) {
        var ghost = sourceEl.cloneNode(true);
        ghost.classList.add('launcher-drag-ghost');
        ghost.style.position = 'fixed';
        ghost.style.zIndex = '10050';
        ghost.style.pointerEvents = 'none';
        ghost.style.width = sourceEl.offsetWidth + 'px';
        ghost.style.opacity = '0.92';
        ghost.style.transform = 'scale(1.05)';
        ghost.style.boxShadow = '0 8px 24px rgba(0,0,0,0.35)';
        document.body.appendChild(ghost);
        sourceEl.classList.add('launcher-drag-source');
        return {
            ghost: ghost,
            move: function (clientX, clientY, offsetX, offsetY) {
                ghost.style.left = (clientX - offsetX) + 'px';
                ghost.style.top = (clientY - offsetY) + 'px';
            },
            destroy: function () {
                try {
                    ghost.remove();
                } catch (_) {}
                sourceEl.classList.remove('launcher-drag-source');
            }
        };
    }

    global.GridLauncher = global.GridLauncher || {};
    global.GridLauncher.gridDrag = {
        getGridItemAtPoint: getGridItemAtPoint,
        shouldMergeFolder: shouldMergeFolder,
        rectOverlapRatio: rectOverlapRatio,
        createDragGhost: createDragGhost,
        OVERLAP_RATIO: OVERLAP_RATIO
    };
})(typeof window !== 'undefined' ? window : this);
