/**
 * VMO AI Website Builder - Multi-Agent Refinement System
 * Allows users to make specific changes without affecting existing content
 * CACHE BUST: Aug 4, 2025 - UNIFIED VERSION
 */
console.log('🤖 VMO Multi-Agent Refinement System UNIFIED v8.0.0 - Loading!');

class VMORefinementAgents {
    constructor() {
        this.activeAgent = null;
        this.refinementContext = null;
        this.isProcessing = false;
        
        this.init();
    }
    
    init() {
        this.bindRefinementEvents();
        this.enhancePromptSystem();
    }
    
    /**
     * Enhance the prompt system with refinement capabilities
     */
    enhancePromptSystem() {
        console.log('🤖 Enhancing prompt system with refinement agents');
        // This method enhances the existing prompt system
        // Implementation can be added later as needed
    }
    
    /**
     * Bind events to the existing prompt/send system
     */
    bindRefinementEvents() {
        // Hook into the existing prompt system
        document.addEventListener('DOMContentLoaded', () => {
            this.enhanceExistingPromptBox();
        });
        
        // Listen for element-specific refinement requests
        document.addEventListener('click', (e) => {
            if (e.target.matches('[data-vmo-refine]')) {
                this.handleElementRefinement(e.target);
            }
        });
    }
    
    /**
     * Enhance the existing prompt/send box with multi-agent capabilities
     */
    enhanceExistingPromptBox() {
        const promptTextarea = document.querySelector('#vmo-prompt-textarea, #vmo-user-input, textarea[name="prompt"]');
        const sendButton = document.querySelector('#vmo-send-btn, .vmo-send-btn, [data-action="send"]');
        
        if (!promptTextarea || !sendButton) {
            console.warn('VMO: Could not find existing prompt system elements');
            return;
        }
        
        // Add multi-agent context indicator
        const contextIndicator = document.createElement('div');
        contextIndicator.id = 'vmo-agent-context';
        contextIndicator.className = 'vmo-agent-context-indicator';
        contextIndicator.innerHTML = `
            <div class="vmo-context-info">
                <span class="vmo-context-agent">🤖 General AI</span>
                <span class="vmo-context-scope">Full Website</span>
            </div>
        `;
        
        promptTextarea.parentNode.insertBefore(contextIndicator, promptTextarea);
        
        // Intercept send button clicks
        const originalSendHandler = sendButton.onclick;
        sendButton.onclick = (e) => {
            e.preventDefault();
            this.handleIntelligentRefinement(promptTextarea.value.trim());
        };
        
        // Add smart suggestions
        this.addSmartSuggestions(promptTextarea);
    }
    
    /**
     * Add smart suggestion system
     */
    addSmartSuggestions(promptTextarea) {
        const suggestionsContainer = document.createElement('div');
        suggestionsContainer.className = 'vmo-smart-suggestions';
        suggestionsContainer.innerHTML = `
            <div class="vmo-suggestions-header">💡 Smart Suggestions:</div>
            <div class="vmo-suggestions-list">
                <button class="vmo-suggestion-btn" data-prompt="Change the background color of the hero section to blue">
                    🎨 Change section background
                </button>
                <button class="vmo-suggestion-btn" data-prompt="Replace the header image with a new AI-generated image">
                    🖼️ Replace specific image
                </button>
                <button class="vmo-suggestion-btn" data-prompt="Add a contact form to the bottom of the page">
                    📝 Add contact form
                </button>
                <button class="vmo-suggestion-btn" data-prompt="Improve the SEO optimization of this page">
                    🔍 Enhance SEO
                </button>
            </div>
        `;
        
        promptTextarea.parentNode.appendChild(suggestionsContainer);
        
        // Bind suggestion clicks
        suggestionsContainer.addEventListener('click', (e) => {
            if (e.target.matches('.vmo-suggestion-btn')) {
                const prompt = e.target.dataset.prompt;
                promptTextarea.value = prompt;
                promptTextarea.focus();
            }
        });
    }
    
