// vmo-refine.js — SURGICAL Refinement System (No More Page Destruction!)

// === UTILITIES ===

// Returns the full page HTML with all SECTION comments intact
window.getFullPageHtmlWithSections = function() {
    if (!window.vmoState?.blocks) return '';
    return window.vmoState.blocks.map(b => b.html.trim()).join('\n\n');
};

// Splits a big HTML string into blocks at SECTION comments
window.splitSectionsFromHtml = function(html) {
    const matches = html.split(/(?=<!--\s*SECTION\s*\d+.*?-->)/i);
    return matches.filter(s => s.trim().startsWith('<!-- SECTION'));
};

// 🔧 NEW: Get specific section HTML only
window.getSectionHtml = function(sectionIndex) {
    if (!window.vmoState?.blocks?.[sectionIndex]) return '';
    return window.vmoState.blocks[sectionIndex].html;
};

// 🔧 NEW: SURGICAL section update (like inspector's commit function)
function updateSpecificSection(sectionIndex, newHtml) {
    if (!window.vmoState?.blocks?.[sectionIndex]) return false;
    
    // Save current state for undo
    if (window.pushUndo) {
        window.pushUndo();
    }
    
    // Update only the specific section
    window.vmoState.blocks[sectionIndex].html = newHtml.trim();
    
    // Re-render only if needed
    if (window.renderBlocks) {
        window.renderBlocks();
    }
    
    // Sync and mark as unsaved
    if (window.vmoSyncLastContent) window.vmoSyncLastContent();
    window.isUnsaved = true;
    
    return true;
}

// === SURGICAL REFINEMENT FUNCTION ===
// 🔧 ENHANCED: Smart section targeting with user selection
window.refineWithUserEdit = function(userPrompt, targetSectionIndex = null, callback) {
    if (!userPrompt?.trim()) {
        window.showToast('Please enter refinement instructions.', 'error');
        if (typeof callback === 'function') callback(false);
        return;
    }

    console.log('[VMO] Starting SURGICAL refinement:', userPrompt);

    // Enhanced section detection
    const executeRefinement = (sectionIndex) => {
        const sectionHtml = window.getSectionHtml(sectionIndex);
        if (!sectionHtml) {
            window.showToast(`Section ${sectionIndex + 1} not found.`, 'error');
            if (typeof callback === 'function') callback(false);
            return;
        }
        
        // SAFETY: Check if vmo_ajax is defined
        if (typeof vmo_ajax === 'undefined' || !vmo_ajax.ajaxurl) {
            window.showToast('System error: Cannot connect to server', 'error');
            if (typeof callback === 'function') callback(false);
            return;
        }
        
        window.showToast(`Refining section ${sectionIndex + 1}...`, 'info', true, true);

        // 🔧 ULTRA-SURGICAL APPROACH: Enhanced precision prompts
        const refinementPrompt = `You are a PRECISION WEB SURGEON. You perform ONLY the specific modifications requested.

🚨 CRITICAL SURGICAL RULES:
1. MODIFY ONLY what the user SPECIFICALLY requests
2. PRESERVE ALL existing content, styling, classes, IDs, and structure
3. Return ONLY the EXACT same section with MINIMAL changes
4. DO NOT add new sections, containers, or unrelated elements
5. DO NOT add "Welcome to our website" or generic content
6. DO NOT create multiple variations or duplicates
7. Maintain ALL existing CSS classes and mobile responsiveness
8. Keep the SAME section structure and hierarchy

TARGET SECTION TO REFINE:
${sectionHtml}

PRECISION REQUEST: ${userPrompt}

INSTRUCTIONS:
- Apply ONLY the requested change to the above section
- Keep ALL existing content and structure intact
- Return the same section with MINIMAL modifications
- DO NOT add unrelated content or multiple variations
- Maintain the same SECTION comment format`;

        const runRefine = () => $.post(vmo_ajax.ajaxurl, {
            action: 'vmo_refine_content',
            security: vmo_ajax.nonce,
            prompt: refinementPrompt,
            current_html: sectionHtml,
            component_state: JSON.stringify(window.vmoState?.componentState || {}),
            current_page: window.vmoState?.currentPage || '',
            project_id: window.currentProjectId || window.vmoCurrentProjectId || 0,
            post_id: window.currentProjectId || window.vmoCurrentProjectId || 0,
            section_index: sectionIndex,
            agent_type: 'precision_refinement'
        }, function(res) {
            window.hideToast(true);
            console.log('[VMO] Surgical refinement response:', res);

            if (res.success && res.data && res.data.html) {
                // 🔧 SURGICAL UPDATE: Only update the target section
                const success = updateSpecificSection(sectionIndex, res.data.html);
                
                if (success) {
                    window.showToast(`Section ${sectionIndex + 1} refined successfully!`, 'success');
                    if (typeof callback === 'function') callback(true);
                } else {
                    window.showToast('Failed to update section.', 'error');
                    if (typeof callback === 'function') callback(false);
                }
            } else {
                // Handle errors appropriately
                if (res.data?.code === 'insufficient_tokens') {
                    window.showToast('Insufficient balance to refine this section. Please upgrade your plan or purchase an add-on.', 'error');
                } else {
                    window.showToast(res.data?.message || 'Refinement failed. Please try again.', 'error');
                }
                console.error('[VMO] Refinement failed:', res);
                if (typeof callback === 'function') callback(false);
            }
        }).fail(function(xhr, text, err) {
            window.hideToast(true);
            console.error('[VMO] AJAX error during refinement:', xhr, text, err);
            window.showToast('Server error occurred. Please try again.', 'error');
            if (typeof callback === 'function') callback(false);
        });
        
        if (typeof window.vmoEnsureConsultationReady === 'function') {
            window.vmoEnsureConsultationReady(runRefine);
        } else {
            runRefine();
        }
    };

    // Smart section targeting
    if (targetSectionIndex !== null) {
        // Section explicitly specified
        executeRefinement(targetSectionIndex);
    } else {
        // Auto-detect or let user choose
        const detectedSection = window.detectTargetSection(userPrompt);
        if (detectedSection !== null) {
            // Section detected from prompt
            executeRefinement(detectedSection);
        } else {
            // Show section chooser for user selection
            window.showSectionChooser(userPrompt, executeRefinement);
        }
    }
};

