// element-remover.js
// Enhanced element picker for Site Customizer with improved UI and reliability

(function() {
    'use strict';
    
    let isActive = false;
    let hoveredElement = null;
    let actionMenu = null;
    let overlay = null;
    let controlBar = null;
    let removedCount = 0;
    
    // Retry configuration for message posting
    const MAX_RETRIES = 3;
    const RETRY_DELAY = 100;
    
    // Inject overlay styles
    function injectStyles() {
        if (document.getElementById('element-remover-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'element-remover-styles';
        style.textContent = `
            .element-remover-highlight {
                outline: 3px solid #007AFF !important;
                outline-offset: 2px !important;
                cursor: pointer !important;
                background-color: rgba(0, 122, 255, 0.08) !important;
            }
            
            .element-remover-overlay {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                right: 0 !important;
                bottom: 0 !important;
                border: 4px solid #007AFF !important;
                z-index: 2147483644 !important;
                pointer-events: none !important;
                box-shadow: inset 0 0 0 4px rgba(0, 122, 255, 0.15) !important;
            }
            
            .element-remover-control-bar {
                position: fixed !important;
                bottom: 24px !important;
                left: 50% !important;
                transform: translateX(-50%) !important;
                background: rgba(0, 0, 0, 0.9) !important;
                backdrop-filter: blur(20px) !important;
                -webkit-backdrop-filter: blur(20px) !important;
                color: white !important;
                padding: 12px 20px !important;
                border-radius: 14px !important;
                font-family: -apple-system, BlinkMacSystemFont, 'SF Pro', system-ui, sans-serif !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                z-index: 2147483647 !important;
                pointer-events: auto !important;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.1) !important;
                display: flex !important;
                align-items: center !important;
                gap: 16px !important;
            }
            
            .element-remover-control-bar .status {
                display: flex !important;
                align-items: center !important;
                gap: 8px !important;
            }
            
            .element-remover-control-bar .status-dot {
                width: 8px !important;
                height: 8px !important;
                background: #FF3B30 !important;
                border-radius: 50% !important;
                animation: pulse 1.5s ease-in-out infinite !important;
            }
            
            .element-remover-control-bar .count {
                color: rgba(255, 255, 255, 0.6) !important;
                font-size: 12px !important;
            }
            
            .element-remover-control-bar .buttons {
                display: flex !important;
                gap: 8px !important;
            }
            
            .element-remover-control-bar button {
                padding: 8px 16px !important;
                border: none !important;
                border-radius: 8px !important;
                font-size: 13px !important;
                font-weight: 600 !important;
                cursor: pointer !important;
                transition: all 0.15s ease !important;
            }
            
            .element-remover-control-bar button.cancel {
                background: rgba(255, 255, 255, 0.15) !important;
                color: white !important;
            }
            
            .element-remover-control-bar button.cancel:hover {
                background: rgba(255, 255, 255, 0.25) !important;
            }
            
            .element-remover-control-bar button.done {
                background: #007AFF !important;
                color: white !important;
            }
            
            .element-remover-control-bar button.done:hover {
                background: #0066DD !important;
            }
            
            @keyframes pulse {
                0%, 100% { opacity: 1; transform: scale(1); }
                50% { opacity: 0.6; transform: scale(1.2); }
            }
            
            .element-remover-action-menu {
                position: fixed !important;
                background: white !important;
                border-radius: 12px !important;
                box-shadow: 0 12px 48px rgba(0, 0, 0, 0.35) !important;
                padding: 8px !important;
                z-index: 2147483647 !important;
                min-width: 220px !important;
                font-family: -apple-system, BlinkMacSystemFont, 'SF Pro', system-ui, sans-serif !important;
                pointer-events: auto !important;
            }
            
            .element-remover-action-menu button {
                display: flex !important;
                align-items: center !important;
                gap: 10px !important;
                width: 100% !important;
                padding: 10px 14px !important;
                border: none !important;
                background: transparent !important;
                color: #000 !important;
                text-align: left !important;
                cursor: pointer !important;
                border-radius: 8px !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                transition: background 0.15s ease !important;
            }
            
            .element-remover-action-menu button:hover {
                background: rgba(0, 122, 255, 0.1) !important;
            }
            
            .element-remover-action-menu button.danger {
                color: #FF3B30 !important;
            }
            
            .element-remover-action-menu button.danger:hover {
                background: rgba(255, 59, 48, 0.1) !important;
            }
            
            .element-remover-action-menu button .icon {
                font-size: 16px !important;
            }
            
            .element-remover-action-menu hr {
                margin: 6px 0 !important;
                border: none !important;
                border-top: 1px solid rgba(0, 0, 0, 0.08) !important;
            }
            
            .element-remover-info {
                padding: 10px 14px !important;
                font-size: 11px !important;
                color: #666 !important;
                border-bottom: 1px solid rgba(0, 0, 0, 0.08) !important;
                margin-bottom: 4px !important;
                font-family: 'SF Mono', Monaco, monospace !important;
                word-break: break-all !important;
            }
            
            @media (prefers-color-scheme: dark) {
                .element-remover-action-menu {
                    background: #1C1C1E !important;
                    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.6) !important;
                }
                .element-remover-action-menu button {
                    color: #FFF !important;
                }
                .element-remover-action-menu button:hover {
                    background: rgba(255, 255, 255, 0.1) !important;
                }
                .element-remover-info {
                    color: #999 !important;
                    border-bottom-color: rgba(255, 255, 255, 0.1) !important;
                }
                .element-remover-action-menu hr {
                    border-top-color: rgba(255, 255, 255, 0.1) !important;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    function activate() {
        if (isActive) return;
        isActive = true;
        removedCount = 0;
        
        injectStyles();
        
        // Create overlay border
        overlay = document.createElement('div');
        overlay.className = 'element-remover-overlay';
        document.body.appendChild(overlay);
        
        // Create control bar at bottom
        controlBar = document.createElement('div');
        controlBar.className = 'element-remover-control-bar';
        controlBar.innerHTML = `
            <div class="status">
                <div class="status-dot"></div>
                <span>Element Editor Active</span>
            </div>
            <span class="count">Click elements to remove</span>
            <div class="buttons">
                <button class="cancel">Cancel</button>
                <button class="done">Done</button>
            </div>
        `;
        document.body.appendChild(controlBar);
        
        // Control bar button handlers
        controlBar.querySelector('.cancel').addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            deactivate();
            notifySwiftWithRetry({ action: 'cancel' });
        }, true);
        
        controlBar.querySelector('.done').addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            deactivate();
            notifySwiftWithRetry({ action: 'done' });
        }, true);
        
        // Add event listeners
        document.addEventListener('mouseover', handleMouseOver, true);
        document.addEventListener('mouseout', handleMouseOut, true);
        document.addEventListener('click', handleClick, true);
        document.addEventListener('keydown', handleKeyDown, true);
        
        console.log('Element Remover: Activated');
    }
    
    function deactivate() {
        if (!isActive) return;
        isActive = false;
        
        // Remove overlay
        if (overlay && overlay.parentNode) {
            overlay.remove();
        }
        overlay = null;
        
        // Remove control bar
        if (controlBar && controlBar.parentNode) {
            controlBar.remove();
        }
        controlBar = null;
        
        // Remove action menu
        hideActionMenu();
        
        // Remove highlight
        if (hoveredElement) {
            hoveredElement.classList.remove('element-remover-highlight');
            hoveredElement = null;
        }
        
        // Remove event listeners
        document.removeEventListener('mouseover', handleMouseOver, true);
        document.removeEventListener('mouseout', handleMouseOut, true);
        document.removeEventListener('click', handleClick, true);
        document.removeEventListener('keydown', handleKeyDown, true);
        
        // Remove styles
        const styles = document.getElementById('element-remover-styles');
        if (styles) styles.remove();
        
        console.log('Element Remover: Deactivated');
    }
    
    function handleMouseOver(event) {
        const element = event.target;
        
        // Don't highlight our own UI
        if (isOurElement(element)) {
            return;
        }
        
        // Remove previous highlight
        if (hoveredElement && hoveredElement !== element) {
            hoveredElement.classList.remove('element-remover-highlight');
        }
        
        // Add new highlight
        element.classList.add('element-remover-highlight');
        hoveredElement = element;
    }
    
    function handleMouseOut(event) {
        const element = event.target;
        
        // Keep highlight if mouse is over action menu
        if (actionMenu && actionMenu.contains(event.relatedTarget)) {
            return;
        }
        
        element.classList.remove('element-remover-highlight');
        if (hoveredElement === element) {
            hoveredElement = null;
        }
    }
    
    function handleClick(event) {
        const element = event.target;
        
        // Allow clicks on our UI elements
        if (isOurElement(element)) {
            return;
        }
        
        event.preventDefault();
        event.stopPropagation();
        
        console.log('Element clicked:', element);
        showActionMenu(element, event.clientX, event.clientY);
    }
    
    function handleKeyDown(event) {
        if (event.key === 'Escape') {
            if (actionMenu) {
                hideActionMenu();
            } else {
                deactivate();
                notifySwiftWithRetry({ action: 'cancel' });
            }
        }
    }
    
    function isOurElement(element) {
        return element === overlay || 
               element === controlBar || 
               element === actionMenu ||
               (controlBar && controlBar.contains(element)) ||
               (actionMenu && actionMenu.contains(element));
    }
    
    function showActionMenu(element, x, y) {
        hideActionMenu();
        
        actionMenu = document.createElement('div');
        actionMenu.className = 'element-remover-action-menu';
        
        // Element info
        const info = document.createElement('div');
        info.className = 'element-remover-info';
        info.textContent = getElementDescription(element);
        actionMenu.appendChild(info);
        
        // Remove This Element
        const removeBtn = document.createElement('button');
        removeBtn.className = 'danger';
        removeBtn.innerHTML = '<span class="icon">🗑️</span> Remove This Element';
        removeBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            removeElement(element, false);
        }, true);
        actionMenu.appendChild(removeBtn);
        
        // Remove Similar Elements
        const removeSimilarBtn = document.createElement('button');
        removeSimilarBtn.className = 'danger';
        removeSimilarBtn.innerHTML = '<span class="icon">🔄</span> Remove Similar Elements';
        removeSimilarBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            removeElement(element, true);
        }, true);
        actionMenu.appendChild(removeSimilarBtn);
        
        const hr = document.createElement('hr');
        actionMenu.appendChild(hr);
        
        // Cancel
        const cancelBtn = document.createElement('button');
        cancelBtn.innerHTML = '<span class="icon">✕</span> Cancel';
        cancelBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            hideActionMenu();
        }, true);
        actionMenu.appendChild(cancelBtn);
        
        // Position menu
        document.body.appendChild(actionMenu);
        
        // Adjust position to stay on screen
        const rect = actionMenu.getBoundingClientRect();
        let menuX = x + 5;
        let menuY = y + 5;
        
        if (menuX + rect.width > window.innerWidth) {
            menuX = window.innerWidth - rect.width - 10;
        }
        if (menuY + rect.height > window.innerHeight) {
            menuY = window.innerHeight - rect.height - 10;
        }
        
        actionMenu.style.left = menuX + 'px';
        actionMenu.style.top = menuY + 'px';
    }
    
    function hideActionMenu() {
        if (actionMenu && actionMenu.parentNode) {
            actionMenu.remove();
        }
        actionMenu = null;
    }
    
    function removeElement(element, similar) {
        const selector = getSelector(element, similar);
        const description = getElementDescription(element);
        
        // Hide the element(s) immediately
        if (similar) {
            const elements = document.querySelectorAll(selector);
            elements.forEach(el => el.style.display = 'none');
            removedCount += elements.length;
        } else {
            element.style.display = 'none';
            removedCount++;
        }
        
        // Update count in control bar
        updateRemovedCount();
        
        // Notify Swift with retry
        notifySwiftWithRetry({
            action: 'remove',
            selector: selector,
            description: description,
            similar: similar
        });
        
        hideActionMenu();
        
        // Clear hover state
        if (hoveredElement) {
            hoveredElement.classList.remove('element-remover-highlight');
            hoveredElement = null;
        }
    }
    
    function updateRemovedCount() {
        if (controlBar) {
            const countEl = controlBar.querySelector('.count');
            if (countEl) {
                countEl.textContent = removedCount > 0 
                    ? `${removedCount} element${removedCount > 1 ? 's' : ''} removed` 
                    : 'Click elements to remove';
            }
        }
    }
    
    function getSelector(element, similar) {
        // Try to get a good selector
        if (element.id) {
            return similar ? `[id="${element.id}"]` : `#${element.id}`;
        }
        
        if (element.className && typeof element.className === 'string') {
            const classes = element.className.trim().split(/\s+/)
                .filter(cls => !cls.startsWith('element-remover-'));
            
            if (classes.length > 0) {
                if (similar) {
                    return '.' + classes.join('.');
                } else {
                    const tag = element.tagName.toLowerCase();
                    return tag + '.' + classes.join('.');
                }
            }
        }
        
        // Fallback to tag name with nth-child for specificity
        const tag = element.tagName.toLowerCase();
        if (!similar && element.parentElement) {
            const siblings = Array.from(element.parentElement.children).filter(
                el => el.tagName === element.tagName
            );
            const index = siblings.indexOf(element);
            if (siblings.length > 1 && index >= 0) {
                return `${tag}:nth-of-type(${index + 1})`;
            }
        }
        
        return tag;
    }
    
    function getElementDescription(element) {
        const tag = element.tagName.toLowerCase();
        
        if (element.id) {
            return `<${tag}#${element.id}>`;
        }
        
        if (element.className && typeof element.className === 'string') {
            const classes = element.className.trim().split(/\s+/)
                .filter(cls => !cls.startsWith('element-remover-'))
                .slice(0, 2);
            
            if (classes.length > 0) {
                return `<${tag}.${classes.join('.')}>`;
            }
        }
        
        // Try to get text content
        const text = element.textContent?.trim().slice(0, 25);
        if (text) {
            return `<${tag}> "${text}${text.length >= 25 ? '...' : ''}"`;
        }
        
        return `<${tag}>`;
    }
    
    // Notify Swift with retry logic for reliability
    function notifySwiftWithRetry(data, retryCount = 0) {
        try {
            if (window.webkit && window.webkit.messageHandlers && 
                window.webkit.messageHandlers.elementRemover) {
                window.webkit.messageHandlers.elementRemover.postMessage(data);
                console.log('Element Remover: Message sent successfully', data.action);
            } else {
                throw new Error('Message handler not available');
            }
        } catch (error) {
            console.warn('Element Remover: Failed to send message', error);
            
            if (retryCount < MAX_RETRIES) {
                console.log(`Element Remover: Retrying in ${RETRY_DELAY}ms (attempt ${retryCount + 1}/${MAX_RETRIES})`);
                setTimeout(() => {
                    notifySwiftWithRetry(data, retryCount + 1);
                }, RETRY_DELAY);
            } else {
                console.error('Element Remover: Max retries reached, message not sent');
                // Notify about the error
                try {
                    if (window.webkit?.messageHandlers?.elementRemover) {
                        window.webkit.messageHandlers.elementRemover.postMessage({
                            action: 'error',
                            message: 'Failed to communicate with app after retries'
                        });
                    }
                } catch (e) {}
            }
        }
    }
    
    // Legacy function for backwards compatibility
    function notifySwift(data) {
        notifySwiftWithRetry(data);
    }
    
    // Expose API
    window.ElementRemover = {
        activate: activate,
        deactivate: deactivate
    };
    
})();
