// VMO AI Agents - Dedicated AI agents for specific functions
// Separates content generation, refinement, and media integration

(function($) {
    'use strict';

    // === AI AGENT SYSTEM ===
    
    window.VMOAIAgents = {
        // Content Generation Agent - Focused only on creating new pages
        contentGenerator: {
            getPrompt: function(userRequest, consultationData = null) {
                return `You are the VMO Content Generation Agent. Your ONLY job is to create complete, mobile-responsive websites from user descriptions.

USER REQUEST: "${userRequest}"

REQUIREMENTS:
1. Generate COMPLETE HTML pages with proper structure
2. MUST be mobile-first and responsive for all screen sizes
3. Use proper viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1.0">
4. Include mobile-optimized CSS with media queries
5. Ensure perfect display on phones, tablets, and desktops
6. Use flexible layouts (flexbox, CSS Grid) that adapt to any screen
7. Text must be readable on mobile (minimum 16px font-size)
8. Touch-friendly buttons (minimum 44px touch targets)
9. Proper spacing and margins for mobile usability

STRUCTURE:
- Start with DOCTYPE and full HTML document
- Include comprehensive CSS for mobile responsiveness
- Create semantic HTML structure
- Add proper SECTION comments for each major section
- Include meta tags for proper mobile rendering

${consultationData ? `BUSINESS CONTEXT: ${JSON.stringify(consultationData)}` : ''}

Generate a complete, mobile-responsive website that works perfectly on all devices.`;
            }
        },

        // Refinement Agent - Ultra-Surgical Precision (No Extra Content)
        refinementAgent: {
            getPrompt: function(userRequest, sectionHtml, sectionIndex) {
                return `🔬 VMO PRECISION REFINEMENT AGENT - SURGICAL MODE ACTIVATED

USER'S EXACT REQUEST: "${userRequest}"

CURRENT SECTION TO REFINE:
${sectionHtml}

🚨 ULTRA-CRITICAL SURGICAL RULES:
1. MODIFY ONLY what the user SPECIFICALLY requested
2. PRESERVE 100% of existing content unless explicitly asked to change it
3. Return ONLY the SAME section with MINIMAL modifications
4. DO NOT add new sections, welcome messages, or unrelated content
5. DO NOT create multiple variations or duplicate elements
6. DO NOT add "Welcome to our website" or generic content
7. Maintain ALL existing CSS classes, IDs, and structure
8. Keep mobile responsiveness intact

❌ FORBIDDEN ACTIONS:
- Adding new sections or containers not in the original
- Creating welcome messages or introductory content
- Duplicating elements (e.g., creating 2 contact forms when asked for 1)
- Changing unrelated parts of the section
- Removing existing content unless explicitly requested

✅ ALLOWED ACTIONS:
- Add/modify ONLY what user specifically requests
- Change colors, fonts, or styling as requested
- Add individual elements (forms, buttons, images) to existing structure
- Modify existing text content if explicitly requested

EXAMPLE SCENARIOS:
❌ BAD: User asks "add contact form" → AI adds welcome section + header + 2 contact forms
✅ GOOD: User asks "add contact form" → AI adds ONE contact form to the existing section

This is MICROSURGERY on web code. Touch only what's requested. Return the exact same section structure with only the requested changes.

SECTION INDEX: ${sectionIndex + 1}`;
            }
        },

        // Media Integration Agent - Focused only on integrating media
        mediaIntegrator: {
            getPrompt: function(userRequest, mediaUrl, mediaType, targetHtml) {
                return `You are the VMO Media Integration Agent. Your ONLY job is to integrate media into existing content.

USER REQUEST: "${userRequest}"
MEDIA URL: ${mediaUrl}
MEDIA TYPE: ${mediaType}
TARGET CONTENT: ${targetHtml}

REQUIREMENTS:
1. Integrate the specified media into the existing content
2. Maintain mobile responsiveness for all media
3. Use proper responsive image/video techniques
4. Ensure media scales properly on all devices
5. Add appropriate CSS for mobile optimization
6. Keep existing structure and content intact
7. Only add/modify what's needed for media integration

MOBILE MEDIA OPTIMIZATION:
- Use responsive images with srcset if needed
- Ensure videos are mobile-friendly
- Proper aspect ratios for different screens
- Touch-friendly media controls
- Optimized loading for mobile connections

Return the modified HTML with properly integrated, mobile-responsive media.`;
            }
        }
    };

    // === AGENT EXECUTION FUNCTIONS ===

    // Execute Content Generation Agent
    window.executeContentGeneration = function(userPrompt, consultationData, callback) {
        console.log('[VMO AI Agents] Executing Content Generation Agent');
        
        const agentPrompt = window.VMOAIAgents.contentGenerator.getPrompt(userPrompt, consultationData);
        
        // Show generation toast
        if (window.showToast) {
            window.showToast('Generating...', 'info', true);
        }

        // Call generation endpoint with specialized prompt
        // ✅ INCREASED TIMEOUT: 10 minutes for complex generation operations
        $.ajax({
            url: vmo_ajax.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmo_generate_content',
                security: vmo_ajax.nonce,
                prompt: agentPrompt,
                project_id: window.currentProjectId || 0,
                post_id: window.currentProjectId || 0,
                agent_type: 'content_generator'
            },
            timeout: 600000, // ✅ 10 minutes for generation (was 2 minutes)
            success: function(response) {
                console.log('[VMO AI Agents] Content generation response:', response);
                
                if (response.success && response.data) {
                    const draftId = parseInt(response.data.draft_id || response.data.post_id || response.data.website_draft?.post_id || 0, 10);
                    if (draftId > 0) {
                        window.currentProjectId = draftId;
                    }
                    if (response.data.grapes_plan && window.vmoGrapesAdapter && typeof window.vmoGrapesAdapter.composeWebsite === 'function') {
                        try {
                            const extracted = consultationData?.extracted_information || consultationData?.extractedInformation || {};
                            const composeContext = {
                                phoneNumber: extracted.business_phone || extracted.phone || extracted.supportPhone || '',
                                emailAddress: extracted.business_email || extracted.businessEmail || extracted.email || extracted.supportEmail || ''
                            };
                            const composed = window.vmoGrapesAdapter.composeWebsite(response.data.grapes_plan, composeContext);
                            if (composed && composed.ok && composed.html) {
                                response.data.html = composed.html;
                                response.data.render_engine = composed.metadata?.render_engine || 'react18';

                                // ── Builder Intelligence: JS QA Critic ──
                                vmoRunQACritic(composed.html, response.data.qa_report || null);

                            } else {
                                if (window.showToast) {
                                    window.showToast('❌ GrapesJS frontend composition failed.', 'error');
                                }
                                if (callback) callback(false, response);
                                return;
                            }
                        } catch (composeError) {
                            console.error('[VMO AI Agents] Grapes composition error:', composeError);
                            if (window.showToast) {
                                window.showToast('❌ GrapesJS frontend composition failed.', 'error');
                            }
                            if (callback) callback(false, response);
                            return;
                        }
                    }

                    if (window.showToast) {
                        window.showToast('Website generated successfully!', 'success');
                    }
                    if (callback) callback(true, response.data);
                } else {
                    console.error('[VMO AI Agents] Generation failed:', response);
                    if (window.showToast) {
                        window.showToast('❌ Generation failed. Please try again.', 'error');
                    }
                    if (callback) callback(false, response);
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMO AI Agents] Generation error:', {xhr, status, error});
                if (window.showToast) {
                    window.showToast('❌ Generation failed. Please check connection.', 'error');
                }
                if (callback) callback(false, {error: error});
            }
        });
    };

    // Execute Refinement Agent
    window.executeRefinement = function(userPrompt, sectionIndex, callback) {
        console.log('[VMO AI Agents] Executing Refinement Agent for section', sectionIndex);
        
        if (!window.vmoState?.blocks?.[sectionIndex]) {
            console.error('[VMO AI Agents] Invalid section index:', sectionIndex);
            if (callback) callback(false, {error: 'Invalid section'});
            return;
        }

        const sectionHtml = window.vmoState.blocks[sectionIndex].html;
        const agentPrompt = window.VMOAIAgents.refinementAgent.getPrompt(userPrompt, sectionHtml, sectionIndex);
        
        // Show refinement toast
        if (window.showToast) {
            window.showToast('Refining...', 'info', true);
        }

        // Call refinement endpoint with specialized prompt
        $.ajax({
            url: vmo_ajax.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmo_refine_content',
                security: vmo_ajax.nonce,
                prompt: agentPrompt,
                section_index: sectionIndex,
                agent_type: 'refinement_agent'
            },
            timeout: 300000, // ✅ 5 minutes for refinement (was 1 minute)
            success: function(response) {
                console.log('[VMO AI Agents] Refinement response:', response);
                
                if (response.success && response.data) {
                    // Update the specific section
                    if (window.updateSpecificSection) {
                        window.updateSpecificSection(sectionIndex, response.data.html);
                    }
                    
                    if (window.showToast) {
                        window.showToast('Content refined successfully!', 'success');
                    }
                    if (callback) callback(true, response.data);
                } else {
                    console.error('[VMO AI Agents] Refinement failed:', response);
                    if (window.showToast) {
                        window.showToast('❌ Refinement failed. Please try again.', 'error');
                    }
                    if (callback) callback(false, response);
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMO AI Agents] Refinement error:', {xhr, status, error});
                if (window.showToast) {
                    window.showToast('❌ Refinement failed. Please check connection.', 'error');
                }
                if (callback) callback(false, {error: error});
            }
        });
    };

    // Execute Media Integration Agent
    window.executeMediaIntegration = function(userPrompt, mediaUrl, mediaType, targetSectionIndex, callback) {
        console.log('[VMO AI Agents] Executing Media Integration Agent');
        
        if (!window.vmoState?.blocks?.[targetSectionIndex]) {
            console.error('[VMO AI Agents] Invalid target section:', targetSectionIndex);
            if (callback) callback(false, {error: 'Invalid target section'});
            return;
        }

        const targetHtml = window.vmoState.blocks[targetSectionIndex].html;
        const agentPrompt = window.VMOAIAgents.mediaIntegrator.getPrompt(userPrompt, mediaUrl, mediaType, targetHtml);
        
        // Show integration toast
        if (window.showToast) {
            window.showToast('Integrating media...', 'info', true);
        }

        // Call media integration endpoint with specialized prompt
        $.ajax({
            url: vmo_ajax.ajaxurl,
            type: 'POST',
            data: {
                action: 'vmo_integrate_media',
                security: vmo_ajax.nonce,
                prompt: agentPrompt,
                media_url: mediaUrl,
                media_type: mediaType,
                section_index: targetSectionIndex,
                agent_type: 'media_integrator'
            },
            timeout: 300000, // ✅ 5 minutes for media integration (was 1 minute)
            success: function(response) {
                console.log('[VMO AI Agents] Media integration response:', response);
                
                if (response.success && response.data) {
                    // Update the specific section
                    if (window.updateSpecificSection) {
                        window.updateSpecificSection(targetSectionIndex, response.data.html);
                    }
                    
                    if (window.showToast) {
                        window.showToast('Media integrated successfully!', 'success');
                    }
                    if (callback) callback(true, response.data);
                } else {
                    console.error('[VMO AI Agents] Media integration failed:', response);
                    if (window.showToast) {
                        window.showToast('❌ Media integration failed. Please try again.', 'error');
                    }
                    if (callback) callback(false, response);
                }
            },
            error: function(xhr, status, error) {
                console.error('[VMO AI Agents] Media integration error:', {xhr, status, error});
                if (window.showToast) {
                    window.showToast('❌ Media integration failed. Please check connection.', 'error');
                }
                if (callback) callback(false, {error: error});
            }
        });
    };

    // Mobile responsiveness utilities
    window.VMOAIAgents.utils = {
        // Ensure mobile-responsive CSS
        getMobileCSS: function() {
            return `
/* Mobile-First Responsive Design */
* {
    box-sizing: border-box;
}

html {
    font-size: 16px; /* Base font size for mobile */
}

body {
    margin: 0;
    padding: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
    line-height: 1.6;
    color: #333;
}

/* Mobile-friendly containers */
.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 16px;
}

/* Responsive images */
img {
    max-width: 100%;
    height: auto;
    display: block;
}

/* Touch-friendly buttons */
button, .btn {
    min-height: 44px;
    min-width: 44px;
    padding: 12px 24px;
    font-size: 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    touch-action: manipulation;
}

/* Responsive typography */
h1 { font-size: 28px; }
h2 { font-size: 24px; }
h3 { font-size: 20px; }
h4 { font-size: 18px; }
p { font-size: 16px; }

/* Tablet styles */
@media (min-width: 768px) {
    html { font-size: 18px; }
    .container { padding: 0 32px; }
    h1 { font-size: 36px; }
    h2 { font-size: 30px; }
    h3 { font-size: 24px; }
}

/* Desktop styles */
@media (min-width: 1024px) {
    html { font-size: 18px; }
    .container { padding: 0 48px; }
    h1 { font-size: 48px; }
    h2 { font-size: 36px; }
    h3 { font-size: 28px; }
}
`;
        },

        // Ensure mobile viewport
        getMobileViewport: function() {
            return '<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">';
        }
    };

    console.log('[VMO AI Agents] Dedicated AI agent system loaded');

    // ═══════════════════════════════════════════
    //  BUILDER INTELLIGENCE — JS QA CRITIC
    // ═══════════════════════════════════════════

    /**
     * Run QA critic on composed HTML. Fires AJAX for server-side deep check
     * and logs the backend strategy QA report. Shows quality badge in builder.
     */
    window.vmoRunQACritic = function(html, backendQA) {
        // Log backend QA report (strategy plan validation)
        if (backendQA) {
            if (backendQA.passed) {
                console.log('[VMO QA] Strategy plan passed all checks ✓');
            } else {
                console.warn('[VMO QA] Strategy plan issues auto-fixed:', backendQA.issues_fixed);
            }
        }

        // Fire async server-side HTML QA critic
        if (typeof vmo_ajax === 'undefined' || !vmo_ajax.ajaxurl) return;

        $.post(vmo_ajax.ajaxurl, {
            action: 'vmo_qa_critic_review',
            nonce: vmo_ajax.nonce,
            html: html
        }, function(resp) {
            if (!resp || !resp.success || !resp.data) return;
            var qa = resp.data;
            console.log('[VMO QA] HTML quality: ' + qa.grade + ' (' + qa.score + '/100)', qa.issues);

            // Show quality badge in builder toolbar
            vmoShowQualityBadge(qa.grade, qa.score, qa.issues);
        }).fail(function() {
            console.warn('[VMO QA] HTML critic request failed (non-blocking)');
        });
    };

    /**
     * Display a quality badge in the builder interface.
     */
    window.vmoShowQualityBadge = function(grade, score, issues) {
        // Remove existing badge
        $('#vmo-qa-badge').remove();

        var gradeColors = { A: '#22c55e', B: '#84cc16', C: '#eab308', D: '#f97316', F: '#ef4444' };
        var color = gradeColors[grade] || '#9fb2c8';

        var badge = $(
            '<div id="vmo-qa-badge" style="' +
            'position:fixed;bottom:20px;right:20px;z-index:9999;' +
            'background:rgba(10,15,22,.95);border:1px solid ' + color + ';' +
            'border-radius:12px;padding:10px 16px;font-family:inherit;' +
            'color:#e6f3ff;font-size:13px;cursor:pointer;' +
            'box-shadow:0 0 20px ' + color + '33;backdrop-filter:blur(12px);' +
            'display:flex;align-items:center;gap:10px;">' +
            '<span style="font-size:22px;font-weight:700;color:' + color + ';">' + grade + '</span>' +
            '<span style="color:#9fb2c8;font-size:12px;">Quality ' + score + '/100</span>' +
            (issues && issues.length ? '<span style="color:#9fb2c8;font-size:11px;">• ' + issues.length + ' issue(s)</span>' : '') +
            '</div>'
        );

        // Click to show details
        badge.on('click', function() {
            if (!issues || !issues.length) {
                if (window.showToast) window.showToast('Website quality: ' + grade + ' (' + score + '/100) — No issues!', 'success');
                return;
            }
            var msgs = issues.map(function(i) { return '• [' + (i.severity || 'info').toUpperCase() + '] ' + i.message; }).join('\n');
            alert('Website QA Report — Grade: ' + grade + ' (' + score + '/100)\n\n' + msgs);
        });

        // Auto-dismiss after 30s
        $('body').append(badge);
        setTimeout(function() { badge.fadeOut(600, function() { badge.remove(); }); }, 30000);
    };

})(jQuery);