// === TARGETED SECTION REFINEMENT ===
window.refineSectionBlock = function(sectionIndex, userEdit, callback) {
    window.refineWithUserEdit(userEdit, sectionIndex, callback);
};

// === BACKGROUND INSERTION (SAFE) ===
window.addBackgroundToSection = function(sectionIndex, imageDescription) {
    const prompt = `Add a background image with description: "${imageDescription}". Apply it using CSS background-image property with background-size: cover and background-position: center. Preserve all existing content and styling. Use [GENERATED_IMAGE: ${imageDescription}] placeholder for the image URL.`;
    window.refineWithUserEdit(prompt, sectionIndex);
};

// === LOGO INSERTION (SAFE) ===
window.addLogoToSection = function(sectionIndex, position = 'top-right', logoDescription = 'company logo') {
    const prompt = `Add a logo positioned in the ${position} corner. Use CSS positioning (position: absolute, top/right/left/bottom values). Size should be appropriate (around 60-100px). Use [GENERATED_IMAGE: ${logoDescription}] placeholder. Do not disturb existing content.`;
    window.refineWithUserEdit(prompt, sectionIndex);
};

// === SMART SECTION DETECTION & TARGETING ===
window.detectTargetSection = function(prompt) {
    // Extract section numbers from various prompt formats
    const patterns = [
        /section\s*(\d+)/i,
        /section\s*#(\d+)/i,
        /(\d+)(?:st|nd|rd|th)?\s*section/i,
        /in\s*section\s*(\d+)/i,
        /bottom\s*section/i, // Special case for "bottom" = last section
        /last\s*section/i,   // Special case for "last" = last section
        /footer/i,           // Footer usually means last section
        /contact\s*section/i // Contact forms often in last section
    ];
    
    for (const pattern of patterns) {
        const match = prompt.match(pattern);
        if (match) {
            if (pattern.source.includes('bottom|last|footer')) {
                // Return last section index
                return (window.vmoState?.blocks?.length || 1) - 1;
            }
            return parseInt(match[1]) - 1; // Convert to 0-based index
        }
    }
    
    // Smart content-based detection
    if (prompt.toLowerCase().includes('contact form')) {
        // Contact forms typically go in the last section
        return (window.vmoState?.blocks?.length || 1) - 1;
    }
    
    if (prompt.toLowerCase().includes('hero') || prompt.toLowerCase().includes('header')) {
        return 0; // Hero/header is typically first section
    }
    
    return null; // Let user choose
};

