/**
 * cropper.js
 * Injected content script to handle area selection
 */

(function () {
    // Prevent multiple injections
    if (document.getElementById('grain-of-salt-cropper-container')) {
        return;
    }

    const container = document.createElement('div');
    container.id = 'grain-of-salt-cropper-container';
    container.className = 'grain-of-salt-cropper-overlay';

    const helperText = document.createElement('div');
    helperText.className = 'grain-of-salt-helper-text';
    helperText.textContent = 'Drag to select an area to verify. Press ESC to cancel.';
    container.appendChild(helperText);

    const selectionBox = document.createElement('div');
    selectionBox.className = 'grain-of-salt-selection-box';
    selectionBox.style.display = 'none';
    container.appendChild(selectionBox);

    document.body.appendChild(container);

    let isDragging = false;
    let startX = 0;
    let startY = 0;

    function onMouseDown(e) {
        // Prevent interaction with page
        e.preventDefault();
        e.stopPropagation();

        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;

        selectionBox.style.left = startX + 'px';
        selectionBox.style.top = startY + 'px';
        selectionBox.style.width = '0px';
        selectionBox.style.height = '0px';
        selectionBox.style.display = 'block';
    }

    function onMouseMove(e) {
        if (!isDragging) return;

        const currentX = e.clientX;
        const currentY = e.clientY;

        const width = Math.abs(currentX - startX);
        const height = Math.abs(currentY - startY);
        const left = Math.min(currentX, startX);
        const top = Math.min(currentY, startY);

        selectionBox.style.width = width + 'px';
        selectionBox.style.height = height + 'px';
        selectionBox.style.left = left + 'px';
        selectionBox.style.top = top + 'px';
    }

    function onMouseUp(e) {
        if (!isDragging) return;
        isDragging = false;

        const rect = selectionBox.getBoundingClientRect();

        // Remove overlay
        cleanup();

        // If selection is too small, treat as cancel or click
        if (rect.width < 50 || rect.height < 50) {
            console.log("Selection too small, ignoring.");
            return;
        }

        // Send coordinates back to extension
        // We need to account for device pixel ratio for high DPI screens if we are cropping a screenshot
        // But captureVisibleTab returns an image sized to the visible viewport (usually CSS pixels * DPR)
        // We'll pass CSS pixels and let the extension handle the math
        const cropData = {
            action: 'CROP_AREA_SELECTED',
            area: {
                x: rect.left,
                y: rect.top,
                width: rect.width,
                height: rect.height,
                devicePixelRatio: window.devicePixelRatio
            }
        };

        chrome.runtime.sendMessage(cropData);
    }

    function onKeyDown(e) {
        if (e.key === 'Escape') {
            cleanup();
        }
    }

    function cleanup() {
        document.removeEventListener('mousedown', onMouseDown);
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
        document.removeEventListener('keydown', onKeyDown);
        if (container.parentNode) {
            container.parentNode.removeChild(container);
        }
    }

    // Attach listeners
    container.addEventListener('mousedown', onMouseDown);
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
    document.addEventListener('keydown', onKeyDown);

})();