    /**
     * Handle intelligent refinement with specialized agents
     */
    async handleIntelligentRefinement(userPrompt) {
        if (!userPrompt || this.isProcessing) return;
        
        this.isProcessing = true;
        this.showProcessingIndicator();
        
        try {
            // Analyze the request to determine the best agent
            const agentAnalysis = this.analyzeUserRequest(userPrompt);
            
            // Set refinement context
            this.refinementContext = {
                originalPrompt: userPrompt,
                agent: agentAnalysis.agent,
                scope: agentAnalysis.scope,
                targetElement: agentAnalysis.targetElement,
                preserveExisting: true
            };
            
            // Update context indicator
            this.updateContextIndicator(agentAnalysis);
            
            // Route to appropriate specialized agent
            await this.deploySpecializedAgent(agentAnalysis);
            
        } catch (error) {
            console.error('VMO Refinement Error:', error);
            this.showToast('❌ Refinement failed. Please try again.', 'error');
        } finally {
            this.isProcessing = false;
            this.hideProcessingIndicator();
        }
    }
    
    /**
     * Analyze user request to determine best agent and scope
     */
    analyzeUserRequest(prompt) {
        const lowercasePrompt = prompt.toLowerCase();
        
        // Agent determination based on keywords
        let agent = 'content_specialist';
        let scope = 'element';
        let targetElement = null;
        
        // Website generation agent
        if (lowercasePrompt.includes('generate') && 
            (lowercasePrompt.includes('website') || lowercasePrompt.includes('page'))) {
            agent = 'website_builder';
            scope = 'page';
        }
        // Media integration agent
        else if (lowercasePrompt.includes('image') || lowercasePrompt.includes('video') || 
                 lowercasePrompt.includes('media') || lowercasePrompt.includes('replace')) {
            agent = 'media_specialist';
            scope = 'media';
        }
        // SEO optimization agent
        else if (lowercasePrompt.includes('seo') || lowercasePrompt.includes('search') || 
                 lowercasePrompt.includes('optimize') || lowercasePrompt.includes('rank')) {
            agent = 'seo_specialist';
            scope = 'seo';
        }
        // Design/styling agent
        else if (lowercasePrompt.includes('color') || lowercasePrompt.includes('style') || 
                 lowercasePrompt.includes('design') || lowercasePrompt.includes('background')) {
            agent = 'design_specialist';
            scope = 'element';
        }
        // Content modification agent
        else if (lowercasePrompt.includes('text') || lowercasePrompt.includes('content') || 
                 lowercasePrompt.includes('headline') || lowercasePrompt.includes('paragraph')) {
            agent = 'content_specialist';
            scope = 'element';
        }
        
        // Determine target element from context
        if (lowercasePrompt.includes('hero') || lowercasePrompt.includes('header')) {
            targetElement = 'hero-section';
        } else if (lowercasePrompt.includes('footer')) {
            targetElement = 'footer-section';
        } else if (lowercasePrompt.includes('navigation') || lowercasePrompt.includes('menu')) {
            targetElement = 'navigation';
        }
        
        return {
            agent,
            scope,
            targetElement,
            confidence: this.calculateConfidence(lowercasePrompt, agent)
        };
    }
    
    /**
     * Calculate confidence score for agent selection
     */
    calculateConfidence(prompt, agent) {
        const agentKeywords = {
            website_builder: ['generate', 'create', 'build', 'website', 'page'],
            media_specialist: ['image', 'video', 'media', 'replace', 'photo'],
            seo_specialist: ['seo', 'search', 'optimize', 'rank', 'google'],
            design_specialist: ['color', 'style', 'design', 'background', 'layout'],
            content_specialist: ['text', 'content', 'headline', 'paragraph', 'copy']
        };
        
        const keywords = agentKeywords[agent] || [];
        const matchCount = keywords.filter(keyword => prompt.includes(keyword)).length;
        
        return Math.min((matchCount / keywords.length) * 100, 100);
    }

    getProjectId() {
        return window.currentProjectId || window.vmoCurrentProjectId || 0;
    }

    getCurrentProjectHTML() {
        const previewFrame = document.getElementById('vmo-preview-iframe');
        if (previewFrame?.contentDocument?.documentElement) {
            return previewFrame.contentDocument.documentElement.outerHTML;
        }
        const contentArea = document.getElementById('vmo-website-content');
        return contentArea ? contentArea.innerHTML : '';
    }