// === SECTION CHOOSER UI ===
window.showSectionChooser = function(prompt, callback) {
    if (!window.vmoState?.blocks || window.vmoState.blocks.length <= 1) {
        // Only one section, use it
        callback(0);
        return;
    }
    
    // Highlight all sections
    window.highlightAllSections();
    
    const sectionOptions = window.vmoState.blocks.map((block, index) => {
        // Extract a preview of the section
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = block.html;
        const textContent = tempDiv.textContent || tempDiv.innerText || '';
        const preview = textContent.substring(0, 50) + (textContent.length > 50 ? '...' : '');
        return `<option value="${index}">Section ${index + 1}: ${preview}</option>`;
    }).join('');
    
    const chooserHtml = `
        <div id="vmo-section-chooser" style="
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            z-index: 10000;
            max-width: 450px;
            width: 90%;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        ">
            <h3 style="margin-top: 0; color: #333; font-size: 18px;">🎯 Choose Target Section</h3>
            <p style="font-size: 14px; color: #666; margin: 10px 0; line-height: 1.4;">
                <strong>Refinement Request:</strong><br>
                "${prompt.substring(0, 120)}${prompt.length > 120 ? '...' : ''}"
            </p>
            <div style="margin: 15px 0;">
                <label style="display: block; font-size: 13px; color: #555; margin-bottom: 5px;">
                    Select the section to refine (sections are highlighted in the preview):
                </label>
                <select id="vmo-target-section" style="
                    width: 100%; 
                    padding: 12px; 
                    border: 2px solid #007cba; 
                    border-radius: 6px; 
                    font-size: 14px;
                    background: white;
                ">
                    ${sectionOptions}
                </select>
            </div>
            <div style="background: #f8f9fa; padding: 12px; border-radius: 6px; margin: 15px 0; font-size: 12px; color: #666;">
                💡 <strong>Tip:</strong> The AI will only modify the selected section. This prevents unwanted changes to other parts of your website.
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <button id="vmo-cancel-chooser" style="
                    margin-right: 12px; 
                    padding: 10px 20px; 
                    border: 1px solid #ccc; 
                    background: white; 
                    border-radius: 6px;
                    cursor: pointer;
                ">Cancel</button>
                <button id="vmo-confirm-chooser" style="
                    padding: 10px 20px; 
                    background: #007cba; 
                    color: white; 
                    border: none; 
                    border-radius: 6px;
                    cursor: pointer;
                    font-weight: 500;
                ">🔧 Refine This Section</button>
            </div>
        </div>
        <div id="vmo-chooser-overlay" style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: 9999;
        "></div>
    `;
    
    $('body').append(chooserHtml);
    
    // Highlight selected section on change
    $('#vmo-target-section').on('change', function() {
        const selectedIndex = parseInt($(this).val());
        window.highlightSpecificSection(selectedIndex);
    });
    
    // Initial highlight of first section
    window.highlightSpecificSection(0);
    
    $('#vmo-confirm-chooser').on('click', function() {
        const selectedSection = parseInt($('#vmo-target-section').val());
        $('#vmo-section-chooser, #vmo-chooser-overlay').remove();
        window.clearSectionHighlights();
        callback(selectedSection);
    });
    
    $('#vmo-cancel-chooser, #vmo-chooser-overlay').on('click', function() {
        $('#vmo-section-chooser, #vmo-chooser-overlay').remove();
        window.clearSectionHighlights();
        if (window.showToast) {
            window.showToast('Refinement cancelled', 'info');
        }
    });
};

// === VISUAL SECTION HIGHLIGHTING ===
window.highlightAllSections = function() {
    $('.vmo-block').each(function(index) {
        $(this).css({
            'outline': '3px solid #007cba',
            'outline-offset': '2px',
            'position': 'relative'
        }).attr('data-section-index', index);
        
        // Add section number badge
        if (!$(this).find('.vmo-section-badge').length) {
            $(this).prepend(`
                <div class="vmo-section-badge" style="
                    position: absolute;
                    top: -15px;
                    left: -15px;
                    background: #007cba;
                    color: white;
                    padding: 4px 8px;
                    border-radius: 12px;
                    font-size: 12px;
                    font-weight: bold;
                    z-index: 100;
                ">Section ${index + 1}</div>
            `);
        }
    });
};

window.highlightSpecificSection = function(sectionIndex) {
    // Clear previous highlights
    $('.vmo-block').css({
        'outline': '2px solid #ddd',
        'outline-offset': '1px'
    });
    
    // Highlight selected section
    $(`.vmo-block[data-section-index="${sectionIndex}"]`).css({
        'outline': '4px solid #28a745',
        'outline-offset': '3px'
    });
};

window.clearSectionHighlights = function() {
    $('.vmo-block').css({
        'outline': '',
        'outline-offset': ''
    }).removeAttr('data-section-index');
    $('.vmo-section-badge').remove();
};

// === LEGACY COMPATIBILITY ===
window.refineMultipleSections = function(userPrompt, callback) {
    // For multi-section requests, detect target or ask user
    const targetSection = window.detectTargetSection(userPrompt);
    window.refineWithUserEdit(userPrompt, targetSection, callback);
};

// 🔧 FIX: Safe AI communication
window.sendRefinementToAI = function(prompt, sectionIndex = null) {
    window.refineWithUserEdit(prompt, sectionIndex);
};

console.log('[VMO] SURGICAL refinement system loaded - no more page destruction!');
