/*-------------------------------------------------------------------
 VMO AI Website Builder – Element-Specific Refinement System
 Ultra-precise element targeting and modification system
 Last modified: August 20, 2025
 -------------------------------------------------------------------*/

(function($) {
    'use strict';

    // Element refinement system state
    window.vmoElementRefiner = {
        selectedElement: null,
        selectedElementPath: null,
        isSelectionMode: false,
        originalContent: null,
        highlightOverlay: null
    };

    // === ELEMENT SELECTION MODE ===
    window.enableElementSelection = function() {
        window.vmoElementRefiner.isSelectionMode = true;
        
        // Add selection cursor
        $('body').addClass('vmo-element-selection-mode');
        
        // Show selection overlay
        showSelectionOverlay();
        
        // Add hover effects to all elements
        $('.vmo-block *').on('mouseenter.elementSelect', function(e) {
            e.stopPropagation();
            highlightElement($(this));
        }).on('mouseleave.elementSelect', function() {
            clearHighlight();
        }).on('click.elementSelect', function(e) {
            e.preventDefault();
            e.stopPropagation();
            selectElement($(this));
            disableElementSelection();
        });
        
        if (window.showToast) {
            window.showToast('Click on any element to select it for refinement', 'info', true);
        }
    };

    window.disableElementSelection = function() {
        window.vmoElementRefiner.isSelectionMode = false;
        $('body').removeClass('vmo-element-selection-mode');
        
        // Remove event listeners
        $('.vmo-block *').off('.elementSelect');
        
        clearHighlight();
        hideSelectionOverlay();
        
        if (window.hideToast) {
            window.hideToast(true);
        }
    };

    // === ELEMENT HIGHLIGHTING ===
    function highlightElement($element) {
        clearHighlight();
        
        const rect = $element[0].getBoundingClientRect();
        const scrollTop = $(window).scrollTop();
        const scrollLeft = $(window).scrollLeft();
        
        if (!window.vmoElementRefiner.highlightOverlay) {
            window.vmoElementRefiner.highlightOverlay = $(`
                <div id="vmo-element-highlight" style="
                    position: absolute;
                    pointer-events: none;
                    z-index: 10000;
                    border: 3px solid #007cba;
                    background: rgba(0, 123, 186, 0.1);
                    border-radius: 4px;
                "></div>
            `);
            $('body').append(window.vmoElementRefiner.highlightOverlay);
        }
        
        window.vmoElementRefiner.highlightOverlay.css({
            top: rect.top + scrollTop - 3,
            left: rect.left + scrollLeft - 3,
            width: rect.width + 6,
            height: rect.height + 6,
            display: 'block'
        });
    }

    function clearHighlight() {
        if (window.vmoElementRefiner.highlightOverlay) {
            window.vmoElementRefiner.highlightOverlay.hide();
        }
    }

    // === ELEMENT SELECTION ===
    function selectElement($element) {
        window.vmoElementRefiner.selectedElement = $element;
        window.vmoElementRefiner.selectedElementPath = getElementPath($element);
        window.vmoElementRefiner.originalContent = $element[0].outerHTML;
        
        // Keep element highlighted
        highlightElement($element);
        
        // Show element info
        const tagName = $element[0].tagName.toLowerCase();
        const elementClass = $element.attr('class') || '';
        const elementId = $element.attr('id') || '';
        
        let elementDescription = `<${tagName}`;
        if (elementId) elementDescription += `#${elementId}`;
        if (elementClass) elementDescription += `.${elementClass.split(' ')[0]}`;
        elementDescription += `>`;
        
        if (window.showToast) {
            window.showToast(`Selected: ${elementDescription}`, 'success', true);
        }
        
        // Emit event for modal integration
        $(document).trigger('elementSelected.vmo', {
            element: $element,
            path: window.vmoElementRefiner.selectedElementPath,
            description: elementDescription
        });
        
        console.log('[VMO Element Refiner] Selected element:', {
            element: $element[0],
            path: window.vmoElementRefiner.selectedElementPath,
            content: window.vmoElementRefiner.originalContent
        });
    }

    // === SELECTION OVERLAY ===
    function showSelectionOverlay() {
        if ($('#vmo-selection-overlay').length) return;
        
        const overlay = $(`
            <div id="vmo-selection-overlay" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 123, 186, 0.05);
                z-index: 9999;
                pointer-events: none;
            ">
                <div style="
                    position: absolute;
                    top: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    background: white;
                    padding: 15px 25px;
                    border-radius: 8px;
                    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
                    pointer-events: auto;
                ">
                    <div style="font-weight: bold; color: #333; margin-bottom: 5px;">🎯 Element Selection Mode</div>
                    <div style="font-size: 14px; color: #666;">Hover over elements and click to select</div>
                    <button onclick="disableElementSelection()" style="
                        margin-top: 10px;
                        padding: 5px 15px;
                        background: #7c5cff;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        cursor: pointer;
                        font-size: 12px;
                    ">Cancel</button>
                </div>
            </div>
        `);
        
        $('body').append(overlay);
    }

    function hideSelectionOverlay() {
        $('#vmo-selection-overlay').remove();
    }

    // === ELEMENT PATH GENERATION ===
    function getElementPath($element) {
        let path = [];
        let current = $element[0];
        
        while (current && current.tagName) {
            let selector = current.tagName.toLowerCase();
            
            if (current.id) {
                selector += `#${current.id}`;
                path.unshift(selector);
                break; // ID is unique, we can stop here
            } else if (current.className) {
                const classes = current.className.split(' ').filter(c => c.trim());
                if (classes.length > 0) {
                    selector += `.${classes[0]}`;
                }
            }
            
            // Add nth-child if needed for specificity
            const siblings = Array.from(current.parentNode?.children || [])
                .filter(el => el.tagName === current.tagName);
            if (siblings.length > 1) {
                const index = siblings.indexOf(current) + 1;
                selector += `:nth-child(${index})`;
            }
            
            path.unshift(selector);
            current = current.parentNode;
            
            // Stop at section level
            if (current?.className?.includes('vmo-block')) {
                break;
            }
        }
        
        return path.join(' > ');
    }

    // === ELEMENT-SPECIFIC REFINEMENT ===
    window.refineSelectedElement = function(refinementPrompt, mediaUrl = null) {
        if (!window.vmoElementRefiner.selectedElement) {
            if (window.showToast) {
                window.showToast('No element selected. Click "Select Element" first.', 'error');
            }
            return;
        }
        
        const $element = window.vmoElementRefiner.selectedElement;
        const elementContent = $element[0].outerHTML;
        const elementPath = window.vmoElementRefiner.selectedElementPath;
        
        // Find which section this element belongs to
        const $section = $element.closest('.vmo-block');
        const sectionIndex = $('.vmo-block').index($section);
        
        if (sectionIndex === -1) {
            if (window.showToast) {
                window.showToast('Could not find element section.', 'error');
            }
            return;
        }
        
        if (window.showToast) {
            window.showToast('Refining selected element...', 'info', true, true);
        }
        
        // Create ultra-precise refinement prompt
        const precisionPrompt = createElementRefinementPrompt(
            refinementPrompt, 
            elementContent, 
            elementPath, 
            mediaUrl
        );
        
        // Use the enhanced refinement system with element targeting
        if (typeof window.refineWithUserEdit === 'function') {
            window.refineWithUserEdit(precisionPrompt, sectionIndex, function(success) {
                if (success) {
                    // Clear selection after successful refinement
                    clearSelection();
                    if (window.showToast) {
                        window.showToast('Element refined successfully!', 'success');
                    }
                }
            });
        }
    };

    // === PRECISION PROMPT CREATION ===
    function createElementRefinementPrompt(userPrompt, elementContent, elementPath, mediaUrl) {
        // Get element context for enhanced precision
        const $element = $(elementPath);
        const elementTag = $element[0] ? $element[0].tagName.toLowerCase() : 'unknown';
        const elementClasses = $element.attr('class') || 'none';
        const elementId = $element.attr('id') || 'none';
        const elementIndex = $element.index();
        const totalSiblings = $element.siblings().length;
        
        let prompt = `🎯 ULTRA-PRECISE ELEMENT-SPECIFIC REFINEMENT

📍 TARGET ELEMENT IDENTIFICATION:
• Path: ${elementPath}
• Tag: <${elementTag}>
• Classes: ${elementClasses}
• ID: ${elementId}
• Position: Element #${elementIndex + 1} of ${totalSiblings + 1} siblings
• Parent: ${$element.parent()[0] ? $element.parent()[0].tagName.toLowerCase() : 'unknown'}

📋 CURRENT ELEMENT HTML (EXACT TARGET):
\`\`\`html
${elementContent.trim()}
\`\`\`

🎯 USER REFINEMENT REQUEST: ${userPrompt}`;

        if (mediaUrl) {
            prompt += `\n\n📸 MEDIA TO INTEGRATE: ${mediaUrl}`;
        }

        prompt += `

🚨 SURGICAL PRECISION PROTOCOL:
1. ⚡ TARGET ONLY: Modify exclusively the <${elementTag}> element at ${elementPath}
2. 🎯 SCOPE LIMIT: Changes apply ONLY to this specific element (child #${elementIndex + 1})
3. 🔒 PRESERVE ALL: Keep 100% of other section content unchanged
4. 📍 MAINTAIN STRUCTURE: Preserve element position and hierarchy
5. 🛡️ PROTECT SIBLINGS: All ${totalSiblings} sibling elements must remain identical
6. 🚫 NO ADDITIONS: Do not add new elements outside the target
7. 🚫 NO PARENT MODS: Do not modify parent or ancestor elements
8. ✨ CONTENT FOCUS: Only modify content/attributes/styling within target element
9. 🎨 MEDIA INTEGRATION: If requested, embed media within target element boundaries only
10. 🔍 PRECISION CHECK: Ensure only the specified element reflects changes

⚠️ CRITICAL: Return the complete section HTML with ONLY the target element modified.
All other elements must remain byte-for-byte identical.

🎯 MODIFICATION ZONE (ONLY MODIFY BETWEEN MARKERS):
════════════════════════════════════════════════════════════════
TARGET: ${elementPath} (${elementTag}.${elementClasses})
════════════════════════════════════════════════════════════════
${elementContent}
════════════════════════════════════════════════════════════════
END TARGET ZONE
════════════════════════════════════════════════════════════════`;

        return prompt;
    }

    // === SELECTION MANAGEMENT ===
    function clearSelection() {
        window.vmoElementRefiner.selectedElement = null;
        window.vmoElementRefiner.selectedElementPath = null;
        window.vmoElementRefiner.originalContent = null;
        clearHighlight();
        
        if (window.vmoElementRefiner.highlightOverlay) {
            window.vmoElementRefiner.highlightOverlay.remove();
            window.vmoElementRefiner.highlightOverlay = null;
        }
    }

    window.clearElementSelection = clearSelection;
    window.getElementPath = getElementPath;
    
    // Expose refinement function
    window.refineSelectedElement = function(element) {
        if (element && element.length) {
            selectElement(element);
            if (window.showToast) {
                window.showToast('Element ready for refinement', 'info');
            }
        }
    };

    // === CSS FOR ELEMENT SELECTION MODE ===
    $('<style>').prop('type', 'text/css').html(`
        .vmo-element-selection-mode {
            cursor: crosshair !important;
        }
        
        .vmo-element-selection-mode .vmo-block * {
            cursor: crosshair !important;
        }
        
        .vmo-element-selection-mode .vmo-block *:hover {
            box-shadow: 0 0 0 3px rgba(0, 123, 186, 0.3) !important;
        }
        
        #vmo-element-highlight {
            box-shadow: 0 0 0 1px rgba(0, 123, 186, 0.5);
            transition: all 0.15s ease;
        }
    `).appendTo('head');

    console.log('[VMO Element Refiner] System loaded');

})(jQuery);