    appendProjectContext(formData) {
        const projectId = this.getProjectId();
        if (projectId) {
            formData.append('project_id', projectId);
            formData.append('post_id', projectId);
        }
        formData.append('current_content', this.getCurrentProjectHTML());
        formData.append('component_state', JSON.stringify(window.vmoState?.componentState || window.vmoState?.component_state || {}));
        formData.append('standalone_runtime_required', 'true');
        formData.append('editing_surface', 'vmo_internal_builder_template');
        return formData;
    }

    normalizeSelector(selector, fallback = 'section') {
        if (!selector || selector === 'auto-detect') {
            return fallback;
        }
        const presets = {
            'hero-section': '[data-vmo-section="hero"], .hero, .hero-section, header, section:first-of-type',
            'footer-section': 'footer, .footer, [data-vmo-section="footer"]',
            navigation: 'nav, .nav, .navigation, [data-vmo-section="navigation"]'
        };
        return presets[selector] || selector;
    }
    
    /**
     * Deploy specialized agent based on analysis
     */
    async deploySpecializedAgent(analysis) {
        const { agent, scope, targetElement } = analysis;
        
        this.showToast(`🤖 Deploying ${this.getAgentName(agent)}...`, 'info');
        
        const agentHandlers = {
            website_builder: () => this.handleWebsiteGeneration(analysis),
            media_specialist: () => this.handleMediaIntegration(analysis),
            seo_specialist: () => this.handleSEOOptimization(analysis),
            design_specialist: () => this.handleDesignRefinement(analysis),
            content_specialist: () => this.handleContentRefinement(analysis)
        };
        
        const handler = agentHandlers[agent];
        if (handler) {
            await handler();
        } else {
            throw new Error('Unknown agent type');
        }
    }
    
    /**
     * Handle website generation with specialized AI
     */
    async handleWebsiteGeneration(analysis) {
        const formData = new FormData();
        formData.append('action', 'vmo_agent_website_generation');
        formData.append('nonce', vmoAjax.nonce);
        formData.append('prompt', analysis.originalPrompt);
        formData.append('preserve_existing', 'true');
        const projectId = window.currentProjectId || window.vmoCurrentProjectId || 0;
        if (projectId) {
            formData.append('project_id', projectId);
            formData.append('post_id', projectId);
        }

        const contentArea = document.getElementById('vmo-website-content');
        const previewFrame = document.getElementById('vmo-preview-iframe');
        if (previewFrame?.contentDocument?.documentElement) {
            formData.append('current_content', previewFrame.contentDocument.documentElement.outerHTML);
        } else if (contentArea) {
            formData.append('current_content', contentArea.innerHTML);
        }
        formData.append('component_state', JSON.stringify(window.vmoState?.componentState || window.vmoState?.component_state || {}));
        formData.append('standalone_runtime_required', 'true');
        formData.append('editing_surface', 'vmo_internal_builder_template');
        
        const response = await fetch(vmoAjax.ajaxurl, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            const nextProjectId = data.data?.draft_id || data.data?.post_id || data.data?.website_draft?.post_id;
            if (nextProjectId) {
                window.currentProjectId = nextProjectId;
                window.vmoCurrentProjectId = nextProjectId;
            }
            this.applyWebsiteChanges(data.data.html);
            this.showToast('✅ Website updated successfully!', 'success');
        } else {
            throw new Error(data.data || 'Website generation failed');
        }
    }
    
    /**
     * Handle media integration with specialized AI
     */
    async handleMediaIntegration(analysis) {
        const formData = new FormData();
        formData.append('action', 'vmo_agent_media_integration');
        formData.append('nonce', vmoAjax.nonce);
        formData.append('prompt', analysis.originalPrompt);
        formData.append('target_element', analysis.targetElement || 'auto-detect');
        formData.append('preserve_layout', 'true');
        this.appendProjectContext(formData);
        
        const response = await fetch(vmoAjax.ajaxurl, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            this.applyMediaChanges(data.data);
            this.showToast('✅ Media integrated successfully!', 'success');
        } else {
            throw new Error(data.data || 'Media integration failed');
        }
    }
    
