/**
 * Sidekick Web Companion Content Script
 * Injected into WKWebView to capture structured feedback.
 */

(function() {
    if (window.__sidekick_injected) return;
    window.__sidekick_injected = true;

    const STATE = {
        isPinning: false,
        hoveredElement: null,
        overlay: null,
    };

    // Privacy mask: blurs credential-bearing inputs while Sidekick records the
    // screen. The CSS between the markers MUST stay identical to the copy in
    // Resources/BrowserExtension/sidekick-chrome/background.js (enforced by
    // privacyMaskSelectorsStayInSyncAcrossSurfaces in the workflow checks).
    const PRIVACY_MASK_CSS = `
/* sidekick:privacy-mask:start */
input[type="password"],
input[type="email"],
input[autocomplete~="username"],
input[autocomplete~="email"],
input[autocomplete*="password"],
input[name*="pass" i], input[id*="pass" i],
input[name*="user" i], input[id*="user" i],
input[name*="email" i], input[id*="email" i],
input[name*="login" i], input[id*="login" i] {
  filter: blur(6px) !important;
}
/* sidekick:privacy-mask:end */
`;

    function setPrivacyMask(enabled) {
        const existing = document.getElementById('__sidekick_privacy_mask');
        if (enabled && !existing) {
            const style = document.createElement('style');
            style.id = '__sidekick_privacy_mask';
            style.textContent = PRIVACY_MASK_CSS;
            (document.head || document.documentElement).appendChild(style);
        } else if (!enabled && existing) {
            existing.remove();
        }
    }

    // --- Message Bridge ---
    function post(kind, payload) {
        if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.sidekick) {
            window.webkit.messageHandlers.sidekick.postMessage({ kind, payload });
        }
    }

    // --- Console Proxy ---
    const originalConsole = {
        log: console.log,
        info: console.info,
        warn: console.warn,
        error: console.error,
        debug: console.debug
    };

    function proxyConsole(type) {
        console[type] = function(...args) {
            originalConsole[type].apply(console, args);
            post('console', {
                type: type,
                text: args.map(a => String(a)).join(' '),
                timestamp: Date.now()
            });
        };
    }

    ['log', 'info', 'warn', 'error', 'debug'].forEach(proxyConsole);

    window.addEventListener('error', (event) => {
        post('error', {
            message: event.message,
            source: event.filename,
            lineno: event.lineno,
            colno: event.colno,
            stack: event.error ? event.error.stack : null
        });
    });

    window.addEventListener('unhandledrejection', (event) => {
        post('error', {
            message: 'Unhandled Rejection: ' + event.reason,
            timestamp: Date.now()
        });
    });

    // --- Viewport & Nav ---
    post('navigation', { url: window.location.href, title: document.title });

    // --- UI Selection (Pinning) ---
    function createOverlay() {
        if (STATE.overlay) return;
        const overlay = document.createElement('div');
        overlay.id = '__sidekick_overlay';
        overlay.style.position = 'fixed';
        overlay.style.pointerEvents = 'none';
        overlay.style.zIndex = '2147483647';
        overlay.style.border = '2px solid #5C5CFF'; // Brand color
        overlay.style.backgroundColor = 'rgba(92, 92, 255, 0.1)';
        overlay.style.borderRadius = '4px';
        overlay.style.transition = 'all 0.15s ease-out';
        overlay.style.display = 'none';
        overlay.style.boxShadow = '0 0 15px rgba(92, 92, 255, 0.3)';
        
        const label = document.createElement('div');
        label.style.position = 'absolute';
        label.style.top = '-24px';
        label.style.left = '0';
        label.style.backgroundColor = '#5C5CFF';
        label.style.color = 'white';
        label.style.fontSize = '10px';
        label.style.padding = '2px 6px';
        label.style.borderRadius = '4px 4px 0 0';
        label.style.whiteSpace = 'nowrap';
        label.id = '__sidekick_overlay_label';
        
        overlay.appendChild(label);
        document.body.appendChild(overlay);
        STATE.overlay = overlay;
    }

    function updateOverlay(el) {
        if (!el || !STATE.overlay) {
            if (STATE.overlay) STATE.overlay.style.display = 'none';
            return;
        }
        const rect = el.getBoundingClientRect();
        STATE.overlay.style.display = 'block';
        STATE.overlay.style.top = `${rect.top}px`;
        STATE.overlay.style.left = `${rect.left}px`;
        STATE.overlay.style.width = `${rect.width}px`;
        STATE.overlay.style.height = `${rect.height}px`;
        
        const label = document.getElementById('__sidekick_overlay_label');
        if (label) {
            const tag = el.tagName.toLowerCase();
            const classes = el.className ? `.${Array.from(el.classList).join('.')}` : '';
            label.textContent = `${tag}${classes} (${Math.round(rect.width)}x${Math.round(rect.height)})`;
        }
    }

    function getPayload(el) {
        const styles = window.getComputedStyle(el);
        const rect = el.getBoundingClientRect();
        
        return {
            tagName: el.tagName.toLowerCase(),
            outerHTML: el.outerHTML, // We'll trim this in Swift if needed
            id: el.id,
            className: el.className,
            attributes: Array.from(el.attributes).reduce((acc, attr) => {
                acc[attr.name] = attr.value;
                return acc;
            }, {}),
            bounds: {
                top: rect.top,
                left: rect.left,
                width: rect.width,
                height: rect.height
            },
            computedStyles: {
                display: styles.display,
                position: styles.position,
                color: styles.color,
                backgroundColor: styles.backgroundColor,
                fontFamily: styles.fontFamily,
                fontSize: styles.fontSize,
                fontWeight: styles.fontWeight,
                margin: styles.margin,
                padding: styles.padding,
                border: styles.border
            },
            selector: buildSelector(el)
        };
    }

    function buildSelector(el) {
        if (el.id) return `#${CSS.escape(el.id)}`;
        if (el.getAttribute('data-testid')) return `[data-testid="${CSS.escape(el.getAttribute('data-testid'))}"]`;
        
        let path = [];
        while (el.nodeType === Node.ELEMENT_NODE) {
            let selector = el.nodeName.toLowerCase();
            if (el.id) {
                selector += '#' + CSS.escape(el.id);
                path.unshift(selector);
                break;
            } else {
                let sib = el, nth = 1;
                while (sib = sib.previousElementSibling) {
                    if (sib.nodeName.toLowerCase() == selector) nth++;
                }
                if (nth != 1) selector += ":nth-of-type(" + nth + ")";
            }
            path.unshift(selector);
            el = el.parentNode;
        }
        return path.join(" > ");
    }

    // --- Event Listeners ---
    document.addEventListener('mouseover', (e) => {
        if (!STATE.isPinning) return;
        // Find the best interactive ancestor or the element itself
        const target = e.target.closest('button, a, input, select, textarea, [role="button"]') || e.target;
        STATE.hoveredElement = target;
        updateOverlay(target);
    });

    document.addEventListener('mousedown', (e) => {
        if (!STATE.isPinning) return;
        e.preventDefault();
        e.stopPropagation();
        
        const target = STATE.hoveredElement || e.target;
        const payload = getPayload(target);
        post('pin', payload);
        
        // Brief flash on pin
        if (STATE.overlay) {
            STATE.overlay.style.backgroundColor = 'rgba(92, 92, 255, 0.5)';
            setTimeout(() => {
                STATE.overlay.style.backgroundColor = 'rgba(92, 92, 255, 0.1)';
            }, 100);
        }
    }, true);

    // --- Control Commands from Swift ---
    window.__sidekick_control = {
        setPinningMode: (active) => {
            STATE.isPinning = active;
            if (active) {
                createOverlay();
                document.body.style.cursor = 'crosshair';
            } else {
                updateOverlay(null);
                document.body.style.cursor = 'default';
            }
        },
        setPrivacyMask: setPrivacyMask
    };

    console.log('Sidekick Web Companion Injected Successfully');
})();