    /**
     * Handle content refinement with specialized AI
     */
    async handleContentRefinement(analysis) {
        const formData = new FormData();
        formData.append('action', 'vmo_agent_content_refinement');
        formData.append('nonce', vmoAjax.nonce);
        formData.append('prompt', analysis.originalPrompt);
        formData.append('target_element', analysis.targetElement || 'auto-detect');
        formData.append('preserve_structure', 'true');
        this.appendProjectContext(formData);
        
        const response = await fetch(vmoAjax.ajaxurl, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            this.applyContentChanges(data.data);
            this.showToast('✅ Content updated successfully!', 'success');
        } else {
            throw new Error(data.data || 'Content refinement failed');
        }
    }

    /**
     * Handle SEO optimization with a standalone metadata contract
     */
    async handleSEOOptimization(analysis) {
        const formData = new FormData();
        formData.append('action', 'vmo_agent_seo_optimization');
        formData.append('nonce', vmoAjax.nonce);
        formData.append('prompt', analysis.originalPrompt);
        this.appendProjectContext(formData);

        const response = await fetch(vmoAjax.ajaxurl, {
            method: 'POST',
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            this.applySEOChanges(data.data);
            this.showToast('✅ SEO contract updated successfully!', 'success');
        } else {
            throw new Error(data.data || 'SEO optimization failed');
        }
    }

    /**
     * Handle design refinement with scoped standalone CSS
     */
    async handleDesignRefinement(analysis) {
        const formData = new FormData();
        formData.append('action', 'vmo_agent_design_refinement');
        formData.append('nonce', vmoAjax.nonce);
        formData.append('prompt', analysis.originalPrompt);
        formData.append('target_element', analysis.targetElement || 'auto-detect');
        this.appendProjectContext(formData);

        const response = await fetch(vmoAjax.ajaxurl, {
            method: 'POST',
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            this.applyDesignChanges(data.data);
            this.showToast('✅ Design updated successfully!', 'success');
        } else {
            throw new Error(data.data || 'Design refinement failed');
        }
    }
    
    /**
     * Apply website changes while preserving existing elements
     */
    applyWebsiteChanges(newHTML) {
        const contentArea = document.getElementById('vmo-website-content');
        if (contentArea) {
            contentArea.innerHTML = newHTML;
            
            // Re-inject replace buttons
            if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') {
                setTimeout(() => {
                    window.vmoInjectReplaceButtonsInIframe();
                }, 500);
            }
        }
    }
    
    /**
     * Apply media changes to specific elements only
     */
    applyMediaChanges(mediaData) {
        if (mediaData.target_selector) {
            const iframe = document.getElementById('vmo-preview-iframe');
            if (iframe?.contentDocument) {
                const targetElement = iframe.contentDocument.querySelector(this.normalizeSelector(mediaData.target_selector, 'img, video, [data-vmo-media]'));
                if (targetElement) {
                    if (mediaData.queue_marker) {
                        Object.entries(mediaData.queue_marker).forEach(([key, value]) => {
                            if (key === 'alt' && targetElement.tagName === 'IMG') {
                                targetElement.setAttribute('alt', value || 'Generated media');
                            } else if (value !== undefined && value !== null) {
                                targetElement.setAttribute(key, String(value));
                            }
                        });
                        targetElement.classList.add('vmo-media-placeholder');
                    } else if (mediaData.new_media_url && targetElement.tagName === 'IMG') {
                        targetElement.src = mediaData.new_media_url;
                    } else if (mediaData.new_media_url && targetElement.tagName === 'VIDEO') {
                        targetElement.src = mediaData.new_media_url;
                    } else if (mediaData.new_media_url) {
                        // Background image replacement
                        targetElement.style.backgroundImage = `url(${mediaData.new_media_url})`;
                    }
                }
            }
        }
    }
    
    /**
     * Apply content changes to specific elements only
     */
    applyContentChanges(contentData) {
        if (contentData.target_selector && contentData.new_content) {
            const iframe = document.getElementById('vmo-preview-iframe');
            if (iframe?.contentDocument) {
                const targetElement = iframe.contentDocument.querySelector(this.normalizeSelector(contentData.target_selector, 'h1, h2, p'));
                if (targetElement) {
                    targetElement.innerHTML = contentData.new_content;
                }
            }
        }
    }

    applySEOChanges(seoData) {
        const iframe = document.getElementById('vmo-preview-iframe');
        const doc = iframe?.contentDocument;
        const recommendations = seoData.seo_recommendations || {};
        if (!doc || !recommendations) return;

        if (recommendations.title) {
            let title = doc.querySelector('title');
            if (!title) {
                title = doc.createElement('title');
                doc.head.appendChild(title);
            }
            title.textContent = recommendations.title;
        }

        if (recommendations.meta_description) {
            let meta = doc.querySelector('meta[name="description"]');
            if (!meta) {
                meta = doc.createElement('meta');
                meta.setAttribute('name', 'description');
                doc.head.appendChild(meta);
            }
            meta.setAttribute('content', recommendations.meta_description);
        }

        if (recommendations.schema_json_ld) {
            let schema = doc.querySelector('script[type="application/ld+json"][data-vmo-seo-schema]');
            if (!schema) {
                schema = doc.createElement('script');
                schema.type = 'application/ld+json';
                schema.setAttribute('data-vmo-seo-schema', 'true');
                doc.head.appendChild(schema);
            }
            schema.textContent = typeof recommendations.schema_json_ld === 'string'
                ? recommendations.schema_json_ld
                : JSON.stringify(recommendations.schema_json_ld);
        }
    }

    applyDesignChanges(designData) {
        const iframe = document.getElementById('vmo-preview-iframe');
        const doc = iframe?.contentDocument;
        if (!doc) return;

        const cssChanges = designData.css_changes;
        let cssText = '';
        if (typeof cssChanges === 'string') {
            cssText = cssChanges;
        } else if (cssChanges && typeof cssChanges === 'object') {
            const selector = this.normalizeSelector(designData.target_selector, 'section');
            const declarations = Object.entries(cssChanges)
                .map(([property, value]) => `${property}: ${value};`)
                .join(' ');
            cssText = `${selector} { ${declarations} }`;
        }

        if (!cssText) return;
        let style = doc.querySelector('style[data-vmo-design-refinement]');
        if (!style) {
            style = doc.createElement('style');
            style.setAttribute('data-vmo-design-refinement', 'true');
            doc.head.appendChild(style);
        }
        style.textContent += `\n${cssText}`;
    }
    
    /**
     * Update context indicator
     */
    updateContextIndicator(analysis) {
        const contextIndicator = document.getElementById('vmo-agent-context');
        if (contextIndicator) {
            const agentName = this.getAgentName(analysis.agent);
            const scopeName = this.getScopeName(analysis.scope);
            
            contextIndicator.innerHTML = `
                <div class="vmo-context-info">
                    <span class="vmo-context-agent">🤖 ${agentName}</span>
                    <span class="vmo-context-scope">${scopeName}</span>
                    <span class="vmo-context-confidence">${Math.round(analysis.confidence)}% match</span>
                </div>
            `;
        }
    }
    
    /**
     * Get human-readable agent name
     */
    getAgentName(agent) {
        const names = {
            website_builder: 'Website Builder',
            media_specialist: 'Media Specialist',
            seo_specialist: 'SEO Expert',
            design_specialist: 'Design Expert',
            content_specialist: 'Content Writer'
        };
        return names[agent] || 'General AI';
    }
    
    /**
     * Get human-readable scope name
     */
    getScopeName(scope) {
        const names = {
            page: 'Full Page',
            element: 'Specific Element',
            media: 'Media Only',
            seo: 'SEO Optimization'
        };
        return names[scope] || 'General';
    }
    
    /**
     * Show processing indicator
     */
    showProcessingIndicator() {
        const indicator = document.createElement('div');
        indicator.id = 'vmo-refinement-processing';
        indicator.className = 'vmo-processing-indicator';
        indicator.innerHTML = `
            <div class="vmo-processing-content">
                <div class="vmo-processing-spinner"></div>
                <div class="vmo-processing-text">AI Agent Processing...</div>
            </div>
        `;
        
        document.body.appendChild(indicator);
    }
    
    /**
     * Hide processing indicator
     */
    hideProcessingIndicator() {
        const indicator = document.getElementById('vmo-refinement-processing');
        if (indicator) {
            indicator.remove();
        }
    }
    
    /**
     * Show toast message
     */
    showToast(message, type = 'info') {
        if (typeof window.showToast === 'function') {
            window.showToast(message, type);
        } else {
            console.log(`VMO ${type.toUpperCase()}: ${message}`);
        }
    }
}

// Initialize the refinement system
document.addEventListener('DOMContentLoaded', () => {
    window.vmoRefinementAgents = new VMORefinementAgents();
});
