/**
 * VMO AI Website Builder - Version 2.0 Conversational AI
 * Enhanced conversational interface with multi-agent AI system
 * CACHE BUST: Aug 4, 2025 - UNIFIED VERSION VERIFICATION
 * VOICE CONVERSATION DISABLED: Text chat and Business Wizard remain fully functional
 */
console.log('🎯 VMO Business Wizard UNIFIED v8.0.0 - Conversational AI Loading! (Voice Conversation Disabled)');

class VMOConversationalAI {
    constructor() {
        this.currentAgent = null;
        this.conversationHistory = [];
        this.isTextChatEnabled = true; // TEXT CHAT ONLY - No voice/audio
        this.currentProject = null;
        this.wizardStep = 0;
        this.wizardData = {};
        this.sessionId = null;
        // E-commerce onboarding state (AI-led KYC + catalog)
        this.ecomOnboarding = {
            active: false,
            step: 0,
            substep: 0, // For conversational product collection
            mode: 'conversational', // 'conversational' or 'structured'
            data: { kyc: {}, products: [] },
            currentProduct: {}, // Product being built
            productImages: [], // Uploaded images
            completed: false
        };
        // Text chat controls (NO VOICE)
        this.aiResponding = false;
        this.hasWelcomed = false;
        
        // ✅ UNIFIED CONVERSATION STATE - Prevents multiple competing AI systems
        this.conversationState = {
            active: false,
            mode: null, // 'greeting', 'consultation', 'user_response', 'generating'
            aiResponding: false,
            lastResponse: null,
            queue: [] // Queue messages instead of simultaneous calls
        };
        
        this.init();
    }
    
    init() {
        console.log('🚀 VMO Conversational AI: Initializing...');
        this.initTextChatOnly();
        this.bindEvents();
        this.initWizardQuestions();
        
        // Initialize main chat interface auto-greeting (TEXT ONLY)
        setTimeout(() => {
            this.initMainChatGreeting();
        }, 1000);
        
        console.log('✅ VMO Conversational AI: Initialization complete (TEXT CHAT ONLY)');
    }
    
    // TEXT CHAT ONLY - No voice recognition
    initTextChatOnly() {
        console.log('💬 Initializing text-based chat interfaces...');
        // Remove any voice-related elements
        const voiceButtons = document.querySelectorAll('[data-voice-enabled], .voice-button, #vmo-wizard-voice');
        voiceButtons.forEach(btn => {
            btn.style.display = 'none';
            console.log('🔇 Hidden voice button:', btn.id || btn.className);
        });
        
        // Ensure text input areas are properly set up
        this.setupTextInputHandlers();
    }
    
    // ❌ DISABLED: Business Wizard text handlers now in vmo-intelligent-consultation.js
    setupTextInputHandlers() {
        console.log('⌨️ Setting up text input handlers... (Business Wizard disabled)');
        
        // ❌ DISABLED: Business Wizard send button - now handled by vmo-intelligent-consultation.js
        /*
        const wizardSendBtn = document.getElementById('vmo-wizard-send');
        if (wizardSendBtn) {
            wizardSendBtn.addEventListener('click', () => {
                this.handleWizardTextInput();
            });
        }
        
        // Business Wizard textarea Enter key
        const wizardTextarea = document.getElementById('vmo-wizard-input');
        if (wizardTextarea) {
            wizardTextarea.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.handleWizardTextInput();
                }
            });
        }
        */
        
        // Main chat interface (if present)
        this.setupMainChatHandlers();
    }
    
    // Handle text input from Business Wizard
    handleWizardTextInput() {
        const textarea = document.getElementById('vmo-wizard-input');
        if (!textarea) return;
        
        const message = textarea.value.trim();
        if (!message) return;
        
        console.log('💬 Business Wizard text input:', message);
        textarea.value = ''; // Clear input
        
        // Send to wizard response handler
        this.sendWizardResponse(message);
    }
    
    // Setup main chat interface handlers
    setupMainChatHandlers() {
        console.log('🤖 Setting up main Jarvis chat handlers...');

        const sendBtn = document.getElementById('vmo-send-message');
        if (sendBtn && !sendBtn.dataset.vmoBound) {
            sendBtn.dataset.vmoBound = '1';
            sendBtn.addEventListener('click', () => this.sendMessage());
        }

        const input = document.getElementById('vmo-user-message');
        if (input && !input.dataset.vmoBound) {
            input.dataset.vmoBound = '1';
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });
        }
    }
    
    bindEvents() {
        console.log('🔧 VMO Conversational AI: Binding events (Business Wizard ENABLED)');
        
        // ✅ RE-ENABLED: Business Wizard button handlers (user's improved version)
        const wizardBtn = document.getElementById('vmo-business-wizard-btn');
        if (wizardBtn) {
            wizardBtn.addEventListener('click', () => {
                console.log('🎯 Business Wizard Header Button Clicked! (CONVERSATIONAL)');
                this.openBusinessWizard();
            });
            console.log('✅ Business Wizard button found and event bound');
        } else {
            console.warn('⚠️ Business Wizard button not found - will retry after DOM loads');
            setTimeout(() => {
                const retryBtn = document.getElementById('vmo-business-wizard-btn');
                if (retryBtn) {
                    retryBtn.addEventListener('click', () => {
                        console.log('🎯 Business Wizard Header Button Clicked! (CONVERSATIONAL - Retry)');
                        this.openBusinessWizard();
                    });
                    console.log('✅ Business Wizard button found on retry and event bound');
                } else {
                    console.error('❌ Business Wizard button still not found after retry');
                }
            }, 2000);
        }
        
        // Event delegation for various actions
        document.addEventListener('click', (e) => {
            if (e.target.closest('[data-action="start-business-wizard"]')) {
                this.startBusinessWizard();
            } else if (e.target.closest('[data-action="start-conversation"]')) {
                this.startConversation('designer');
            } else if (e.target.closest('[data-action="start-voice-session"]')) {
                this.startVoiceSession();
            } else if (e.target.closest('[data-action="manual-design"]')) {
                this.openManualDesign();
            }
        });
        
        // ❌ DISABLED: Business Wizard Controls now handled by vmo-intelligent-consultation.js
        /*
        document.getElementById('vmo-wizard-start')?.addEventListener('click', () => {
            console.log('🎯 Business Wizard Start Button Clicked! (UNIFIED)');
            this.startWizardQuestions();
        });
        
        document.getElementById('vmo-wizard-send')?.addEventListener('click', () => {
            console.log('📤 Business Wizard Send Button Clicked! (UNIFIED)');
            this.sendWizardResponse();
        });
        
        document.getElementById('vmo-wizard-voice')?.addEventListener('click', () => {
            console.log('🎤 Business Wizard Voice Button Clicked! (UNIFIED)');
            this.startWizardVoice();
        });
        
        document.getElementById('vmo-wizard-transcribe')?.addEventListener('click', () => {
            console.log('💬 Business Wizard Transcribe Button Clicked! (UNIFIED)');
            this.startWizardTranscribe();
        });
        
        document.getElementById('vmo-wizard-previous')?.addEventListener('click', () => {
            this.previousWizardQuestion();
        });
        
        document.getElementById('vmo-wizard-skip')?.addEventListener('click', () => {
            this.skipWizardQuestion();
        });
        
        document.getElementById('vmo-wizard-approve-plan')?.addEventListener('click', () => {
            this.approveBusinessPlan();
        });
        */
        
        // ✅ RE-ENABLED: Close Business Wizard button
        document.getElementById('vmo-close-business-wizard')?.addEventListener('click', () => {
            this.closeBusinessWizard();
        });
        
        // Wizard response textarea enter key - SKIP if intelligent consultation will handle it
        const wizardTextarea = document.getElementById('vmo-wizard-response');
        if (wizardTextarea && !window._vmoIntelligentConsultationActive) {
            wizardTextarea.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendWizardResponse();
                }
            });
        }
        
        // Conversation controls
        this.setupMainChatHandlers();
        
        document.getElementById('vmo-voice-input')?.addEventListener('click', () => {
            this.startVoiceInput();
        });
        
        // Modal close buttons
        document.getElementById('vmo-close-conversation')?.addEventListener('click', () => {
            this.closeConversation();
        });
        
        // Preview button handlers - FIX FOR BROWSER PREVIEW
        document.addEventListener('click', (e) => {
            if (e.target.matches('.vmo-wizard-btn-view') || e.target.closest('.vmo-wizard-btn-view')) {
                e.preventDefault();
                this.openBrowserPreview();
            }
        });
    }
    
    // ✅ Re-bind Business Wizard buttons (called after modal opens to ensure buttons work)
    rebindWizardButtons() {
        console.log('🔧 Re-binding Business Wizard buttons...');
        
        // Remove any existing listeners by cloning and replacing buttons
        const rebind = (id, handler) => {
            const oldBtn = document.getElementById(id);
            if (oldBtn) {
                const newBtn = oldBtn.cloneNode(true);
                oldBtn.parentNode.replaceChild(newBtn, oldBtn);
                newBtn.addEventListener('click', handler.bind(this));
                console.log(`✅ Re-bound: ${id}`);
            } else {
                console.warn(`⚠️ Button not found: ${id}`);
            }
        };
        
        // Re-bind all wizard buttons
        rebind('vmo-wizard-send', this.sendWizardResponse);
        rebind('vmo-wizard-voice', this.startWizardVoice);
        rebind('vmo-wizard-transcribe', this.startWizardTranscribe);
        rebind('vmo-wizard-upload', this.handleFileUpload);
        rebind('vmo-wizard-video', this.handleVideoUpload);
        rebind('vmo-wizard-start', this.startWizardQuestions);
        rebind('vmo-close-business-wizard', this.closeBusinessWizard);
        rebind('vmo-wizard-back', this.previousWizardQuestion);
        rebind('vmo-wizard-skip', this.skipWizardQuestion);
        
        // Re-bind Enter key for textarea - SKIP if intelligent consultation is active
        const textarea = document.getElementById('vmo-wizard-response');
        if (textarea && !window._vmoIntelligentConsultationActive) {
            const newTextarea = textarea.cloneNode(true);
            textarea.parentNode.replaceChild(newTextarea, textarea);
            newTextarea.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendWizardResponse();
                }
            });
            console.log('✅ Re-bound: vmo-wizard-response Enter key (Conversational mode)');
        } else if (window._vmoIntelligentConsultationActive) {
            console.log('⏭️ Skipping textarea rebind - Intelligent Consultation is active');
        }
        
        console.log('✅ All Business Wizard buttons re-bound successfully');
    }
    
    // Open Business Wizard - Full Screen Modal
    async openBusinessWizard() {
        console.log('🎯 Opening Business Wizard Modal (CONVERSATIONAL)');
        
        const modal = document.getElementById('vmo-business-wizard-modal');
        if (!modal) {
            console.error('❌ Business Wizard Modal NOT FOUND!');
            console.log('Available modals:', Array.from(document.querySelectorAll('[id*="modal"]')).map(el => el.id));
            alert('Business Wizard modal not found. Please refresh the page and try again.');
            return;
        }
        
        console.log('✅ Business Wizard Modal Found:', modal);
        console.log('✅ Modal current display:', modal.style.display);
        
        // ✅ CRITICAL FIX: Hide voice panel to prevent duplicate AI responses
        const voicePanel = document.getElementById('vmo-ai-voice');
        if (voicePanel) {
            voicePanel.style.display = 'none';
            console.log('✅ Voice panel hidden - preventing duplicate responses');
        }
        
        try {
            // Force modal to show
            modal.style.display = 'flex';
            modal.style.visibility = 'visible';
            modal.style.opacity = '1';
            modal.setAttribute('aria-hidden', 'false');
            
            console.log('✅ Modal display set to:', modal.style.display);
            
            // Add background blur when opening
            document.body.classList.add('vmo-wizard-active');
            
            // Reset wizard state
            this.resetWizardState();
            
            // Check conversation container
            const conversation = document.getElementById('vmo-wizard-conversation');
            console.log('✅ Conversation container found:', conversation ? 'YES' : 'NO');
            
            // ✅ Load business memory and conversation history
            await this.loadBusinessMemory();
            
            if (typeof this.showToast === 'function') {
                this.showToast('Business Development Wizard opened. Loading your business context...', 'success');
            } else if (window.showToast) {
                window.showToast('Business Development Wizard opened. Loading your business context...', 'success');
            }
            
            // ✅ FIXED: Show welcome message WITHOUT triggering competing AI systems
            console.log('🎯 About to show welcome message...');
            setTimeout(() => {
                try {
                    console.log('🎯 Calling showSimpleWelcome()...');
                    this.showSimpleWelcome();
                    console.log('✅ Welcome shown successfully');
                    
                    // ✅ CRITICAL: Re-bind button events after modal content loads
                    this.rebindWizardButtons();
                    console.log('✅ Wizard buttons re-bound');
                } catch (error) {
                    console.error('❌ ERROR in showSimpleWelcome:', error);
                    console.error('Error stack:', error.stack);
                }
            }, 500); // Reduced delay
            
        } catch (error) {
            console.error('❌ Error opening Business Wizard:', error);
            console.error('Error stack:', error.stack);
            alert('Error opening Business Wizard: ' + error.message);
        }
    }
    
    // Close Business Wizard
    closeBusinessWizard() {
        const modal = document.getElementById('vmo-business-wizard-modal');
        if (modal) {
            modal.style.display = 'none';
            // Remove background blur when closing
            document.body.classList.remove('vmo-wizard-active');
        }
        
        // ✅ CRITICAL FIX: Show voice panel again when Business Wizard closes
        const voicePanel = document.getElementById('vmo-ai-voice');
        if (voicePanel) {
            voicePanel.style.display = 'block';
            console.log('✅ Voice panel restored');
        }
        
    // Stop any active voice session
    this.voiceSessionActive = false;
    try { this.recognition && this.recognition.stop && this.recognition.stop(); } catch(e) {}
        if (typeof showToast === 'function') {
            showToast('Business Development Wizard closed', 'info');
        }
    }
    
    // Reset wizard to initial state
    resetWizardState() {
        // Reset consultation state
        this.currentCategory = null;
        this.currentQuestionIndex = 0;
        this.consultationData = {};
        this.comprehensiveBusinessResults = null;
    this.voiceSessionActive = false;
    this.isSpeaking = false;
    this.aiResponding = false;
    this.hasWelcomed = false;
        
        this.updateWizardProgress(0);
        
        // Show intro, hide other sections
        document.getElementById('vmo-wizard-conversation')?.style.setProperty('display', 'block');
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-results')?.style.setProperty('display', 'none');
        
        // Clear conversation
        const conversation = document.getElementById('vmo-wizard-conversation');
        if (conversation) {
            // Clear ALL messages completely
            conversation.innerHTML = '';
            console.log('🔧 DEBUG: Conversation cleared completely');
        }
        
        // Clear responses
        const responseField = document.getElementById('vmo-wizard-response');
        if (responseField) {
            responseField.value = '';
            responseField.placeholder = 'Type your answer here...';
        }
        
        // Reset buttons - SHOW START BUTTON OVERLAY
        const startOverlay = document.getElementById('vmo-wizard-start-overlay');
        if (startOverlay) {
            startOverlay.style.display = 'block';
        }
        const startBtn = document.getElementById('vmo-wizard-start');
        if (startBtn) {
            startBtn.style.setProperty('display', 'block', 'important');
            startBtn.style.setProperty('visibility', 'visible', 'important');
            startBtn.style.setProperty('opacity', '1', 'important');
            console.log('🔧 START BUTTON OVERLAY RESTORED');
        }
        document.getElementById('vmo-wizard-send')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-previous')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-skip')?.style.setProperty('display', 'block');
        
    // Reset progress text
        const progressText = document.getElementById('vmo-wizard-progress-text');
        if (progressText) {
            progressText.textContent = 'Ready to Start Consultation';
        }
    // Do not add duplicate welcome here; startVoiceGreeting will handle unified welcome + TTS
    }
    
    // RADICAL CHANGE: Voice greeting and automatic consultation start
    // ✅ SIMPLIFIED: Show welcome message WITHOUT triggering AI conversation
    showSimpleWelcome() {
        console.log('👋 Showing simple welcome message');
        
        // ✅ Context-aware greeting based on business memory (NO AI CALL)
        let welcomeMessage;
        if (this.hasWebsite && this.businessMemory && this.businessMemory.length > 0) {
            const businessName = this.businessMemory.find(m => m.category === 'business_name')?.value || 'your business';
            welcomeMessage = `Welcome back! 👋\n\nI have your ${businessName} information saved. Ready to continue building your complete business ecosystem?\n\nWhat would you like to focus on today?`;
            this.updateWizardProgress(50);
        } else if (this.previousConsultations && this.previousConsultations.length > 0) {
            welcomeMessage = `Welcome back! 🌟\n\nGreat to see you again! Let's pick up where we left off and continue building your business.\n\nAre you ready to move forward?`;
            this.updateWizardProgress(25);
        } else {
            // ✅ Warm, professional introduction with personality
            welcomeMessage = `Hi there! 👋 I'm your VMO Business Consultant—think of me as your personal business strategist here to help you build something amazing.\n\nWhether you're just starting out with a new idea or growing an existing business, I'm here to guide you through every step. We'll have a friendly conversation to understand your vision, and then I'll help you build a complete business ecosystem: professional website, marketing systems, legal documents, SEO optimization—everything you need.\n\nLet's start simple: What kind of business are you thinking about?\n\n(And hey, it's totally okay if you're still figuring things out—that's what I'm here for!)`;
            this.updateWizardProgress(0);
        }
        
        // ✅ Add welcome message (NO AI CALL, NO TTS auto-trigger)
        if (!this.hasWelcomed) {
            this.addWizardMessage(welcomeMessage, true);
            this.hasWelcomed = true;
        }
        
        // ✅ REMOVED: Voice listener and business insights (causing issues)
        // User will type or click voice button manually when ready
    }
    
    // ✅ DEPRECATED: Old voice greeting function kept for compatibility
    startVoiceGreeting() {
        console.log('⚠️ startVoiceGreeting() called but redirected to showSimpleWelcome()');
        this.showSimpleWelcome();
    }

    // Initialize main chat interface greeting
    initMainChatGreeting() {
        console.log('💬 Initializing main chat interface greeting...');
        
        // Check if chat history container exists
        const chatHistory = document.getElementById('vmo-chat-history');
        if (!chatHistory) {
            console.log('ℹ️ Main chat interface not found - skipping greeting');
            return;
        }
        
        // Check if already has messages
        if (chatHistory.innerHTML.trim()) {
            console.log('ℹ️ Chat already has messages - skipping greeting');
            return;
        }
        
        // Add welcome message to main chat
        const welcomeMessage = `
            <div class="vmo-ai-message">
                <div class="vmo-message-avatar">🤖</div>
                <div class="vmo-message-content">
                    <p>Hello! I'm VMO, your AI website builder assistant. I'm here to help you:</p>
                    <ul>
                        <li>🏗️ <strong>Generate websites</strong> - Just describe what you want</li>
                        <li>✨ <strong>Refine content</strong> - Make changes to existing sections</li>
                        <li>🎨 <strong>Add media</strong> - Insert images, videos, and more</li>
                        <li>🏢 <strong>Business consultation</strong> - Click the red Business Wizard button for a complete setup</li>
                    </ul>
                    <p>What would you like to create today?</p>
                </div>
            </div>
        `;
        
        chatHistory.innerHTML = welcomeMessage;
        console.log('✅ Main chat greeting added');
    }

    async injectRecentBusinessInsights() {
        try {
            const report = await this.fetchPaymentsReport();
            if (!report) return;
            const last30 = report?.comparative?.last_30d || 0;
            const prev30 = report?.comparative?.prev_30d || 0;
            const mom = report?.comparative?.mom_change;
            const weekly = Array.isArray(report?.chart?.sales) ? report.chart.sales.slice(-1)[0] || 0 : 0;
            const currency = (report?.orders?.[0]?.currency || 'usd').toLowerCase();
            const fmt = (amt) => {
                const n = Number(amt||0) / 100;
                try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency.toUpperCase() }).format(n); } catch(e) { return `$${n.toFixed(2)}`; }
            };
            const momText = (typeof mom === 'number') ? ` (${mom >= 0 ? '▲' : '▼'} ${Math.abs(mom*100).toFixed(1)}% vs prior 30d)` : '';
            const msg = `Since your last session, you’ve processed ${fmt(last30)} in the last 30 days${momText}. Last week: ${fmt(weekly)}. Want to push these numbers higher, add new products/services, or adjust your strategy?`;
            this.addWizardMessage(msg, true);
        } catch (e) { /* non-blocking */ }
    }

    async fetchPaymentsReport() {
        try {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) || (window.location.origin + '/wp-json/');
            const url = apiRoot + 'vmo-builder/v1/payments/report';
            const res = await fetch(url, { method: 'GET' });
            const json = await res.json();
            return json?.data || null;
        } catch (e) { return null; }
    }
    
    // VOICE SYSTEM REMOVED: Speech recognition disabled for No Voice version
    startVoiceListener() {
        // No-op function - voice recognition completely disabled
        console.log('🔇 Voice recognition disabled - text-only mode');
        return;
    }
    
    // VOICE SYSTEM REMOVED: All speech/audio playback disabled for No Voice version
    speakMessage(text, addTranscript = true) {
        // No-op function - voice playback completely disabled
        console.log('🔇 Voice system disabled - text-only mode');
        return;
    }
    
    // VOICE SYSTEM REMOVED: Web Speech API disabled for No Voice version
    speakWithWebAPI(text) {
        // No-op function - voice playback completely disabled
        return;
    }
    
    // ✅ Load business memory and conversation history from database
    async loadBusinessMemory() {
        console.log('💾 Loading business memory from database...');
        try {
            const response = await fetch(window.vmo_ajax?.ajax_url || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'vmo_get_business_memory',
                    nonce: window.vmo_ajax?.nonce || ''
                })
            });
            
            const data = await response.json();
            
            if (data.success && data.data) {
                this.businessMemory = data.data.memories || [];
                this.previousConsultations = data.data.consultations || [];
                this.hasWebsite = data.data.has_website || false;
                this.businessStage = data.data.business_stage || 'new';
                
                console.log('✅ Business memory loaded:', {
                    memories: this.businessMemory.length,
                    consultations: this.previousConsultations.length,
                    hasWebsite: this.hasWebsite,
                    stage: this.businessStage
                });
                
                // Update progress based on business stage
                if (this.hasWebsite) {
                    this.updateWizardProgress(50); // Existing client
                }
            } else {
                console.log('ℹ️ No previous business memory found (new client)');
                this.businessMemory = [];
                this.previousConsultations = [];
                this.hasWebsite = false;
                this.businessStage = 'new';
            }
        } catch (error) {
            console.error('❌ Error loading business memory:', error);
            this.businessMemory = [];
            this.previousConsultations = [];
            this.hasWebsite = false;
            this.businessStage = 'new';
        }
    }
    
    // Start wizard questions flow - NOW WITH REAL AI CONVERSATION
    startWizardQuestions() {
        console.log('🎯 Starting AI-powered business consultation');
        this.currentCategory = null;
        this.currentQuestionIndex = 0;
        this.consultationData = {};
        this.conversationHistory = []; // Track conversation for context
        
        this.startAIConsultation();
        
        // Hide start button overlay, show conversation controls
        const startOverlay = document.getElementById('vmo-wizard-start-overlay');
        if (startOverlay) {
            startOverlay.style.display = 'none';
        }
        document.getElementById('vmo-wizard-start')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-send')?.style.setProperty('display', 'block');
        document.getElementById('vmo-wizard-voice')?.style.setProperty('display', 'block');
    }

    // Start AI-powered consultation with expert-level questioning
    async startAIConsultation() {
        // Initialize client intelligence database
        this.clientIntelligence = {
            businessProfile: {},
            responses: [],
            insights: {},
            recommendations: [],
            timestamp: Date.now()
        };
        // Do not add another welcome here if we've already greeted
        if (!this.hasWelcomed) {
            const intro = `Welcome! We’ll keep this simple: we’ll do a brief intake, I’ll ask a few focused questions, and then I’ll generate your website’s structure, page copy, imagery, brand accents, and baseline SEO. You’ll end with a reviewable site draft and clear next steps. When you’re ready, tell me about your business.`;
            this.addWizardMessage(intro, true);
            this.hasWelcomed = true;
        }
        
        // ✅ CRITICAL FIX: Removed automatic AI greeting call that was causing duplicate responses
        // The greeting is already shown by showSimpleWelcome() which asks ONE simple question
        // User will type their answer and THEN the AI will respond naturally via sendWizardResponse()
        console.log('✅ AI consultation ready - waiting for user input');
        
        /*
        // DISABLED: This setTimeout was sending a second greeting from AI, competing with showSimpleWelcome()
        // Wait a moment, then ask the first strategic question
        setTimeout(async () => {
            const expertPrompt = `You are the world's top business consultant - think McKinsey, BCG, Bain level expertise. You help entrepreneurs at ALL stages, from startup ideas to established businesses.

Your role:
- FIRST: Determine if they have an existing business or want to start new
- Adapt your questioning style based on their situation
- For NEW businesses: Help discover opportunities, validate ideas, define target market
- For EXISTING businesses: Focus on growth, optimization, digital transformation
- Think like Harvard MBA + 20 years consulting both startups and Fortune 500 companies
- Guide them toward a complete business strategy with website as the foundation

Available business infrastructure we can build:
- Professional website with SEO & local presence
- E-commerce capabilities and payment processing
- AI phone assistant for 24/7 customer service
- Legal documents and business structure
- Marketing strategy and lead generation
- Advanced SEO Management System (continuous optimization)
- Automated content creation and blog publishing (with approval)
- Location-targeted service pages for market expansion
- Real-time ranking monitoring and improvements
- Ongoing automation services

START by asking ONE strategic question that determines their current business situation - whether they have an existing business they want to grow/improve, or if they're looking to start something completely new.

Based on their answer, you'll adapt your approach:
- If EXISTING: Focus on growth, digital presence, optimization
- If NEW STARTUP: Focus on opportunity discovery, validation, business model

Be professional, insightful, and demonstrate expertise in both startup strategy and business growth.`;
            
            try {
                // Fetch first question via conversation AJAX
                const response = await this.sendAIMessage(expertPrompt);
                this.addWizardMessage(response, true);
                // Ensure the first AI question is part of the conversation history so follow-ups like
                // "how do you mean?" can reference it correctly
                if (typeof response === 'string' && response.trim().length) {
                    this.conversationHistory.push({ role: 'assistant', content: response });
                }
                // Store initial consultation start
                this.saveClientResponse('consultation_start', {
                    timestamp: new Date().toISOString(),
                    consultant_prompt: expertPrompt
                });
            } catch (error) {
                console.error('Expert consultation start error:', error);
                // Fallback question if AI call fails
                const fallbackMessage = `What specific market problem or opportunity have you identified, and what unique insight or advantage do you possess that positions you to capture significant market value?`;
                this.addWizardMessage(fallbackMessage, true);
            }
        }, 1500);
        */
    }
    
    // Ask current wizard question
    askWizardQuestion() {
        if (!this.currentCategory) {
            this.showWizardReview();
            return;
        }
        
        const categoryQuestions = this.wizardQuestions[this.currentCategory];
        if (this.currentQuestionIndex >= categoryQuestions.length) {
            // Move to next category
            const currentCategoryIndex = this.categoryOrder.indexOf(this.currentCategory);
            if (currentCategoryIndex < this.categoryOrder.length - 1) {
                this.currentCategory = this.categoryOrder[currentCategoryIndex + 1];
                this.currentQuestionIndex = 0;
                
                // Show category transition message
                const categoryNames = {
                    'business_basics': 'Business Basics',
                    'target_market': 'Target Market Analysis',
                    'business_model': 'Business Model',
                    'goals_objectives': 'Goals & Objectives',
                    'brand_vision': 'Brand & Vision',
                    'operational_needs': 'Operational Requirements'
                };
                
                this.addWizardMessage(`Great! Now let's move on to ${categoryNames[this.currentCategory]}.`, true);
                
                setTimeout(() => {
                    this.askWizardQuestion();
                }, 1500);
                return;
            } else {
                // All categories completed
                this.showWizardReview();
                return;
            }
        }
        
        const question = categoryQuestions[this.currentQuestionIndex];
        this.addWizardMessage(question.question, true, question.suggestions);
        
        // Update progress
        const totalQuestions = this.categoryOrder.reduce((total, cat) => {
            return total + this.wizardQuestions[cat].length;
        }, 0);
        
        const completedQuestions = this.categoryOrder.slice(0, this.categoryOrder.indexOf(this.currentCategory))
            .reduce((total, cat) => total + this.wizardQuestions[cat].length, 0) + this.currentQuestionIndex;
        
        const progress = (completedQuestions / totalQuestions) * 100;
        this.updateWizardProgress(progress);
        
        // Update progress text
        const progressText = document.getElementById('vmo-wizard-progress-text');
        if (progressText) {
            const categoryNames = {
                'business_basics': 'Business Basics',
                'target_market': 'Target Market',
                'business_model': 'Business Model',
                'goals_objectives': 'Goals',
                'brand_vision': 'Brand Vision',
                'operational_needs': 'Operations'
            };
            progressText.textContent = `${categoryNames[this.currentCategory]} (${this.currentQuestionIndex + 1}/${this.wizardQuestions[this.currentCategory].length})`;
        }
        
        // Show previous button after first question
        const isFirstQuestion = this.currentCategory === this.categoryOrder[0] && this.currentQuestionIndex === 0;
        if (!isFirstQuestion) {
            document.getElementById('vmo-wizard-previous')?.style.setProperty('display', 'block');
        }
    }
    
    // Send wizard response
    async sendWizardResponse() {
        const responseField = document.getElementById('vmo-wizard-response');
        const response = responseField?.value.trim();
        
        if (!response) {
            this.showToast('Please provide an answer before continuing.', 'warning');
            return;
        }

        // If we're in the guided e-commerce onboarding flow, handle that first
        if (this.ecomOnboarding && this.ecomOnboarding.active) {
            // Show user message
            this.addWizardMessage(response, false);
            await this.handleEcommerceAnswer(response);
            responseField.value = '';
            return;
        }

        if (this.aiResponding) {
            this.showToast('One moment—finishing my previous reply.', 'info');
            return;
        }

        // ✅ CRITICAL FIX: Set flag IMMEDIATELY to prevent race condition (multiple simultaneous calls)
        this.aiResponding = true;

        // Add user message to conversation
        this.addWizardMessage(response, false);
        this.conversationHistory.push({role: 'user', content: response});

        // If the user is asking for clarification, explain the last AI question instead of advancing
        const needsClarification = /what do you mean|how do you mean|i don't understand|i dont understand|explain|what are you talking|not sure i understand|clarify/i.test(response.toLowerCase());
        if (needsClarification) {
            const lastAssistantMsg = [...this.conversationHistory].reverse().find(m => m.role === 'assistant');
            const lastQuestion = lastAssistantMsg?.content || 'the previous question';

            // Show typing indicator
            this.addWizardMessage('...', true, [], 'typing');
            try {
                const explanationPrompt = `The client asked you to clarify your previous question. The question was: "${lastQuestion}".
Please rephrase it in very simple, friendly language and give 2 concrete examples from different business types (for example, a local service business and an online product business) so it’s easy to understand.
Do not ask a new question yet. End with a brief check like: "Would you like to proceed with this topic or explore another area?"`;

                const aiResponse = await this.sendAIMessage(explanationPrompt, false);
                this.removeTypingIndicator();
                if (typeof aiResponse === 'string' && aiResponse.length > 10) {
                    this.addWizardMessage(aiResponse, true);
                    this.conversationHistory.push({ role: 'assistant', content: aiResponse });
                } else {
                    const fallbackResponse = this.generateExpertFallbackResponse(response);
                    this.addWizardMessage(fallbackResponse, true);
                    this.conversationHistory.push({ role: 'assistant', content: fallbackResponse });
                }
            } catch (e) {
                this.removeTypingIndicator();
                const fallbackResponse = this.generateExpertFallbackResponse(response);
                this.addWizardMessage(fallbackResponse, true);
                this.conversationHistory.push({ role: 'assistant', content: fallbackResponse });
            }
            // Do not continue with the normal questioning flow in this turn
            responseField.value = '';
            return;
        }
        
        // Before normal AI flow, detect ecommerce intent and offer instant onboarding
        const paymentsEnabled = (window.vmo_ajax && !!vmo_ajax.payments_enabled) || (window.vmoAjax && !!vmoAjax.payments_enabled);
        const wantsEcommerce = this.detectEcommerceIntent(response);
        if (!this.ecomOnboarding.completed && !this.ecomOnboarding.active && paymentsEnabled && wantsEcommerce) {
            // Show user message
            this.addWizardMessage(response, false);
            // Start the guided flow
            await this.beginEcommerceOnboarding();
            responseField.value = '';
            return;
        }

        // Save client response to intelligence database
        await this.saveClientResponse(`response_${Date.now()}`, {
            question_context: this.conversationHistory[this.conversationHistory.length - 2]?.content || '',
            user_response: response,
            timestamp: new Date().toISOString(),
            session_info: {
                total_responses: this.conversationHistory.filter(m => m.role === 'user').length,
                conversation_depth: this.conversationHistory.length
            }
        });
        
        // Clear input
        responseField.value = '';

        // Build expert consultant context
        const conversationContext = this.conversationHistory.map(msg => 
            `${msg.role === 'user' ? 'Client' : 'Consultant'}: ${msg.content}`
        ).join('\n\n');

        const expertPrompt = `You are a world-class business consultant (McKinsey/BCG level). You help entrepreneurs at ALL stages - from startup ideas to established businesses. Continue this strategic consultation:

${conversationContext}

Client just responded: "${response}"

Your expertise:
- Adapt your approach based on whether they have existing business or starting new
- For EXISTING businesses: Focus on growth, digital transformation, optimization, market expansion
- For NEW startups: Focus on opportunity discovery, validation, business model development
- Think like a Harvard MBA with 20+ years consulting both startups and Fortune 500 companies
- Ask probing questions that reveal opportunities and strategic advantages
- Remember everything they've told you - never repeat questions
- Guide toward a complete business strategy with website as the foundation

Available business infrastructure we can build:
- Professional website with SEO & local presence
- E-commerce capabilities and payment processing
- AI phone assistant for 24/7 customer service
- Legal documents and business structure
- Marketing strategy and lead generation
- Advanced SEO Management System (continuous optimization)
- Automated content creation and blog publishing (with approval)
- Location-targeted service pages for market expansion
- Real-time ranking monitoring and improvements
- Ongoing automation services

Current conversation depth: ${this.conversationHistory.length/2} exchanges

If this is exchange 8-10+ and you have sufficient business intelligence, transition to:
"Excellent insights! I now have enough strategic intelligence to deploy my specialist team. Let me assign our AI experts to create your complete business package..."

Otherwise, ask ONE more strategic question that builds on their response and helps develop their business strategy - whether that's growth for existing business or development for new venture.

Continue as the expert consultant:`;

        try {
            // Show typing indicator
            this.addWizardMessage('...', true, [], 'typing');
            this.aiResponding = true;
            
            const aiResponse = await this.sendAIMessage(expertPrompt, false);
            
            // Remove typing indicator and add real response
            this.removeTypingIndicator();
            
            // Validate response is a proper string
            if (typeof aiResponse === 'string' && aiResponse.length > 10) {
                this.addWizardMessage(aiResponse, true);
                this.conversationHistory.push({role: 'assistant', content: aiResponse});
                
                // Check if consultation is complete (look for transition language)
                if (aiResponse.toLowerCase().includes('specialist team') || 
                    aiResponse.toLowerCase().includes('deploy') ||
                    aiResponse.toLowerCase().includes('ai experts') ||
                    this.conversationHistory.length > 16) {
                    this.completeConsultation();
                }
            } else {
                // Fallback to manual expert response
                const fallbackResponse = this.generateExpertFallbackResponse(response);
                this.addWizardMessage(fallbackResponse, true);
                this.conversationHistory.push({role: 'assistant', content: fallbackResponse});
            }
            
        } catch (error) {
            console.error('Expert consultation error:', error);
            this.removeTypingIndicator();
            
            // Generate intelligent fallback based on user response
            const fallbackResponse = this.generateExpertFallbackResponse(response);
            this.addWizardMessage(fallbackResponse, true);
            this.conversationHistory.push({role: 'assistant', content: fallbackResponse});
        } finally {
            // ✅ FIXED: Always reset flag, even if error occurs
            this.aiResponding = false;
        }
    }

    // Detect if the user intends to sell online / needs payments
    detectEcommerceIntent(text) {
        try {
            const t = (text || '').toLowerCase();
            if (!t) return false;
            const keywords = [
                'sell online','sell products','online store','ecommerce','e-commerce','shop','checkout','buy button','stripe','payments','subscription','subscriptions','cart','purchase','storefront','merch','merchandise','digital download'
            ];
            return keywords.some(k => t.includes(k));
        } catch (e) { return false; }
    }

    // Start guided ecommerce onboarding (AI-led KYC + product catalog)
    async beginEcommerceOnboarding() {
        this.ecomOnboarding.active = true;
        this.ecomOnboarding.step = 1;
        this.ecomOnboarding.data = { kyc: {}, products: [] };
        this.addWizardMessage("Great news — I can enable your store and VMO Pay now so you can accept money immediately after setup. First, a couple of quick details for payouts: Are you operating as an Individual/sole proprietor or a Company? Also, what country are you based in (two-letter code like US, GB, CA)?", true);
        this.addWizardMessage("Reply in one line like: Individual, US", true);
    }

    isYes(text) {
        const t = (text || '').trim().toLowerCase();
        return /^(y|yes|yep|yeah|sure|ok|okay|affirmative|do it|let's go|lets go|proceed)/.test(t);
    }
    isNo(text) {
        const t = (text || '').trim().toLowerCase();
        return /^(n|no|nope|not now|later|skip)/.test(t);
    }

    // Parse product lines like: "Basic T-Shirt | 19.99 | usd | stock 25 | type item | ship yes"
    parseProductsList(multilineText) {
        const lines = (multilineText || '').split(/\n|;+/).map(l => l.trim()).filter(Boolean);
        const products = [];
        for (const line of lines) {
            const parts = line.split('|').map(p => p.trim());
            if (!parts.length) continue;
            const name = parts[0] || '';
            let price = 0, currency = 'usd', stock_qty = 0, product_type = 'item', ship = false;
            for (let i=1;i<parts.length;i++) {
                const p = parts[i].toLowerCase();
                // price
                const priceMatch = p.match(/\$?\s*([0-9]+(?:\.[0-9]{1,2})?)/);
                if (priceMatch) price = parseFloat(priceMatch[1]);
                // currency
                const curMatch = p.match(/\b([a-z]{3})\b/);
                if (curMatch) currency = curMatch[1];
                // stock
                const stockMatch = p.match(/stock\s*(\d+)/);
                if (stockMatch) stock_qty = parseInt(stockMatch[1], 10) || 0;
                // type
                if (p.includes('subscription')) product_type = 'subscription';
                else if (p.includes('download')) product_type = 'downloadable';
                else if (p.includes('service')) product_type = 'service';
                else if (p.includes('item') || p.includes('product')) product_type = 'item';
                // shipping
                if (p.includes('ship yes') || p.includes('shipping yes') || p.includes('ship:yes')) ship = true;
                if (p.includes('ship no') || p.includes('shipping no') || p.includes('ship:no')) ship = false;
            }
            if (!name || !price) continue;
            products.push({
                name,
                price_cents: Math.round(price * 100),
                currency: currency || 'usd',
                product_type,
                stock_tracking: stock_qty > 0,
                stock_qty: stock_qty || 0,
                shipping_required: ship
            });
        }
        return products;
    }

    async handleEcommerceAnswer(text) {
        const step = this.ecomOnboarding.step;
        const data = this.ecomOnboarding.data;
        const clean = (text || '').trim();

        if (step === 1) {
            // Expect: "Individual, US" or similar
            const parts = clean.split(',').map(s => s.trim());
            const type = (parts[0] || '').toLowerCase().includes('comp') ? 'company' : 'individual';
            const country = (parts[1] || parts[0] || 'US').replace(/[^A-Za-z]/g, '').slice(0,2).toUpperCase();
            data.kyc.business_type = type;
            data.kyc.country = country || 'US';
            this.ecomOnboarding.step = 2;
            this.addWizardMessage("Got it. What’s the best email for payouts/receipts? And the business or owner name?", true);
            this.addWizardMessage("Reply like: owner@domain.com, John Smith or ACME LLC", true);
            return;
        }

        if (step === 2) {
            const parts = clean.split(',').map(s => s.trim());
            const email = parts[0] || '';
            const name = parts.slice(1).join(', ') || parts[0] || '';
            data.kyc.email = email;
            if (data.kyc.business_type === 'company') {
                data.kyc.company_name = name;
                data.kyc.business_name = name;
            } else {
                const bits = name.split(' ');
                data.kyc.first_name = bits[0] || '';
                data.kyc.last_name = bits.slice(1).join(' ') || '';
                data.kyc.business_name = name;
            }

            // Attempt provisioning immediately
            this.addWizardMessage('✨ Perfect! Setting up your secure VMO Pay account...', true);
            try {
                const prov = await this.provisionStripeAccount(data.kyc);
                if (prov && prov.account_id && prov.onboarding_url) {
                    // Express account with onboarding link
                    this.addWizardMessage(
                        '🔒 Great! I\'ve pre-filled your business information.\n\n' +
                        '**Next Step:** You\'ll need to complete secure identity verification for VMO Pay.\n\n' +
                        '**What you\'ll need:**\n' +
                        '• Government ID (driver\'s license or passport)\n' +
                        '• Bank account info for receiving payments\n' +
                        '• Business tax ID (SSN or EIN)\n\n' +
                        '**This takes 3-5 minutes.** Click the button below to complete verification in a new tab. When done, click "Return to VMO" and you\'ll come right back here to continue! 🚀',
                        true
                    );
                    
                    // Add button to open payment provider onboarding
                    this.addStripeOnboardingButton(prov.onboarding_url, prov.account_id);
                    
                    // Save state for when user returns
                    this.ecomOnboarding.stripeAccountId = prov.account_id;
                    this.ecomOnboarding.awaitingReturn = true;
                    
                    // Start polling for completion
                    this.startStripeCompletionCheck(prov.account_id);
                    return;
                } else if (prov && prov.account_id) {
                    // Old custom account flow (fallback)
                    this.addWizardMessage('✅ VMO Pay account prepared. Next, add a few products so your shop has buy buttons that work right away. Please list 1–5 products in this format, one per line:\n\nName | 19.99 | usd | stock 10 | type item | ship yes', true);
                    this.ecomOnboarding.step = 3;
                    return;
                }
            } catch (e) {
                // fallthrough to retry or skip
            }
            this.addWizardMessage('I couldn’t auto-configure payments just now. You can still continue—add products below and we’ll prompt you to finish payouts later. Please list products as: Name | 19.99 | usd | stock 10 | type item | ship yes', true);
            this.ecomOnboarding.step = 3;
            return;
        }

        if (step === 3) {
            const products = this.parseProductsList(clean);
            if (!products.length) {
                this.addWizardMessage('I didn’t catch any products. Try again like:\nBasic T-Shirt | 19.99 | usd | stock 25 | type item | ship yes', true);
                return;
            }
            this.addWizardMessage('Adding your products to the store catalog…', true);
            try {
                await this.upsertProductCatalog(products);
                this.addWizardMessage('✅ Products saved. I’ll also ensure your Shop and Product pages are generated. Visitors will see Buy buttons that route to secure Stripe Checkout with platform fees handled.', true);
                // Record into consultation data for downstream generators
                this.consultationData = this.consultationData || {};
                this.consultationData.ecommerce = this.consultationData.ecommerce || {};
                this.consultationData.ecommerce.products = products;
                this.ecomOnboarding.active = false;
                this.ecomOnboarding.completed = true;
                // Small nudge to continue the broader consultation
                this.addWizardMessage('If you have shipping preferences (self-fulfill vs. integrate later), tell me now. Otherwise, we can continue with the rest of your business strategy.', true);
                return;
            } catch (e) {
                this.addWizardMessage('Saving products failed. You can try again with the same format or say “skip” to continue.', true);
                return;
            }
        }
    }

    async provisionStripeAccount(kyc) {
        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) || (window.location.origin + '/wp-json/');
        const url = apiRoot + 'vmo-builder/v1/stripe/connect/provision';
        const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(kyc || {}) });
        if (!res.ok) throw new Error('Provision failed');
        return res.json();
    }

    async upsertProductCatalog(products) {
        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) || (window.location.origin + '/wp-json/');
        const url = apiRoot + 'vmo-builder/v1/store/products';
        const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ products }) });
        if (!res.ok) throw new Error('Upsert failed');
        return res.json();
    }

    addStripeOnboardingButton(onboardingUrl, accountId) {
        const buttonHtml = `
            <div class="vmo-stripe-onboarding-action" style="margin: 20px 0; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; text-align: center;">
                <a href="${onboardingUrl}" target="_blank" class="vmo-stripe-button" style="display: inline-block; padding: 15px 40px; background: white; color: #667eea; font-weight: bold; font-size: 16px; border-radius: 8px; text-decoration: none; box-shadow: 0 4px 15px rgba(0,0,0,0.2); transition: transform 0.2s;" 
                   onmouseover="this.style.transform='scale(1.05)'" 
                   onmouseout="this.style.transform='scale(1)'">
                    🔒 Complete Stripe Verification
                </a>
                <p style="color: white; margin-top: 15px; font-size: 14px;">
                    Opens in new tab • Takes 3-5 minutes • Secure & encrypted
                </p>
                <p style="color: rgba(255,255,255,0.9); margin-top: 10px; font-size: 12px;">
                    <strong>⚠️ Important:</strong> After completing verification, look for the "Return to VMO" button on the Stripe page, or just close the tab and I'll detect completion automatically!
                </p>
            </div>
        `;
        
        const messagesContainer = document.getElementById('vmoConversationalMessages') || this.chatMessages;
        if (messagesContainer) {
            const shouldAutoScroll = this.isContainerNearBottom(messagesContainer);
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = buttonHtml;
            messagesContainer.appendChild(tempDiv.firstElementChild);
            if (shouldAutoScroll) {
                this.scrollContainerToBottom(messagesContainer);
            }
        }
    }

    async checkStripeAccountStatus(accountId) {
        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) || (window.location.origin + '/wp-json/');
        const url = apiRoot + 'vmo-builder/v1/stripe/check-status';
        try {
            const res = await fetch(url, { 
                method: 'GET', 
                headers: { 'Content-Type': 'application/json' }
            });
            if (!res.ok) return null;
            return res.json();
        } catch (e) {
            return null;
        }
    }

    startStripeCompletionCheck(accountId) {
        // Poll every 5 seconds to check if user completed onboarding
        const pollInterval = 5000;
        let attempts = 0;
        const maxAttempts = 120; // 10 minutes max
        
        const checkCompletion = async () => {
            attempts++;
            
            const status = await this.checkStripeAccountStatus(accountId);
            
            if (status && status.completed) {
                // User completed onboarding!
                clearInterval(this.stripePollingInterval);
                this.onStripeOnboardingComplete();
            } else if (attempts >= maxAttempts) {
                // Timeout after 10 minutes
                clearInterval(this.stripePollingInterval);
                this.addWizardMessage(
                    '⏱ Haven\'t detected completion yet. No worries! You can complete Stripe verification anytime and return here. ' +
                    'For now, let\'s continue with your product catalog. Say "continue" or list your products.',
                    true
                );
            }
        };
        
        // Start polling
        this.stripePollingInterval = setInterval(checkCompletion, pollInterval);
        
        // Also check immediately
        setTimeout(checkCompletion, 2000);
    }

    onStripeOnboardingComplete() {
        // User completed Stripe verification
        this.ecomOnboarding.awaitingReturn = false;
        
        this.addWizardMessage(
            '🎉 Excellent! Your payment account is now verified and ready to accept payments!\n\n' +
            'Now let\'s build your product catalog! I can guide you through adding products conversationally, ' +
            'or you can use a quick bulk format if you prefer.\n\n' +
            '**Tell me about your first product** (name, price, description), or say **"bulk format"** for advanced mode.',
            true
        );
        
        this.ecomOnboarding.step = 3;
        this.ecomOnboarding.substep = 0;
    }

    // ========================================
    // CONVERSATIONAL PRODUCT COLLECTION
    // ========================================

    startConversationalProductCollection() {
        // Reset current product
        this.ecomOnboarding.currentProduct = {
            name: '',
            price_cents: 0,
            currency: 'usd',
            description: '',
            images: [],
            videos: [],
            product_type: 'item',
            stock_tracking: false,
            stock_qty: 0,
            shipping_required: true,
            variants: []
        };
        
        this.ecomOnboarding.substep = 1; // Start with product name
        
        this.addWizardMessage(
            '✨ Great! Let\'s add your first product.\n\n' +
            '**What\'s the product called?** (e.g., "Organic Cotton T-Shirt" or "Premium Coffee Blend")',
            true
        );
    }

    async handleConversationalProduct(text) {
        const substep = this.ecomOnboarding.substep;
        const product = this.ecomOnboarding.currentProduct;
        const clean = (text || '').trim();

        // Allow user to skip at any time
        if (clean.toLowerCase() === 'skip' || clean.toLowerCase() === 'done' || clean.toLowerCase() === 'finish') {
            await this.finalizeProductCatalog();
            return;
        }

        // Substep 1: Product Name
        if (substep === 1) {
            if (!clean) {
                this.addWizardMessage('Please tell me the product name, or say "skip" to finish adding products.', true);
                return;
            }
            
            product.name = clean;
            this.ecomOnboarding.substep = 2;
            
            this.addWizardMessage(
                `Perfect! "${product.name}" sounds great! 💫\n\n` +
                `**What\'s the price?** (e.g., "$24.99" or "19.50" or "€29.99")`,
                true
            );
            return;
        }

        // Substep 2: Price
        if (substep === 2) {
            const price = this.extractPrice(clean);
            
            if (!price || price <= 0) {
                this.addWizardMessage('I didn\'t catch a valid price. Try again like: "$24.99" or "19.50"', true);
                return;
            }
            
            product.price_cents = Math.round(price * 100);
            product.currency = this.extractCurrency(clean) || 'usd';
            this.ecomOnboarding.substep = 3;
            
            const formatted = `${product.currency.toUpperCase()} ${(product.price_cents / 100).toFixed(2)}`;
            this.addWizardMessage(
                `Got it! **${formatted}** 💰\n\n` +
                `**Can you give me a brief description of this product?**\n` +
                `(Or say "skip" and I'll generate one for you based on the name)`,
                true
            );
            return;
        }

        // Substep 3: Description
        if (substep === 3) {
            if (clean.toLowerCase() === 'skip' || clean.toLowerCase() === 'generate' || clean.toLowerCase() === 'auto') {
                // AI-generate description
                product.description = this.generateProductDescription(product.name, product.price_cents / 100);
                this.addWizardMessage(
                    `I\'ll create a description for you: "${product.description}"\n\n` +
                    `You can change it later in your dashboard if needed.`,
                    true
                );
            } else {
                product.description = clean;
                this.addWizardMessage(`Great description! 📝`, true);
            }
            
            this.ecomOnboarding.substep = 4;
            
            this.addWizardMessage(
                `**Do you have any images or videos for this product?**\n\n` +
                `You can:\n` +
                `• Paste image URLs (one per line)\n` +
                `• Say "upload" to add files\n` +
                `• Say "skip" to use a placeholder for now`,
                true
            );
            return;
        }

        // Substep 4: Images/Videos
        if (substep === 4) {
            if (clean.toLowerCase() === 'skip' || clean.toLowerCase() === 'none' || clean.toLowerCase() === 'later') {
                product.images = [];
                this.addWizardMessage(`No problem! You can add images later from your dashboard. 📸`, true);
            } else if (clean.toLowerCase() === 'upload') {
                this.addWizardMessage(
                    `📤 Image upload coming soon! For now, paste image URLs or say "skip" to continue.`,
                    true
                );
                return;
            } else {
                // Extract URLs from text
                const urls = this.extractUrls(clean);
                product.images = urls.filter(url => this.isImageUrl(url));
                product.videos = urls.filter(url => this.isVideoUrl(url));
                
                if (product.images.length > 0) {
                    this.addWizardMessage(`✅ Added ${product.images.length} image(s)!`, true);
                }
                if (product.videos.length > 0) {
                    this.addWizardMessage(`✅ Added ${product.videos.length} video(s)!`, true);
                }
            }
            
            this.ecomOnboarding.substep = 5;
            
            // Check if product might have variants
            if (this.detectsPossibleVariants(product.name, product.description)) {
                this.addWizardMessage(
                    `**Does this product come in different sizes, colors, or variants?**\n\n` +
                    `For example: "Small, Medium, Large" or "Red, Blue, Green" or just say "no"`,
                    true
                );
            } else {
                // Skip to stock
                this.ecomOnboarding.substep = 6;
                this.addWizardMessage(
                    `**How many do you have in stock?**\n\n` +
                    `(Say a number like "50" or "unlimited" if you don't track inventory)`,
                    true
                );
            }
            return;
        }

        // Substep 5: Variants (optional)
        if (substep === 5) {
            if (clean.toLowerCase() === 'no' || clean.toLowerCase() === 'none' || clean.toLowerCase() === 'skip') {
                product.variants = [];
                this.addWizardMessage(`Got it, no variants! 👍`, true);
            } else {
                // Parse variants
                product.variants = this.parseVariants(clean);
                if (product.variants.length > 0) {
                    this.addWizardMessage(
                        `✅ Added ${product.variants.length} variant(s): ${product.variants.join(', ')}`,
                        true
                    );
                }
            }
            
            this.ecomOnboarding.substep = 6;
            this.addWizardMessage(
                `**How many do you have in stock?**\n\n` +
                `(Say a number like "50" or "unlimited" if you don't track inventory)`,
                true
            );
            return;
        }

        // Substep 6: Stock
        if (substep === 6) {
            if (clean.toLowerCase().includes('unlimited') || clean.toLowerCase().includes('don\'t track') || clean.toLowerCase().includes('no limit')) {
                product.stock_tracking = false;
                product.stock_qty = 9999;
                this.addWizardMessage(`Got it! Unlimited stock. 📦`, true);
            } else {
                const qty = this.extractNumber(clean);
                if (qty && qty > 0) {
                    product.stock_tracking = true;
                    product.stock_qty = qty;
                    this.addWizardMessage(`Perfect! ${qty} in stock. 📦`, true);
                } else {
                    this.addWizardMessage(`I didn't catch that. Try: "50" or "unlimited"`, true);
                    return;
                }
            }
            
            this.ecomOnboarding.substep = 7;
            this.addWizardMessage(
                `**Does this product require physical shipping?**\n\n` +
                `Say "yes" for physical products, or "no" for digital downloads/services.`,
                true
            );
            return;
        }

        // Substep 7: Shipping
        if (substep === 7) {
            product.shipping_required = this.detectsYes(clean);
            
            if (product.shipping_required) {
                product.product_type = 'item';
                this.addWizardMessage(`Got it! Physical product with shipping. 📮`, true);
            } else {
                // Detect if digital or service
                if (clean.toLowerCase().includes('digital') || clean.toLowerCase().includes('download')) {
                    product.product_type = 'downloadable';
                    this.addWizardMessage(`Got it! Digital download. 💾`, true);
                } else if (clean.toLowerCase().includes('service') || clean.toLowerCase().includes('consultation')) {
                    product.product_type = 'service';
                    this.addWizardMessage(`Got it! Service-based product. 💼`, true);
                } else {
                    product.product_type = 'item';
                    product.shipping_required = false;
                    this.addWizardMessage(`Got it! No shipping required. ✅`, true);
                }
            }
            
            // Save this product
            await this.saveConversationalProduct();
            
            // Ask if more products
            this.ecomOnboarding.substep = 8;
            this.addWizardMessage(
                `🎉 **Product added successfully!**\n\n` +
                `**Want to add another product?** Say "yes" to continue, or "no" to finish and generate your shop pages.`,
                true
            );
            return;
        }

        // Substep 8: More products?
        if (substep === 8) {
            if (this.detectsYes(clean)) {
                // Start over with new product
                this.startConversationalProductCollection();
            } else {
                // Finalize catalog
                await this.finalizeProductCatalog();
            }
            return;
        }
    }

    async saveConversationalProduct() {
        // Add current product to data array
        this.ecomOnboarding.data.products.push({ ...this.ecomOnboarding.currentProduct });
        
        // Save to backend
        try {
            await this.upsertProductCatalog([this.ecomOnboarding.currentProduct]);
        } catch (e) {
            this.addWizardMessage('⚠️ Had trouble saving that product. It\'s stored locally, we\'ll sync it shortly.', true);
        }
    }

    async finalizeProductCatalog() {
        const productCount = this.ecomOnboarding.data.products.length;
        
        if (productCount === 0) {
            this.addWizardMessage(
                'You haven\'t added any products yet. Want to add at least one? Say "yes" to continue or "skip" to move on.',
                true
            );
            return;
        }
        
        this.addWizardMessage(
            `✅ **Perfect! You've added ${productCount} product(s) to your catalog.**\n\n` +
            `I'm now generating your shop pages with:\n` +
            `• Product catalog page\n` +
            `• Individual product pages\n` +
            `• Secure Stripe checkout buttons\n` +
            `• Inventory tracking\n\n` +
            `This will take just a moment... 🚀`,
            true
        );
        
        // Record into consultation data for downstream generators
        this.consultationData = this.consultationData || {};
        this.consultationData.ecommerce = this.consultationData.ecommerce || {};
        this.consultationData.ecommerce.products = this.ecomOnboarding.data.products;
        
        this.ecomOnboarding.active = false;
        this.ecomOnboarding.completed = true;
        
        setTimeout(() => {
            this.addWizardMessage(
                `🎊 **E-commerce store setup complete!**\n\n` +
                `Your products are live and ready to sell. Customers can now:\n` +
                `• Browse your catalog\n` +
                `• Add items to cart\n` +
                `• Checkout securely with Stripe\n\n` +
                `If you have shipping preferences or want to configure anything else, let me know! Otherwise, we can continue with the rest of your business strategy.`,
                true
            );
        }, 2000);
    }

    // ========================================
    // HELPER METHODS FOR CONVERSATIONAL MODE
    // ========================================

    extractPrice(text) {
        // Extract price from various formats: $24.99, 24.99, €19.99, etc.
        const patterns = [
            /\$\s*([0-9]+(?:\.[0-9]{1,2})?)/,     // $24.99
            /€\s*([0-9]+(?:\.[0-9]{1,2})?)/,      // €24.99
            /£\s*([0-9]+(?:\.[0-9]{1,2})?)/,      // £24.99
            /([0-9]+\.[0-9]{1,2})/,               // 24.99
            /([0-9]+)/                             // 24
        ];
        
        for (const pattern of patterns) {
            const match = text.match(pattern);
            if (match) {
                return parseFloat(match[1]);
            }
        }
        
        return null;
    }

    extractCurrency(text) {
        if (text.includes('$') || text.toLowerCase().includes('usd') || text.toLowerCase().includes('dollar')) return 'usd';
        if (text.includes('€') || text.toLowerCase().includes('eur') || text.toLowerCase().includes('euro')) return 'eur';
        if (text.includes('£') || text.toLowerCase().includes('gbp') || text.toLowerCase().includes('pound')) return 'gbp';
        if (text.toLowerCase().includes('cad')) return 'cad';
        if (text.toLowerCase().includes('aud')) return 'aud';
        return 'usd'; // default
    }

    extractUrls(text) {
        const urlPattern = /(https?:\/\/[^\s]+)/g;
        const matches = text.match(urlPattern);
        return matches || [];
    }

    isImageUrl(url) {
        const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.bmp'];
        const lower = url.toLowerCase();
        return imageExts.some(ext => lower.includes(ext)) || lower.includes('image') || lower.includes('img');
    }

    isVideoUrl(url) {
        const videoExts = ['.mp4', '.webm', '.mov', '.avi', '.mkv'];
        const lower = url.toLowerCase();
        return videoExts.some(ext => lower.includes(ext)) || lower.includes('video') || lower.includes('youtube') || lower.includes('vimeo');
    }

    detectsPossibleVariants(name, description) {
        const text = `${name} ${description}`.toLowerCase();
        const variantKeywords = ['size', 'color', 'variant', 'small', 'medium', 'large', 'red', 'blue', 'black', 'white', 'xl', 'xxl'];
        return variantKeywords.some(keyword => text.includes(keyword));
    }

    parseVariants(text) {
        // Parse comma or line-separated variants
        const separators = [',', '\n', ';', '|'];
        let variants = [text];
        
        for (const sep of separators) {
            if (text.includes(sep)) {
                variants = text.split(sep).map(v => v.trim()).filter(Boolean);
                break;
            }
        }
        
        return variants;
    }

    extractNumber(text) {
        const match = text.match(/([0-9]+)/);
        return match ? parseInt(match[1], 10) : null;
    }

    detectsYes(text) {
        const lower = text.toLowerCase().trim();
        const yesWords = ['yes', 'yeah', 'yep', 'sure', 'ok', 'okay', 'y', 'true', 'correct', 'right', 'definitely', 'absolutely'];
        return yesWords.some(word => lower === word || lower.startsWith(word + ' ') || lower.endsWith(' ' + word));
    }

    generateProductDescription(name, price) {
        // Simple AI-like description generation
        const templates = [
            `High-quality ${name} at an affordable price. Perfect for everyday use.`,
            `Premium ${name} crafted with care. Get yours today for just $${price.toFixed(2)}!`,
            `${name} - A customer favorite! Excellent quality and great value.`,
            `Discover our ${name}. Thoughtfully designed and built to last.`,
            `${name} - Professional grade quality at an accessible price point.`
        ];
        
        return templates[Math.floor(Math.random() * templates.length)];
    }
    
    // Previous wizard question
    previousWizardQuestion() {
        if (this.currentQuestionIndex > 0) {
            this.currentQuestionIndex--;
        } else {
            // Go to previous category
            const currentCategoryIndex = this.categoryOrder.indexOf(this.currentCategory);
            if (currentCategoryIndex > 0) {
                this.currentCategory = this.categoryOrder[currentCategoryIndex - 1];
                this.currentQuestionIndex = this.wizardQuestions[this.currentCategory].length - 1;
            }
        }
        
        this.askWizardQuestion();
        
        // Hide previous button on first question
        const isFirstQuestion = this.currentCategory === this.categoryOrder[0] && this.currentQuestionIndex === 0;
        if (isFirstQuestion) {
            document.getElementById('vmo-wizard-previous')?.style.setProperty('display', 'none');
        }
    }
    
    // Skip wizard question
    skipWizardQuestion() {
        const categoryQuestions = this.wizardQuestions[this.currentCategory];
        const currentQuestion = categoryQuestions[this.currentQuestionIndex];
        
        if (!this.consultationData[this.currentCategory]) {
            this.consultationData[this.currentCategory] = {};
        }
        
        this.consultationData[this.currentCategory][currentQuestion.key] = '[Skipped]';
        
        this.addWizardMessage('[Skipped this question]', false);
        this.currentQuestionIndex++;
        
        setTimeout(() => {
            this.askWizardQuestion();
        }, 500);
    }
    
    // Format message text with markdown and proper structure
    formatMessageText(text) {
        if (!text || typeof text !== 'string') return text;
        
        // Don't format if already contains HTML
        if (/<[^>]+>/.test(text)) return text;
        
        // Escape HTML to prevent XSS
        text = text.replace(/&/g, '&amp;')
                   .replace(/</g, '&lt;')
                   .replace(/>/g, '&gt;');
        
        // Convert markdown bold and italic
        text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
        text = text.replace(/\*(.+?)\*/g, '<em>$1</em>');
        text = text.replace(/`(.+?)`/g, '<code>$1</code>');
        
        // Process lists
        const lines = text.split('\n');
        let formattedLines = [];
        let inList = false;
        let listType = null;
        
        for (let line of lines) {
            const trimmed = line.trim();
            
            // Detect bullet points
            if (trimmed.startsWith('-') || trimmed.startsWith('*') || trimmed.startsWith('•')) {
                if (!inList || listType !== 'ul') {
                    if (inList) formattedLines.push(`</${listType}>`);
                    formattedLines.push('<ul>');
                    inList = true;
                    listType = 'ul';
                }
                formattedLines.push('<li>' + trimmed.substring(1).trim() + '</li>');
            }
            // Detect numbered lists
            else if (trimmed.match(/^\d+\./)) {
                if (!inList || listType !== 'ol') {
                    if (inList) formattedLines.push(`</${listType}>`);
                    formattedLines.push('<ol>');
                    inList = true;
                    listType = 'ol';
                }
                formattedLines.push('<li>' + trimmed.replace(/^\d+\./, '').trim() + '</li>');
            }
            // Regular line
            else {
                if (inList) {
                    formattedLines.push(`</${listType}>`);
                    inList = false;
                    listType = null;
                }
                formattedLines.push(line);
            }
        }
        
        // Close any open list
        if (inList) {
            formattedLines.push(`</${listType}>`);
        }
        
        text = formattedLines.join('\n');
        
        // Convert paragraphs (double line breaks)
        text = text.replace(/\n\n+/g, '</p><p>');
        
        // Convert single line breaks to <br> (but not inside lists/code)
        text = text.replace(/([^>])\n([^<])/g, '$1<br>$2');
        
        // Wrap in paragraph if not already wrapped
        if (!text.startsWith('<')) {
            text = '<p>' + text + '</p>';
        }
        
        // Clean up empty paragraphs
        text = text.replace(/<p>\s*<\/p>/g, '');
        text = text.replace(/<p>\s*<br>\s*<\/p>/g, '');
        
        return text;
    }

    // Add message to wizard conversation
    isContainerNearBottom(container, threshold = 100) {
        if (!container) return false;
        const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
        return distanceFromBottom <= threshold;
    }

    scrollContainerToBottom(container) {
        if (!container) return;
        container.scrollTop = container.scrollHeight;
    }

    addWizardMessage(message, isFromAI = true, suggestions = null, messageType = 'normal') {
        // Flexible signature support: addWizardMessage('ai'|'system', 'message')
        if ((message === 'ai' || message === 'system') && typeof isFromAI === 'string') {
            message = isFromAI;
            isFromAI = true;
        }
        console.log('🔧 DEBUG: addWizardMessage called with:', { 
            message: typeof message === 'string' ? message.substring(0, 100) + '...' : message, 
            isFromAI, 
            messageType,
            messageLength: typeof message === 'string' ? message.length : 'not string'
        });
        
        const conversation = document.getElementById('vmo-wizard-conversation');
        if (!conversation) {
            console.error('🔧 DEBUG: No conversation element found');
            return;
        }
        const shouldAutoScroll = this.isContainerNearBottom(conversation);
        
        // Validate message content
        if (!message || typeof message !== 'string' || message.trim() === '') {
            console.error('🔧 DEBUG: Empty or invalid message passed to addWizardMessage:', message);
            return; // Don't create empty message bubbles
        }
        
        const messageDiv = document.createElement('div');
        messageDiv.className = isFromAI ? 'vmo-ai-message' : 'vmo-user-message';
        
        if (messageType === 'typing') {
            this.addTypingIndicator();
            return;
        }
        
        if (isFromAI) {
            console.log('🔧 DEBUG: Creating AI message with content:', message.substring(0, 50) + '...');
            const formattedMessage = this.formatMessageText(message);
            const pluginMeta = (window.vmoAjax || window.vmo_ajax || {});
            const pluginBase = String(pluginMeta.pluginUrl || pluginMeta.plugin_url || '').replace(/\/+$/, '');
            const avatarMarkup = pluginBase
                ? `<img src="${pluginBase}/assets/vmo-icon.svg" alt="VMO AI" />`
                : '🤖';
            messageDiv.innerHTML = `
                <div class="vmo-ai-avatar">
                    ${avatarMarkup}
                </div>
                <div class="vmo-message-content">
                    <div class="vmo-message-text">${formattedMessage}</div>
                </div>
            `;
        } else {
            const formattedMessage = this.formatMessageText(message);
            messageDiv.innerHTML = `
                <div class="vmo-user-message-content">
                    <div class="vmo-message-text">${formattedMessage}</div>
                </div>
            `;
        }
        
        conversation.appendChild(messageDiv);
        if (shouldAutoScroll) {
            this.scrollContainerToBottom(conversation);
        }
        
        // Add suggestions if provided
        if (suggestions && suggestions.length > 0) {
            this.showWizardSuggestions(suggestions);
        } else {
            this.clearWizardSuggestions();
        }

        // Auto TTS for AI messages (only plain text messages)
        if (isFromAI && messageType === 'normal') {
            const containsHTML = /<[^>]+>/.test(message) || /vmo-/.test(message);
            if (!containsHTML) {
                this.speakMessage(message, false);
            }
        }
    }
    
    // Show wizard suggestions
    showWizardSuggestions(suggestions) {
        const suggestionsContainer = document.getElementById('vmo-wizard-suggestions');
        if (!suggestionsContainer) return;
        
        suggestionsContainer.innerHTML = '';
        suggestions.forEach(suggestion => {
            const btn = document.createElement('button');
            btn.className = 'vmo-wizard-suggestion';
            btn.textContent = suggestion;
            btn.onclick = () => {
                document.getElementById('vmo-wizard-response').value = suggestion;
                this.sendWizardResponse();
            };
            suggestionsContainer.appendChild(btn);
        });
    }
    
    // Clear wizard suggestions
    clearWizardSuggestions() {
        const suggestionsContainer = document.getElementById('vmo-wizard-suggestions');
        if (suggestionsContainer) {
            suggestionsContainer.innerHTML = '';
        }
    }

    // Send message to AI and get response
    async sendAIMessage(prompt, isSystemMessage = false) {
        console.log('🔧 DEBUG: sendAIMessage called with prompt:', prompt);
        console.log('🔧 DEBUG: vmoAjax object:', vmoAjax);
        
        try {
            // Create proper chat format for conversation using recent history for context
            const chat = [];
            chat.push({
                role: 'system',
                content: 'You are a professional business consultant conducting an active consultation session. ⚠️ CRITICAL: The user has ALREADY clicked the Business Wizard button and is IN a live consultation with you RIGHT NOW. DO NOT recommend clicking the Business Wizard button, starting a consultation, or using any red buttons - you ARE the Business Wizard, the consultation is ALREADY ACTIVE. Provide clear, helpful, and conversational responses. Do not include HTML or markdown. Keep responses natural, concise, and human. If the user asks for clarification, explain the previous question plainly with simple examples before proceeding. IMPORTANT: Politely refuse any request that is illegal, unsafe, or outside the permitted scope of this assistant. When refusing, be calm and professional, and if appropriate, suggest compliant alternatives. Consider the user\'s stated business/location context when referring to legal limitations.'
            });
            // Include the last N messages of history to preserve context
            const history = Array.isArray(this.conversationHistory) ? this.conversationHistory.slice(-12) : [];
            history.forEach(m => {
                chat.push({ role: m.role === 'user' ? 'user' : 'assistant', content: m.content });
            });
            // Append the new user message/prompt
            chat.push({ role: 'user', content: prompt });

            console.log('🔧 DEBUG: Chat format created:', chat);

            const formData = new FormData();
            formData.append('action', 'vmo_conversation_chat'); // Use conversation-specific action
            formData.append('chat_type', 'consultant'); // ✅ CRITICAL: Identify as Business Consultant AI
            // Server expects 'security' with nonce created using 'vmo_builder_nonce'
            const nonce = (window.vmo_ajax && vmo_ajax.nonce) || (window.vmoAjax && (vmoAjax.nonce || vmoAjax.security)) || '';
            formData.append('security', nonce);
            formData.append('chat', JSON.stringify(chat));

            console.log('🔧 DEBUG: FormData created with action: vmo_conversation_chat, chat_type: consultant');
            console.log('🔧 DEBUG: AJAX URL:', vmoAjax.ajaxurl);

            // Resolve ajax URL from localized objects for compatibility
            const ajaxUrl = (window.vmo_ajax && vmo_ajax.ajaxurl) || (window.vmoAjax && (vmoAjax.ajaxurl || vmoAjax.ajax_url)) || '/wp-admin/admin-ajax.php';
            const response = await fetch(ajaxUrl, {
                method: 'POST',
                body: formData
            });

            console.log('🔧 DEBUG: Fetch response status:', response.status);

            if (!response.ok) {
                console.error('🔧 DEBUG: HTTP Error:', response.status, response.statusText);
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            // Read raw text for debugging and robust JSON parsing
            const responseText = await response.text();
            console.log('🔧 DEBUG: Raw AJAX response text:', responseText);
            let data;
            try {
                data = JSON.parse(responseText);
            } catch (err) {
                console.error('🔧 DEBUG: Failed to parse JSON:', err, responseText);
                throw new Error('Invalid JSON response');
            }
            console.log('🔧 DEBUG: Parsed AJAX Response:', data);
            console.log('🔧 DEBUG: Response success flag:', data.success);
            console.log('🔧 DEBUG: Response data object:', data.data);
            console.log('🔧 DEBUG: Response data.response:', data.data?.response);
            
            if (!data.success) {
                console.error('🔧 DEBUG: AJAX Error - data.data:', data.data);
                console.error('🔧 DEBUG: AJAX Error - data.data.message:', data.data?.message);
                throw new Error(data.data?.message || 'Conversation failed');
            }

            // Ensure we have a proper data.data object
            if (!data.data || typeof data.data !== 'object') {
                console.error('🔧 DEBUG: Invalid data.data structure:', data.data);
                throw new Error('Invalid response structure');
            }

            // Extract response content - must be from data.data.response only
            // Extract response content and allow reassignment after cleaning
            let content = data.data && typeof data.data.response === 'string'
                ? data.data.response
                : null;
            
            console.log('🔧 DEBUG: Extracted content:', content);
            console.log('🔧 DEBUG: Content type:', typeof content);
            
            // Validate content string
            if (!content) {
                console.error('🔧 DEBUG: data.data.response is missing or not a string:', data.data);
                throw new Error('No valid content in response');
            }
            // Ensure content is a valid string
            if (!content || typeof content !== 'string') {
                console.error('🔧 DEBUG: Missing or invalid content in response:', content);
                console.error('🔧 DEBUG: Full data.data object:', data.data);
                throw new Error('No valid content in response');
            }
            
            if (typeof content !== 'string') {
                console.warn('🔧 DEBUG: Non-string response, using fallback:', content);
                return this.generateExpertFallbackResponse();
            }

            // Clean content without mutating original
            const stripped = content.replace(/<[^>]*>/g, '').trim();
            const cleaned = stripped.replace(/\*\*/g, '').replace(/\*/g, '');
            console.log('🔧 DEBUG: Cleaned content:', cleaned);
            // Check for boolean values or invalid responses
            if (!cleaned || cleaned === 'true' || cleaned === 'false' || 
                cleaned.includes('true false') || cleaned.length < 10) {
                console.warn('🔧 DEBUG: Invalid cleaned content, using fallback:', cleaned);
                return this.generateExpertFallbackResponse(cleaned);
            }
            console.log('🔧 DEBUG: Final content to return:', cleaned);
            return cleaned;

        } catch (error) {
            console.error('🔧 DEBUG: Exception in sendAIMessage:', error);
            console.error('🔧 DEBUG: Error message:', error.message);
            console.error('🔧 DEBUG: Error stack:', error.stack);
            return this.generateExpertFallbackResponse();
        }
    }

    // Add typing indicator
    addTypingIndicator() {
        const conversation = document.getElementById('vmo-wizard-conversation');
        if (!conversation) return;
        const shouldAutoScroll = this.isContainerNearBottom(conversation);

        const typingDiv = document.createElement('div');
        typingDiv.className = 'vmo-ai-message vmo-typing-indicator';
        typingDiv.id = 'vmo-typing-indicator';
        typingDiv.innerHTML = `
            <div class="vmo-ai-avatar">🤖</div>
            <div class="vmo-message-content">
                <div class="vmo-typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
        `;
        conversation.appendChild(typingDiv);
        if (shouldAutoScroll) {
            this.scrollContainerToBottom(conversation);
        }
    }

    // Remove typing indicator
    removeTypingIndicator() {
        const typingIndicator = document.getElementById('vmo-typing-indicator');
        if (typingIndicator) {
            typingIndicator.remove();
        }
    }

    // Complete consultation and move to generation
    completeConsultation() {
        // Save final consultation data
        this.saveClientResponse('consultation_complete', {
            conversationHistory: this.conversationHistory,
            insights: this.clientIntelligence,
            timestamp: new Date().toISOString()
        });

        // Add download log button before deploying agents
        setTimeout(() => {
            this.addWizardMessage("🎉 Excellent! Your consultation planning is complete. I now have the strategic insights needed to assemble your comprehensive business package and website draft.", true);
            
            // Add download log option
            setTimeout(() => {
                this.addDownloadLogButton();
                
                setTimeout(() => {
                    this.addWizardMessage("Ready to deploy my team of AI specialists? They'll create your complete business package including your website, legal documents, SEO strategy, and business plan.", true);
                    
                    setTimeout(() => {
                        this.initiateMultiAgentSystem();
                    }, 2000);
                }, 3000);
            }, 2000);
        }, 1500);
    }

    // Add download log button to conversation
    addDownloadLogButton() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'vmo-wizard-message vmo-wizard-message-ai';
        messageDiv.innerHTML = `
            <div class="vmo-wizard-message-content">
                <div class="vmo-download-log-container">
                    <p>📋 <strong>Download your consultation log:</strong></p>
                    <button id="vmo-download-consultation-log" class="vmo-download-log-btn">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="7,10 12,15 17,10"/>
                            <line x1="12" y1="15" x2="12" y2="3"/>
                        </svg>
                        Download Conversation Log
                    </button>
                </div>
            </div>
        `;

        const messagesContainer = document.getElementById('vmo-wizard-messages');
        if (messagesContainer) {
            const shouldAutoScroll = this.isContainerNearBottom(messagesContainer);
            messagesContainer.appendChild(messageDiv);
            if (shouldAutoScroll) {
                this.scrollContainerToBottom(messagesContainer);
            }
        }

        // Bind download functionality
        document.getElementById('vmo-download-consultation-log')?.addEventListener('click', () => {
            this.downloadConsultationLog();
        });
    }

    // Download consultation log as formatted text file
    downloadConsultationLog() {
        const timestamp = new Date().toLocaleDateString();
        const businessName = this.getBusinessNameFromConversation() || 'Business';
        
        let logContent = `# VMO AI Business Consultation Log
Date: ${timestamp}
Business: ${businessName}
Consultant: VMO AI Expert Business Consultant

## Consultation Summary
This document contains the complete conversation between ${businessName} and the VMO AI business consultant. This strategic consultation forms the foundation for the comprehensive business package including website, legal documents, SEO strategy, and business plan.

---

## Conversation Transcript

`;

        // Add conversation history
        this.conversationHistory.forEach((msg, index) => {
            const role = msg.role === 'user' ? '**Client**' : '**AI Consultant**';
            const content = msg.content.replace(/\n/g, '\n   ');
            logContent += `### ${index + 1}. ${role}:\n   ${content}\n\n`;
        });

        logContent += `---

## Next Steps
✅ Multi-agent AI system deployment
✅ Strategic analysis by 5 specialist AI agents
✅ Complete website generation with SEO optimization
✅ Legal documentation package creation
✅ Business plan and financial projections
✅ Marketing strategy implementation

Generated by VMO AI Business Development System
© ${new Date().getFullYear()} VMO AI Website Builder
`;

        // Create and download file
        const blob = new Blob([logContent], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${businessName.replace(/[^a-zA-Z0-9]/g, '_')}_Business_Consultation_${new Date().toISOString().split('T')[0]}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        this.showToast('📋 Consultation log downloaded successfully!', 'success');
    }

    // Extract business name from conversation for file naming
    getBusinessNameFromConversation() {
        for (const msg of this.conversationHistory) {
            if (msg.role === 'user') {
                // Look for business name patterns in user responses
                const content = msg.content.toLowerCase();
                if (content.includes('business') || content.includes('company') || content.includes('startup')) {
                    // Try to extract a likely business name (simple heuristic)
                    const words = msg.content.split(' ');
                    for (let i = 0; i < words.length - 1; i++) {
                        if (words[i].toLowerCase().includes('called') || 
                            words[i].toLowerCase().includes('named') ||
                            words[i].toLowerCase().includes('business')) {
                            return words[i + 1]?.replace(/[^a-zA-Z0-9]/g, '') || 'Business';
                        }
                    }
                }
            }
        }
        return 'Business';
    }

    // Generate expert fallback responses when AI fails
    generateExpertFallbackResponse(userResponse = '') {
        const responseCount = this.conversationHistory.filter(m => m.role === 'user').length;
        // Safely handle undefined or non-string userResponse
        const lowercaseResponse = typeof userResponse === 'string'
            ? userResponse.toLowerCase()
            : '';
        // If user asked for clarification, restate the last assistant question simply
        const askedForClarification = /what do you mean|how do you mean|i don't understand|i dont understand|explain|what are you talking|not sure i understand|clarify/.test(lowercaseResponse);
        if (askedForClarification) {
            const lastAssistantMsg = [...this.conversationHistory].reverse().find(m => m.role === 'assistant');
            const lastQuestion = lastAssistantMsg?.content || 'the previous question';
            return `Sure—let me clarify what I meant by: "${lastQuestion}".

In simple terms, I’m trying to understand your current business situation so I can tailor the plan for you.

For example:
- Local service business: You might be a home cleaning company wanting more bookings in your city.
- Online product business: You might sell digital templates and want better SEO and a smoother checkout.

Does that help? Would you like to proceed with this topic or explore another area?`;
        }
        
        // Expert-level fallback responses based on conversation context
        const fallbackResponses = [
            // Early conversation (responses 1-3)
            "Excellent. Now, let me understand your competitive landscape better. Who are your primary competitors, and what specific advantages do you have that they cannot easily replicate?",
            
            "That's insightful. Tell me about your target customer's pain points. What keeps them awake at night, and how does your solution address their most pressing concerns?",
            
            "I see potential here. What's your go-to-market strategy? How do you plan to acquire your first 100 customers, and what's your customer acquisition cost thesis?",
            
            // Mid conversation (responses 4-6)
            "Fascinating. Let's discuss your business model. What are your primary revenue streams, and how do you plan to achieve sustainable unit economics?",
            
            "That's strategic thinking. Now, what operational challenges do you anticipate as you scale? What systems and processes will be critical to your growth?",
            
            "Good insight. Tell me about your team and key partnerships. What core competencies do you need to build or acquire to execute your vision?",
            
            // Late conversation (responses 7+)
            "Perfect. I'm getting a comprehensive picture of your business. What's your 18-month milestone that would indicate you're on track to dominate this market?",
            
            "Excellent strategic thinking. Based on everything you've shared, I believe I have sufficient intelligence to deploy my specialist team. Let me now engage our AI experts to analyze different aspects of your business and create your comprehensive implementation plan."
        ];
        
        // Select appropriate response based on conversation depth
        let selectedResponse;
        if (responseCount >= 8) {
            // Trigger completion for late-stage conversations
            selectedResponse = fallbackResponses[fallbackResponses.length - 1];
            setTimeout(() => this.completeConsultation(), 2000);
        } else if (responseCount >= 7) {
            selectedResponse = fallbackResponses[fallbackResponses.length - 2];
        } else {
            selectedResponse = fallbackResponses[Math.min(responseCount - 1, fallbackResponses.length - 3)];
        }
        
    return selectedResponse || "Tell me more about that aspect of your business strategy. What opportunities do you see there?";
    }

    // Save client response to database for future use
    async saveClientResponse(questionKey, responseData) {
        try {
            const formData = new FormData();
            formData.append('action', 'vmo_save_client_response');
            formData.append('nonce', vmoAjax.nonce);
            formData.append('user_id', vmoAjax.userId || 0);
            formData.append('question_key', questionKey);
            formData.append('response_data', JSON.stringify(responseData));
            formData.append('session_id', this.sessionId || Date.now());

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

            const data = await response.json();
            if (data.success) {
                console.log('✅ Client intelligence saved:', questionKey);
            }
        } catch (error) {
            console.error('❌ Failed to save client intelligence:', error);
        }
    }

    // Load client intelligence (placeholder - use consultation status/profile where needed)
    async loadClientIntelligence() { return this.clientIntelligence || {}; }

    // Initiate multi-agent system
    async initiateMultiAgentSystem() {
        this.addWizardMessage("🤖 Deploying AI specialist team:\n\n• Strategy Analyst - Market research & competitive analysis\n• Legal Specialist - Document generation & compliance\n• SEO Expert - Search engine optimization\n• Content Creator - Website & marketing materials\n• Business Planner - Financial projections & growth strategy", true);

        setTimeout(() => {
            this.showWizardReview();
        }, 3000);
    }
    
    // Enhanced wizard progress system - HEADER FILLS WITH LIME GREEN
    updateWizardProgress(percentage) {
        const progressFill = document.getElementById('vmo-wizard-progress');
        const progressText = document.getElementById('vmo-wizard-progress-text');
        const progressPercentage = document.getElementById('vmo-wizard-progress-percentage');
        
        if (progressFill) {
            // Smooth animation for header background fill
            progressFill.style.transition = 'width 0.6s ease-in-out';
            progressFill.style.width = `${Math.max(0, Math.min(100, percentage))}%`;
        }
        
        // Optionally update text to show percentage (subtle)
        if (progressText && percentage > 0) {
            progressText.textContent = `Business Consultation ${Math.round(percentage)}%`;
        }
        
        // Update percentage display
        if (progressPercentage) {
            progressPercentage.textContent = `${Math.round(percentage)}%`;
        }
        
        // Update progress milestones
        this.updateProgressMilestones(percentage);
        
        // Update consultation stage indicator
        this.updateConsultationStage(percentage);
    }
    
    // Update progress milestones - ENHANCED UX
    updateProgressMilestones(percentage) {
        const milestones = [
            { threshold: 0, label: 'Starting Consultation', icon: '🚀' },
            { threshold: 20, label: 'Business Analysis', icon: '🏢' },
            { threshold: 40, label: 'Market Research', icon: '📊' },
            { threshold: 60, label: 'Strategy Development', icon: '🎯' },
            { threshold: 80, label: 'Solution Design', icon: '🎨' },
            { threshold: 100, label: 'Implementation Ready', icon: '✅' }
        ];
        
        const currentMilestone = milestones.reverse().find(m => percentage >= m.threshold);
        
        if (currentMilestone) {
            const progressText = document.getElementById('vmo-wizard-progress-text');
            if (progressText) {
                progressText.innerHTML = `${currentMilestone.icon} ${currentMilestone.label}`;
            }
            
            // Update milestone indicators if they exist
            const milestoneIndicators = document.querySelectorAll('.vmo-milestone-indicator');
            milestoneIndicators.forEach((indicator, index) => {
                const milestoneThreshold = milestones[milestones.length - 1 - index].threshold;
                if (percentage >= milestoneThreshold) {
                    indicator.classList.add('completed');
                    indicator.style.background = '#4caf50';
                } else {
                    indicator.classList.remove('completed');
                    indicator.style.background = '#ddd';
                }
            });
        }
    }
    
    // Update consultation stage - BUSINESS-FOCUSED
    updateConsultationStage(percentage) {
        const stages = [
            { min: 0, max: 15, name: 'Initial Discovery', desc: 'Understanding your business foundation' },
            { min: 15, max: 35, name: 'Business Analysis', desc: 'Analyzing market position and opportunities' },
            { min: 35, max: 55, name: 'Strategic Planning', desc: 'Developing growth strategies' },
            { min: 55, max: 75, name: 'Solution Design', desc: 'Creating your digital presence' },
            { min: 75, max: 90, name: 'Implementation Planning', desc: 'Preparing for launch' },
            { min: 90, max: 100, name: 'Launch Ready', desc: 'Everything is set for success' }
        ];
        
        const currentStage = stages.find(stage => percentage >= stage.min && percentage < stage.max) || stages[stages.length - 1];
        
        // Update stage display if element exists
        const stageDisplay = document.getElementById('vmo-consultation-stage');
        if (stageDisplay && currentStage) {
            stageDisplay.innerHTML = `
                <div class="vmo-stage-name">${currentStage.name}</div>
                <div class="vmo-stage-desc">${currentStage.desc}</div>
            `;
        }
    }
    
    // Show wizard review phase
    showWizardReview() {
        document.getElementById('vmo-wizard-conversation')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'block');
        
        this.generateBusinessPlan();
    }
    
    // Generate business plan summary from AI conversation
    async generateBusinessPlan() {
        const reviewContent = document.getElementById('vmo-review-content');
        if (!reviewContent) return;
        
        // Show loading state
        reviewContent.innerHTML = `
            <div class="vmo-plan-loading">
                <div class="vmo-loading-spinner"></div>
                <p>🤖 Generating your comprehensive business plan...</p>
                <p><small>This includes competitor analysis, legal documents, and strategic recommendations</small></p>
            </div>
        `;

        // Build conversation summary for AI
        const conversationSummary = this.conversationHistory.map(msg => 
            `${msg.role === 'user' ? 'User' : 'AI'}: ${msg.content}`
        ).join('\n\n');

        const businessPlanPrompt = `Based on this business consultation conversation, generate a comprehensive business plan:

${conversationSummary}

Create a detailed business plan with these sections:

1. **EXECUTIVE SUMMARY**
2. **BUSINESS OVERVIEW**  
3. **COMPETITOR ANALYSIS** (with specific competitor names and strategies to overcome them)
4. **MARKET SHARE PROJECTIONS** (realistic timelines and percentages)
5. **LEGAL DOCUMENTS NEEDED** (comprehensive list based on business type)
6. **STRATEGIC ACTION PLAN** (step-by-step with timelines)
7. **FINANCIAL PROJECTIONS** (revenue potential and costs)

Format as clean HTML with proper headings and bullet points. Make it professional and actionable.`;

        try {
            const businessPlan = await this.sendAIMessage(businessPlanPrompt, false);
            
            reviewContent.innerHTML = `
                <div class="vmo-business-plan">
                    <h3>📋 Your Comprehensive Business Plan</h3>
                    <div class="vmo-plan-content">
                        ${businessPlan}
                    </div>
                    <div class="vmo-plan-actions">
                        <button class="vmo-wizard-btn vmo-wizard-btn-secondary" onclick="vmoConversationalAI.editBusinessPlan()">
                            ✏️ Edit Plan
                        </button>
                        <button class="vmo-wizard-btn vmo-wizard-btn-primary" onclick="vmoConversationalAI.approveBusinessPlan()">
                            ✅ Approve & Generate Business Package
                        </button>
                    </div>
                </div>
            `;
            
            // Store the generated plan
            this.comprehensiveBusinessResults = businessPlan;
            
        } catch (error) {
            console.error('Business plan generation error:', error);
            reviewContent.innerHTML = `
                <div class="vmo-plan-error">
                    <h3>⚠️ Plan Generation Error</h3>
                    <p>Unable to generate business plan. Please try again.</p>
                    <button class="vmo-wizard-btn" onclick="vmoConversationalAI.generateBusinessPlan()">
                        🔄 Retry Generation
                    </button>
                </div>
            `;
        }
        
        // Update progress text
        const progressText = document.getElementById('vmo-wizard-progress-text');
        if (progressText) {
            progressText.textContent = 'Review & Approval';
        }
    }

    // Update agent status in UI
    updateAgentStatus(agentId, status) {
        const agentElement = document.getElementById(agentId);
        if (!agentElement) return;

        const statusElement = agentElement.querySelector('.vmo-agent-status');
        const agentItem = agentElement;

        agentItem.classList.remove('active', 'complete', 'error');
        
        switch(status) {
            case 'active':
                agentItem.classList.add('active');
                statusElement.textContent = '🔄';
                break;
            case 'complete':
                agentItem.classList.add('complete');
                statusElement.textContent = '✅';
                break;
            case 'error':
                agentItem.classList.add('error');
                statusElement.textContent = '❌';
                break;
        }
    }

    // Display multi-agent results
    displayMultiAgentResults(reviewContent, results) {
        const resultSections = Object.values(results).map(agent => `
            <div class="vmo-agent-result">
                <h4>📊 ${agent.name} Report</h4>
                <div class="vmo-agent-content">${agent.content}</div>
            </div>
        `).join('');

        reviewContent.innerHTML = `
            <div class="vmo-multi-agent-results">
                <h3>🎯 Comprehensive Business Intelligence Report</h3>
                <div class="vmo-results-summary">
                    <p>Your AI specialist team has completed a comprehensive analysis. Below are the detailed reports from each specialist.</p>
                </div>
                
                ${resultSections}
                
                <div class="vmo-results-actions">
                    <button class="vmo-wizard-btn vmo-wizard-btn-secondary" onclick="vmoConversationalAI.editMultiAgentResults()">
                        ✏️ Edit Reports
                    </button>
                    <button class="vmo-wizard-btn vmo-wizard-btn-primary" onclick="vmoConversationalAI.approveAndExecute()">
                        ✅ Approve & Execute Implementation
                    </button>
                </div>
            </div>
        `;

        // Store comprehensive results
        this.comprehensiveBusinessResults = results;
        
        // Save to client intelligence database
        this.saveClientResponse('multi_agent_analysis', {
            results: results,
            timestamp: new Date().toISOString(),
            status: 'completed'
        });
    }

    // Approve and execute implementation
    async approveAndExecute() {
        this.showToast('Implementation approved! Generating live website with SEO optimization...', 'success');
        
        setTimeout(() => {
            this.executeImplementation();
        }, 2000);
    }

    // Execute implementation with live preview
    async executeImplementation() {
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'block');
        
        const generationContent = document.getElementById('vmo-generation-content');
        if (generationContent) {
            generationContent.innerHTML = `
                <div class="vmo-implementation-progress">
                    <h3>🚀 Implementation in Progress</h3>
                    <div class="vmo-progress-items">
                        <div class="vmo-progress-item active" id="website-creation">
                            <span class="vmo-progress-icon">🌐</span>
                            <span>Creating multi-page website...</span>
                            <span class="vmo-progress-status">🔄</span>
                        </div>
                        <div class="vmo-progress-item" id="seo-implementation">
                            <span class="vmo-progress-icon">🚀</span>
                            <span>Implementing SEO optimization...</span>
                            <span class="vmo-progress-status">⏳</span>
                        </div>
                        <div class="vmo-progress-item" id="legal-docs">
                            <span class="vmo-progress-icon">⚖️</span>
                            <span>Generating legal documents...</span>
                            <span class="vmo-progress-status">⏳</span>
                        </div>
                        <div class="vmo-progress-item" id="live-preview">
                            <span class="vmo-progress-icon">👁️</span>
                            <span>Setting up live preview...</span>
                            <span class="vmo-progress-status">⏳</span>
                        </div>
                    </div>
                </div>
            `;
        }

        // Execute implementation steps
        await this.runImplementationSteps();
    }

    // Edit business plan
    editBusinessPlan() {
        const reviewContent = document.getElementById('vmo-review-content');
        if (!reviewContent || !this.comprehensiveBusinessResults) return;

        const currentPlan = this.comprehensiveBusinessResults;
        
        reviewContent.innerHTML = `
            <div class="vmo-plan-editor">
                <h3>✏️ Edit Your Business Plan</h3>
                <div class="vmo-editor-container">
                    <textarea id="vmo-plan-editor" class="vmo-plan-textarea" rows="20">${currentPlan}</textarea>
                </div>
                <div class="vmo-editor-actions">
                    <button class="vmo-wizard-btn vmo-wizard-btn-secondary" onclick="vmoConversationalAI.cancelEdit()">
                        ❌ Cancel
                    </button>
                    <button class="vmo-wizard-btn vmo-wizard-btn-primary" onclick="vmoConversationalAI.saveBusinessPlan()">
                        💾 Save Changes
                    </button>
                </div>
            </div>
        `;
    }

    // Save edited business plan
    saveBusinessPlan() {
        const editor = document.getElementById('vmo-plan-editor');
        if (!editor) return;

        this.comprehensiveBusinessResults = editor.value;
        this.showToast('Business plan updated successfully!', 'success');
        
        // Return to review view
        this.displaySavedPlan();
    }

    // Cancel edit and return to review
    cancelEdit() {
        this.displaySavedPlan();
    }

    // Display the saved plan
    displaySavedPlan() {
        const reviewContent = document.getElementById('vmo-review-content');
        if (!reviewContent) return;

        reviewContent.innerHTML = `
            <div class="vmo-business-plan">
                <h3>📋 Your Comprehensive Business Plan</h3>
                <div class="vmo-plan-content">
                    ${this.comprehensiveBusinessResults}
                </div>
                <div class="vmo-plan-actions">
                    <button class="vmo-wizard-btn vmo-wizard-btn-secondary" onclick="vmoConversationalAI.editBusinessPlan()">
                        ✏️ Edit Plan
                    </button>
                    <button class="vmo-wizard-btn vmo-wizard-btn-primary" onclick="vmoConversationalAI.approveBusinessPlan()">
                        ✅ Approve & Generate Business Package
                    </button>
                </div>
            </div>
        `;
    }
    
    // Approve business plan and start AI generation
    approveBusinessPlan() {
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'block');
        
        this.startAIGeneration();
    }
    
    // Start AI agents generation process
    startAIGeneration() {
        this.updateGenerationProgress(0, 'Initializing AI agents...');
        
        const agents = [
            { id: 'vmo-agent-designer', name: 'Web Designer', task: 'Creating multi-page website...', delay: 2000 },
            { id: 'vmo-agent-analyst', name: 'Business Analyst', task: 'Conducting market research...', delay: 4000 },
            { id: 'vmo-agent-legal', name: 'Legal Document', task: 'Drafting legal documents...', delay: 6000 },
            { id: 'vmo-agent-content', name: 'Content Creator', task: 'Writing business content...', delay: 8000 },
            { id: 'vmo-agent-seo', name: 'SEO Marketing', task: 'Optimizing for search engines...', delay: 10000 }
        ];
        
        let completedAgents = 0;
        
        agents.forEach((agent, index) => {
            setTimeout(() => {
                this.completeAgent(agent.id);
                completedAgents++;
                
                const progress = (completedAgents / agents.length) * 100;
                const status = completedAgents === agents.length ? 
                    'All AI agents completed! Preparing results...' : 
                    `${agent.name} Agent completed. ${agents.length - completedAgents} agents remaining...`;
                
                this.updateGenerationProgress(progress, status);
                
                if (completedAgents === agents.length) {
                    setTimeout(() => {
                        this.showGenerationResults();
                    }, 2000);
                }
            }, agent.delay);
        });
    }
    
    // Complete an AI agent
    completeAgent(agentId) {
        const agent = document.getElementById(agentId);
        const indicator = agent?.querySelector('.vmo-agent-indicator');
        if (indicator) {
            indicator.textContent = '✅';
            indicator.style.color = '#00ff9a';
        }
    }
    
    // Update generation progress
    updateGenerationProgress(percentage, status) {
        const progressFill = document.getElementById('vmo-generation-progress');
        const statusText = document.getElementById('vmo-generation-status');
        
        if (progressFill) {
            progressFill.style.width = `${percentage}%`;
        }
        
        if (statusText) {
            statusText.textContent = status;
        }
    }
    
    // Show generation results
    showGenerationResults() {
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-results')?.style.setProperty('display', 'block');
        
        // Update progress to 100%
        this.updateWizardProgress(100);
        
        const progressText = document.getElementById('vmo-wizard-progress-text');
        if (progressText) {
            progressText.textContent = 'Complete!';
        }
        
        this.showToast('🎉 Your complete business package is ready!', 'success');
    }
        
    // VOICE SYSTEM REMOVED: Voice input disabled for No Voice version
    startVoiceInput() {
        // No-op function - voice input completely disabled
        console.log('🔇 Voice input disabled - text-only mode');
        return;
    }
    
    initWizardQuestions() {
        // Comprehensive business consultation questions organized by category
        this.wizardQuestions = {
            business_basics: [
                {
                    key: "business_name",
                    question: "Hi! I'm your comprehensive business consultant AI. Let's start with the basics - what's the name of your business or project?",
                    type: "text",
                    required: true,
                    suggestions: ["My Business", "Startup Name", "Company LLC"]
                },
                {
                    key: "industry_type",
                    question: "What industry does your business operate in?",
                    type: "text",
                    required: true,
                    suggestions: ["Technology", "Healthcare", "Retail", "Food & Beverage", "Professional Services", "Manufacturing", "Education", "Real Estate"]
                },
                {
                    key: "business_stage",
                    question: "What stage is your business currently in?",
                    type: "text",
                    required: true,
                    suggestions: ["Just an idea", "Starting up", "Early stage", "Established", "Growing", "Expanding"]
                },
                {
                    key: "business_description",
                    question: "Can you describe what your business does in 2-3 sentences?",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "location",
                    question: "Where is your business located? (City, State/Country)",
                    type: "text",
                    required: true,
                    suggestions: ["New York, NY", "Los Angeles, CA", "London, UK", "Online/Remote"]
                }
            ],
            target_market: [
                {
                    key: "target_customers",
                    question: "Who are your ideal customers? Describe your target audience in detail.",
                    type: "textarea",
                    required: true,
                    suggestions: ["Small business owners", "Young professionals", "Families with children", "Senior citizens", "Students"]
                },
                {
                    key: "customer_demographics",
                    question: "What are the key demographics of your target customers? (Age, income, location, etc.)",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "customer_pain_points",
                    question: "What problems or pain points does your business solve for customers?",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "market_size",
                    question: "How would you describe the size of your target market?",
                    type: "text",
                    required: true,
                    suggestions: ["Local market", "Regional market", "National market", "International market", "Niche market"]
                },
                {
                    key: "customer_budget",
                    question: "What's the typical budget range your customers have for your products/services?",
                    type: "text",
                    required: true,
                    suggestions: ["Under $100", "$100-$500", "$500-$2,000", "$2,000-$10,000", "Over $10,000"]
                }
            ],
            business_model: [
                {
                    key: "revenue_model",
                    question: "How does your business make money? What's your revenue model?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Product sales", "Service fees", "Subscription model", "Commission-based", "Advertising revenue", "Licensing"]
                },
                {
                    key: "main_products_services",
                    question: "What are your main products or services? List your top 3-5 offerings.",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "pricing_strategy",
                    question: "What's your pricing strategy? How do you price your products/services?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Competitive pricing", "Premium pricing", "Value-based pricing", "Cost-plus pricing", "Freemium model"]
                },
                {
                    key: "competitors",
                    question: "Who are your main competitors? List 3-5 businesses you compete with.",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "competitive_advantage",
                    question: "What makes your business different from competitors? What's your unique selling proposition?",
                    type: "textarea",
                    required: true,
                    suggestions: []
                }
            ],
            goals_objectives: [
                {
                    key: "short_term_goals",
                    question: "What are your short-term business goals (next 6-12 months)?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Increase sales", "Launch new product", "Expand team", "Improve online presence", "Get more customers"]
                },
                {
                    key: "long_term_goals",
                    question: "What are your long-term business goals (1-3 years)?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Scale operations", "Expand to new markets", "Achieve profitability", "Build brand recognition", "Exit strategy"]
                },
                {
                    key: "success_metrics",
                    question: "How do you measure success? What are your key performance indicators (KPIs)?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Revenue growth", "Customer acquisition", "Market share", "Profit margins", "Customer satisfaction"]
                },
                {
                    key: "challenges",
                    question: "What are the biggest challenges your business currently faces?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Finding customers", "Cash flow", "Competition", "Marketing", "Operations", "Hiring talent"]
                },
                {
                    key: "website_goals",
                    question: "What do you want your website to achieve for your business?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Generate leads", "Sell products online", "Build brand awareness", "Provide customer support", "Showcase portfolio"]
                }
            ],
            brand_vision: [
                {
                    key: "mission_statement",
                    question: "What's your business mission? Why does your business exist?",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "vision_statement",
                    question: "What's your vision for the future of your business?",
                    type: "textarea",
                    required: true,
                    suggestions: []
                },
                {
                    key: "core_values",
                    question: "What are your core business values? What principles guide your business decisions?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Quality", "Innovation", "Customer service", "Integrity", "Sustainability", "Teamwork"]
                },
                {
                    key: "brand_personality",
                    question: "How would you describe your brand's personality? What tone and style represent your business?",
                    type: "text",
                    required: true,
                    suggestions: ["Professional", "Friendly", "Innovative", "Trustworthy", "Creative", "Authoritative", "Approachable"]
                },
                {
                    key: "brand_colors",
                    question: "Do you have preferred colors for your brand? If not, what colors appeal to you?",
                    type: "text",
                    required: false,
                    suggestions: ["Blue (trust)", "Green (growth)", "Red (energy)", "Orange (creativity)", "Purple (luxury)", "Black (elegance)"]
                }
            ],
            operational_needs: [
                {
                    key: "contact_preferences",
                    question: "How do you prefer customers to contact you?",
                    type: "text",
                    required: true,
                    suggestions: ["Phone", "Email", "Contact form", "Live chat", "Appointment booking", "Social media"]
                },
                {
                    key: "payment_methods",
                    question: "What payment methods do you want to accept?",
                    type: "text",
                    required: true,
                    suggestions: ["Credit cards", "PayPal", "Bank transfer", "Cash", "Stripe", "Square", "Cryptocurrency"]
                },
                {
                    key: "essential_features",
                    question: "What essential features does your website need?",
                    type: "textarea",
                    required: true,
                    suggestions: ["Online store", "Booking system", "Portfolio gallery", "Blog", "Customer portal", "Email newsletter", "Social media integration"]
                },
                {
                    key: "content_management",
                    question: "Who will manage and update your website content?",
                    type: "text",
                    required: true,
                    suggestions: ["Myself", "My team", "Hire someone", "Need training", "Automatic updates preferred"]
                },
                {
                    key: "legal_requirements",
                    question: "Are there any specific legal requirements or compliance needs for your industry?",
                    type: "textarea",
                    required: false,
                    suggestions: ["GDPR compliance", "HIPAA compliance", "Terms of service", "Privacy policy", "Disclaimers", "Industry regulations"]
                }
            ]
        };
        
        // Current consultation state
        this.currentCategory = null;
        this.currentQuestionIndex = 0;
        this.consultationData = {};
        this.categoryOrder = ['business_basics', 'target_market', 'business_model', 'goals_objectives', 'brand_vision', 'operational_needs'];
    }
    
    // Show wizard review phase
    showWizardReview() {
        // Hide conversation, show review section
        document.getElementById('vmo-wizard-conversation')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'block');
        
        // Generate comprehensive summary
        const summary = this.generateComprehensiveBusinessSummary();
        this.addWizardMessage('Excellent! I\'ve gathered comprehensive information about your business. Here\'s a complete summary of your consultation:', true);
        this.addWizardMessage(summary, true);
        
        // Show approve button
        const approveButton = document.getElementById('vmo-wizard-approve-plan');
        if (approveButton) {
            approveButton.style.display = 'block';
            approveButton.textContent = 'Generate Complete Business Package';
        }
        
        this.updateWizardProgress(100);
        const progressText = document.getElementById('vmo-wizard-progress-text');
        if (progressText) {
            progressText.textContent = 'Consultation Plan Ready - Awaiting Generation Approval';
        }
    }
    
    // Generate comprehensive business summary
    generateComprehensiveBusinessSummary() {
        let summary = '<div class="vmo-business-summary">';
        
        const categoryTitles = {
            'business_basics': '🏢 Business Foundation',
            'target_market': '🎯 Target Market Analysis',
            'business_model': '💼 Business Model',
            'goals_objectives': '🎯 Goals & Strategy',
            'brand_vision': '🌟 Brand & Vision',
            'operational_needs': '⚙️ Operational Requirements'
        };
        
        Object.keys(this.consultationData).forEach(category => {
            summary += `<div class="vmo-summary-section">`;
            summary += `<h3>${categoryTitles[category] || category}</h3>`;
            
            Object.keys(this.consultationData[category]).forEach(key => {
                const value = this.consultationData[category][key];
                if (value && value !== '[Skipped]') {
                    const formattedKey = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                    summary += `<p><strong>${formattedKey}:</strong> ${value}</p>`;
                }
            });
            
            summary += `</div>`;
        });
        
        summary += '</div>';
        return summary;
    }
    
    // Approve business plan and start generation
    approveBusinessPlan() {
        this.addWizardMessage('Perfect! Now I\'ll engage our team of AI specialists to create your complete business package...', true);
        
        // Hide review, show generation
        document.getElementById('vmo-wizard-review')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'block');
        
        // Start comprehensive business generation
        setTimeout(() => {
            this.startComprehensiveBusinessGeneration();
        }, 1500);
    }
    
    // Start comprehensive business generation with all agents
    async startComprehensiveBusinessGeneration() {
        this.addWizardMessage('Our specialized AI team is now working on your complete business package...', true);
        
        // Show agent processing UI
        const processingHTML = `
            <div id="vmo-agent-processing" class="vmo-agent-processing-container">
                <div class="vmo-processing-header">
                    <h3>🤖 AI Business Specialists Working on Your Project</h3>
                    <p>Please wait while our comprehensive team analyzes and creates your business package...</p>
                </div>
                <div id="vmo-current-agent" class="vmo-current-agent"></div>
                <div class="vmo-processing-progress">
                    <div class="vmo-progress-bar">
                        <div id="vmo-progress-fill" class="vmo-progress-fill" style="width: 0%"></div>
                    </div>
                    <span id="vmo-progress-percentage">0%</span>
                </div>
                <div class="vmo-agent-list">
                    <div class="vmo-agent-item" id="agent-business-consultant">📊 Business Consultant</div>
                    <div class="vmo-agent-item" id="agent-web-architect">🏗️ Web Architect</div>
                    <div class="vmo-agent-item" id="agent-content-strategist">✍️ Content Strategist</div>
                    <div class="vmo-agent-item" id="agent-legal-compliance">⚖️ Legal Compliance</div>
                    <div class="vmo-agent-item" id="agent-seo-marketing">🚀 SEO & Marketing</div>
                    <div class="vmo-agent-item" id="agent-operations-specialist">⚙️ Operations Specialist</div>
                </div>
            </div>
        `;
        
        this.addWizardMessage(processingHTML, true);
        
        try {
            // Step 1: Start Business Consultation
            this.updateAgentProgress('Starting comprehensive business consultation...', 5);
            this.highlightAgent('agent-business-consultant');
            
            const consultationResult = await this.callBusinessConsultationBackend('start_consultation', this.consultationData);
            this.updateAgentProgress('✅ Business consultation initialized', 15);
            
            // Step 2: Process consultation responses
            this.updateAgentProgress('Processing consultation responses with AI analysis...', 20);
            const analysisResult = await this.callBusinessConsultationBackend('process_consultation', this.consultationData);
            this.updateAgentProgress('✅ Business analysis complete', 35);
            
            // Step 3: Web Architecture Planning
            this.highlightAgent('agent-web-architect');
            this.updateAgentProgress('Designing website architecture...', 40);
            const architectureResult = await this.callBusinessConsultationBackend('web_architecture', this.consultationData);
            this.updateAgentProgress('✅ Website architecture designed', 50);
            
            // Step 4: Content Strategy
            this.highlightAgent('agent-content-strategist');
            this.updateAgentProgress('Creating content strategy and copywriting...', 55);
            const contentResult = await this.callBusinessConsultationBackend('content_strategy', this.consultationData);
            this.updateAgentProgress('✅ Content strategy complete', 65);
            
            // Step 5: Legal Documentation
            this.highlightAgent('agent-legal-compliance');
            this.updateAgentProgress('Generating legal documents...', 70);
            const legalResult = await this.callBusinessConsultationBackend('legal_documents', this.consultationData);
            this.updateAgentProgress('✅ Legal documents ready', 80);
            
            // Step 6: SEO & Marketing
            this.highlightAgent('agent-seo-marketing');
            this.updateAgentProgress('Optimizing SEO and marketing strategy...', 85);
            const seoResult = await this.callBusinessConsultationBackend('seo_marketing', this.consultationData);
            this.updateAgentProgress('✅ SEO optimization complete', 90);
            
            // Step 7: Operations & Final Generation
            this.highlightAgent('agent-operations-specialist');
            this.updateAgentProgress('Finalizing operational systems...', 95);
            const operationsResult = await this.callBusinessConsultationBackend('operations', this.consultationData);
            
            // Step 8: Generate Complete Website
            this.updateAgentProgress('Generating your complete business website...', 98);
            const finalResult = await this.callBusinessWebsiteGeneration(this.consultationData);
            
            this.updateAgentProgress('🎉 Complete business package ready!', 100);
            
            // Show results
            setTimeout(() => {
                this.showComprehensiveBusinessResults(finalResult);
            }, 2000);
            
        } catch (error) {
            console.error('Comprehensive Business Generation Error:', error);
            this.addWizardMessage('I apologize, but there was an issue generating your business package. Our team is working to resolve this. Please try again or contact support for assistance.', true);
            this.updateAgentProgress('❌ Generation failed - please try again', 0);
        }
    }
    
    // Highlight current working agent
    highlightAgent(agentId) {
        // Remove previous highlights
        document.querySelectorAll('.vmo-agent-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // Highlight current agent
        const agentElement = document.getElementById(agentId);
        if (agentElement) {
            agentElement.classList.add('active');
        }
    }
    
    getAjaxUrl() {
        const enhanced = window.vmo_ajax || {};
        const legacy = window.vmoAjax || {};
        return enhanced.ajaxurl || legacy.ajaxurl || legacy.ajax_url || '/wp-admin/admin-ajax.php';
    }

    getNonce() {
        const enhanced = window.vmo_ajax || {};
        const legacy = window.vmoAjax || {};
        return enhanced.nonce || legacy.security || legacy.nonce || '';
    }

    ensureConsultationSessionId() {
        if (this.sessionId) {
            return this.sessionId;
        }

        try {
            const stored = window.localStorage && window.localStorage.getItem('vmo_consultation_session_id');
            if (stored) {
                this.sessionId = stored;
                return this.sessionId;
            }
        } catch (error) {
            // localStorage may be unavailable in restricted browser contexts.
        }

        this.sessionId = `conv_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
        try {
            if (window.localStorage) {
                window.localStorage.setItem('vmo_consultation_session_id', this.sessionId);
            }
        } catch (error) {
            // Session still works for this page load.
        }
        return this.sessionId;
    }

    buildEnhancedConsultationMessage(phase, consultationData) {
        const label = String(phase || 'consultation').replace(/[_-]+/g, ' ');
        const data = consultationData || {};
        const summary = JSON.stringify(data, null, 2);

        if (phase === 'start_consultation') {
            return `Start the enhanced Jerreme business consultation using this captured intake. Continue as the business operating system consultant and identify any missing launch-critical information.\n\n${summary}`;
        }

        return `Continue the enhanced Jerreme business consultation for phase: ${label}. Use the captured intake below as current context, update the consultation state, and ask for only the next missing launch-critical details.\n\n${summary}`;
    }

    // Call the enhanced backend for business consultation phases
    async callBusinessConsultationBackend(phase, consultationData) {
        const ajaxUrl = this.getAjaxUrl();
        const nonce = this.getNonce();
        const sessionId = this.ensureConsultationSessionId();

        const formData = new FormData();
        formData.append('action', 'vmo_process_consultation_message');
        formData.append('security', nonce);
        formData.append('session_id', sessionId);
        formData.append('message', this.buildEnhancedConsultationMessage(phase, consultationData));
        formData.append('context', JSON.stringify({
            source: 'vmo-conversational-compat',
            legacy_phase: phase,
            consultation_data: consultationData || {},
            wizard_data: this.wizardData || {},
            consultation_data_legacy: this.consultationData || {},
        }));

        const response = await fetch(ajaxUrl, { method: 'POST', body: formData });
        const result = await response.json();
        if (!result.success) {
            throw new Error((result.data && (result.data.message || result.data)) || 'Consultation processing failed');
        }
        return result.data;
    }
    
    // Call chunked backend for final website generation
    async callBusinessWebsiteGeneration(consultationData) {
        return this.callChunkedBusinessGeneration(consultationData || {});
    }

    async callChunkedBusinessGeneration(consultationData) {
        const totalChunks = 12;
        const sessionId = this.ensureConsultationSessionId();
        let finalPayload = null;

        for (let chunk = 1; chunk <= totalChunks; chunk++) {
            let attempt = 0;
            let completed = false;
            let lastError = null;

            while (!completed && attempt < 3) {
                attempt++;
                const controller = new AbortController();
                const timeout = window.setTimeout(() => controller.abort(), 600000);

                try {
                    const response = await fetch(this.getAjaxUrl(), {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        signal: controller.signal,
                        body: new URLSearchParams({
                            action: 'vmo_trigger_business_generation',
                            security: this.getNonce(),
                            nonce: this.getNonce(),
                            _ajax_nonce: this.getNonce(),
                            session_id: sessionId,
                            chunk: String(chunk),
                            consultation_data: JSON.stringify(consultationData || {})
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`Generation chunk ${chunk} failed with HTTP ${response.status}`);
                    }

                    const result = await response.json();
                    if (!result.success) {
                        throw new Error((result.data && result.data.message) || `Generation chunk ${chunk} failed`);
                    }

                    finalPayload = result.data || {};
                    completed = true;
                } catch (error) {
                    lastError = error;
                } finally {
                    window.clearTimeout(timeout);
                }

                if (!completed && attempt < 3) {
                    await new Promise(resolve => window.setTimeout(resolve, 1500 * attempt));
                }
            }

            if (!completed) {
                throw lastError || new Error(`Generation chunk ${chunk} could not complete after retries.`);
            }

            if (finalPayload && finalPayload.is_complete) {
                break;
            }
        }

        const websiteDraft = {
            post_id: finalPayload?.post_id || 0,
            preview_url: finalPayload?.preview_url || '',
            homepage_html: finalPayload?.homepage_html || '',
            content: finalPayload?.homepage_html || '',
            pages_map: finalPayload?.pages_map || {},
            builder_state: finalPayload?.builder_state || {},
            project_title: finalPayload?.project_title || '',
            qa_report: finalPayload?.qa_report || {},
            media_complete: !!finalPayload?.media_complete,
            preview_ready: !!finalPayload?.preview_ready,
            publish_ready: !!finalPayload?.publish_ready
        };

        return {
            ...(finalPayload || {}),
            website_draft: websiteDraft,
            draft_id: websiteDraft.post_id,
            preview_url: websiteDraft.preview_ready ? websiteDraft.preview_url : '',
            preview_ready: websiteDraft.preview_ready,
            media_complete: websiteDraft.media_complete,
            content: websiteDraft.homepage_html,
            html: websiteDraft.homepage_html,
            status: websiteDraft.preview_ready ? 'draft' : 'generating_media',
            canonical_pipeline: true,
            chunked_generation: true
        };
    }

    // Synchronous enhanced generation is kept only as a legacy fallback.
    async callEnhancedBusinessWebsiteGeneration(consultationData) {
        const formData = new FormData();
        formData.append('action', 'vmo_generate_business_website_enhanced');
        const nonce = this.getNonce();
        formData.append('security', nonce);
        formData.append('session_id', this.ensureConsultationSessionId());
        formData.append('consultation_data', JSON.stringify(consultationData || {}));
        const ajaxUrl = this.getAjaxUrl();
        const response = await fetch(ajaxUrl, { method: 'POST', body: formData });
        const result = await response.json();
        if (!result.success) {
            throw new Error((result.data && (result.data.message || result.data)) || 'Website generation failed');
        }
        return result.data;
    }
    
    // Start multi-agent processing with real backend calls
    async startAgentProcessing() {
        this.addWizardMessage('ai', 'Our team of AI specialists is now analyzing your business requirements...');
        
        // Show agent processing UI
        const processingHTML = `
            <div id="vmo-agent-processing" class="vmo-agent-processing-container">
                <div class="vmo-processing-header">
                    <h3>AI Business Specialists Working on Your Project</h3>
                    <p>Please wait while our experts analyze your requirements...</p>
                </div>
                <div id="vmo-current-agent" class="vmo-current-agent"></div>
                <div class="vmo-processing-progress">
                    <div class="vmo-progress-bar">
                        <div id="vmo-progress-fill" class="vmo-progress-fill" style="width: 0%"></div>
                    </div>
                    <span id="vmo-progress-percentage">0%</span>
                </div>
            </div>
        `;
        
        this.addWizardMessage('system', processingHTML);
        
        try {
            // Call backend for business analysis
            const analysisResult = await this.callBusinessWizardBackend('business_analysis', this.wizardData);
            this.updateAgentProgress('Business Analysis Complete', 25);
            
            // Design planning
            const designResult = await this.callBusinessWizardBackend('design_planning', this.wizardData);
            this.updateAgentProgress('Design Planning Complete', 50);
            
            // Content creation
            const contentResult = await this.callBusinessWizardBackend('content_creation', this.wizardData);
            this.updateAgentProgress('Content Strategy Complete', 75);
            
            // Legal setup
            const legalResult = await this.callBusinessWizardBackend('legal_setup', this.wizardData);
            this.updateAgentProgress('Legal Documentation Complete', 90);
            
            // Final generation
            this.updateAgentProgress('Generating Complete Business Package...', 95);
            const finalResult = await this.callBusinessWizardGeneration(this.wizardData);
            
            this.updateAgentProgress('Complete!', 100);
            
            // Show results
            setTimeout(() => {
                this.showBusinessResults(finalResult);
            }, 1500);
            
        } catch (error) {
            console.error('Business Wizard Error:', error);
            this.addWizardMessage('ai', 'I apologize, but there was an issue processing your request. Please try again or contact support.');
        }
    }
    
    // Call backend for specific wizard phases
    async callBusinessWizardBackend(phase, responses) {
        return this.callBusinessConsultationBackend(phase, responses);
    }
    
    // Call backend for final generation
    async callBusinessWizardGeneration(responses) {
        return this.callBusinessWebsiteGeneration(responses);
    }
    
    // Update agent processing progress
    updateAgentProgress(status, percentage) {
        const currentAgentDiv = document.getElementById('vmo-current-agent');
        const progressFill = document.getElementById('vmo-progress-fill');
        const progressText = document.getElementById('vmo-progress-percentage');
        
        if (currentAgentDiv) {
            currentAgentDiv.innerHTML = `
                <div class="vmo-agent-status">
                    <i class="fas fa-robot vmo-agent-icon"></i>
                    <span>${status}</span>
                </div>
            `;
        }
        
        if (progressFill) {
            progressFill.style.width = percentage + '%';
        }
        
        if (progressText) {
            progressText.textContent = percentage + '%';
        }
    }
    
    // Show comprehensive business results
    showComprehensiveBusinessResults(results) {
        // Hide generation, show results
        document.getElementById('vmo-wizard-generation')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-results')?.style.setProperty('display', 'block');
        
        const resultsHTML = `
            <div class="vmo-comprehensive-business-results">
                <div class="vmo-results-header">
                    <h2>🎉 Your Complete Business Analysis is Ready!</h2>
                    <p>Based on your responses, we've created a comprehensive business strategy and recommendations.</p>
                </div>
                
                <div class="vmo-results-grid">
                    <div class="vmo-result-card vmo-primary-result">
                        <h3>� Business Strategy Overview</h3>
                        <div class="vmo-business-overview">
                            <div class="vmo-business-detail">
                                <strong>Business Name:</strong> ${results.businessName || 'Your Business'}
                            </div>
                            <div class="vmo-business-detail">
                                <strong>Industry:</strong> ${results.industry || 'General Business'}
                            </div>
                            <div class="vmo-business-detail">
                                <strong>Target Audience:</strong> ${results.targetAudience || 'General Audience'}
                            </div>
                            <div class="vmo-business-detail">
                                <strong>Primary Goals:</strong> ${results.goals || 'Business Growth'}
                            </div>
                        </div>
                        
                        <div class="vmo-recommendations">
                            <h4>💡 Strategic Recommendations</h4>
                            <ul>
                                <li>Develop a strong online presence to reach your target audience</li>
                                <li>Focus on customer engagement and retention strategies</li>
                                <li>Implement digital marketing campaigns tailored to your industry</li>
                                <li>Create professional business assets and documentation</li>
                            </ul>
                        </div>
                        
                        <div class="vmo-next-steps">
                            <h4>🚀 Next Steps</h4>
                            <p>Ready to bring your business vision to life? Let's create a professional website that represents your brand perfectly.</p>
                            <div class="vmo-result-actions">
                                <button class="vmo-btn vmo-btn-primary" onclick="vmoAI.startWebsiteCreation()">
                                    <i class="fas fa-rocket"></i> Create Website Now
                                </button>
                                <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.showTemplateGallery()">
                                    <i class="fas fa-palette"></i> Browse Templates
                                </button>
                            </div>
                        </div>
                    </div>
                            ${selectedTemplate ? `
                                <button class="vmo-btn vmo-btn-accent" onclick="vmoAI.useBusinessTemplate('${selectedTemplate.id}')">
                                    <i class="fas fa-rocket"></i> Use This Template
                                </button>
                            ` : ''}
                        </div>
                    </div>
                    
                    <div class="vmo-result-card">
                        <h3>� Complete Business Analysis</h3>
                        <p>Comprehensive business strategy, competitor analysis, and market positioning</p>
                        <div class="vmo-analysis-summary">
                            <div class="vmo-analysis-item">
                                <i class="fas fa-users"></i>
                                <span>Target Market Analysis</span>
                            </div>
                            <div class="vmo-analysis-item">
                                <i class="fas fa-chart-line"></i>
                                <span>Competitor Research</span>
                            </div>
                            <div class="vmo-analysis-item">
                                <i class="fas fa-bullseye"></i>
                                <span>Growth Strategy</span>
                            </div>
                        </div>
                        <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.viewBusinessAnalysis()">
                            <i class="fas fa-chart-pie"></i> View Full Analysis
                        </button>
                    </div>
                    
                    <div class="vmo-result-card">
                        <h3>📄 Legal Document Suite</h3>
                        <p>Complete legal protection package tailored to your business</p>
                        <div class="vmo-document-list">
                            <div class="vmo-document-item">
                                <i class="fas fa-shield-alt"></i>
                                <span>Privacy Policy</span>
                                <button class="vmo-btn-sm" onclick="vmoAI.downloadDocument('privacy')">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <div class="vmo-document-item">
                                <i class="fas fa-file-contract"></i>
                                <span>Terms of Service</span>
                                <button class="vmo-btn-sm" onclick="vmoAI.downloadDocument('terms')">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <div class="vmo-document-item">
                                <i class="fas fa-exclamation-triangle"></i>
                                <span>Disclaimer</span>
                                <button class="vmo-btn-sm" onclick="vmoAI.downloadDocument('disclaimer')">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="vmo-result-card">
                        <h3>� SEO & Marketing Strategy</h3>
                        <p>Complete digital marketing roadmap and SEO optimization plan</p>
                        <div class="vmo-marketing-highlights">
                            <div class="vmo-highlight-item">
                                <i class="fas fa-search"></i>
                                <span>Keyword Strategy</span>
                            </div>
                            <div class="vmo-highlight-item">
                                <i class="fas fa-share-alt"></i>
                                <span>Social Media Plan</span>
                            </div>
                            <div class="vmo-highlight-item">
                                <i class="fas fa-envelope"></i>
                                <span>Email Marketing</span>
                            </div>
                        </div>
                        <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.viewMarketingStrategy()">
                            <i class="fas fa-rocket"></i> View Strategy
                        </button>
                    </div>
                    
                    <div class="vmo-result-card">
                        <h3>📋 Business Plan PDF</h3>
                        <p>Professional business plan document ready for investors or lenders</p>
                        <div class="vmo-plan-features">
                            <span class="vmo-plan-tag">💼 Executive Summary</span>
                            <span class="vmo-plan-tag">📈 Financial Projections</span>
                            <span class="vmo-plan-tag">🎯 Market Analysis</span>
                        </div>
                        <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.downloadBusinessPlan()">
                            <i class="fas fa-file-pdf"></i> Download Business Plan
                        </button>
                    </div>
                    
                    <div class="vmo-result-card">
                        <h3>⚙️ Operational Systems</h3>
                        <p>Payment processing, contact forms, and business automation setup</p>
                        <div class="vmo-operations-list">
                            <div class="vmo-ops-item">
                                <i class="fas fa-credit-card"></i>
                                <span>Payment Integration</span>
                            </div>
                            <div class="vmo-ops-item">
                                <i class="fas fa-envelope"></i>
                                <span>Contact Forms</span>
                            </div>
                            <div class="vmo-ops-item">
                                <i class="fas fa-calendar"></i>
                                <span>Booking System</span>
                            </div>
                        </div>
                        <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.configureOperations()">
                            <i class="fas fa-cogs"></i> Configure
                        </button>
                    </div>
                </div>
                
                <div class="vmo-results-summary">
                    <h3>📈 What You're Getting:</h3>
                    <div class="vmo-summary-grid">
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>Professional multi-page website</span>
                        </div>
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>Complete legal protection</span>
                        </div>
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>SEO & marketing strategy</span>
                        </div>
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>Business plan & analysis</span>
                        </div>
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>Operational systems setup</span>
                        </div>
                        <div class="vmo-summary-item">
                            <i class="fas fa-check-circle"></i>
                            <span>Competitor research</span>
                        </div>
                    </div>
                </div>
                
                <div class="vmo-results-actions">
                    <button class="vmo-btn vmo-btn-primary vmo-btn-large" onclick="vmoAI.publishCompleteBusinessPackage()">
                        <i class="fas fa-rocket"></i> Launch Your Business Now
                    </button>
                    <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.refineBusinessPackage()">
                        <i class="fas fa-edit"></i> Refine & Customize
                    </button>
                    <button class="vmo-btn vmo-btn-outline" onclick="vmoAI.startNewConsultation()">
                        <i class="fas fa-plus"></i> Start New Consultation
                    </button>
                </div>
            </div>
        `;
        
        this.addWizardMessage('system', resultsHTML);
        
        // Store results for later use
        this.comprehensiveBusinessResults = results;
        
        // Show success toast
        this.showToast('🎉 Your complete business package is ready! Review all components above.', 'success');
    }
    
    // Helper functions for comprehensive business results
    previewCompleteWebsite() {
        if (this.comprehensiveBusinessResults?.website?.main_page) {
            const previewWindow = window.open('', '_blank', 'width=1200,height=800');
            previewWindow.document.write(this.comprehensiveBusinessResults.website.main_page);
            previewWindow.document.close();
        } else {
            this.showToast('Website preview not available', 'warning');
        }
    }
    
    customizeWebsite() {
        this.addWizardMessage('ai', 'Opening website customization options...');
        // This would integrate with the existing VMO customization system
        this.showToast('Website customization will be available in the next update', 'info');
    }
    
    viewBusinessAnalysis() {
        const analysis = this.comprehensiveBusinessResults?.business_analysis;
        if (analysis) {
            const modal = document.createElement('div');
            modal.className = 'vmo-modal-overlay';
            modal.innerHTML = `
                <div class="vmo-modal vmo-analysis-modal">
                    <div class="vmo-modal-header">
                        <h3>📊 Complete Business Analysis</h3>
                        <button class="vmo-modal-close" onclick="this.closest('.vmo-modal-overlay').remove()">×</button>
                    </div>
                    <div class="vmo-modal-content">
                        <div class="vmo-analysis-tabs">
                            <button class="vmo-tab-btn active" onclick="vmoAI.showAnalysisTab('market')">Market Analysis</button>
                            <button class="vmo-tab-btn" onclick="vmoAI.showAnalysisTab('competitors')">Competitors</button>
                            <button class="vmo-tab-btn" onclick="vmoAI.showAnalysisTab('strategy')">Strategy</button>
                        </div>
                        <div class="vmo-analysis-content">
                            <div id="market-analysis" class="vmo-tab-content active">
                                ${analysis.market_analysis || 'Market analysis will be displayed here.'}
                            </div>
                            <div id="competitor-analysis" class="vmo-tab-content">
                                ${analysis.competitor_analysis || 'Competitor analysis will be displayed here.'}
                            </div>
                            <div id="strategy-analysis" class="vmo-tab-content">
                                ${analysis.strategy_recommendations || 'Strategy recommendations will be displayed here.'}
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            this.showToast('Business analysis not available', 'warning');
        }
    }
    
    showAnalysisTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.vmo-tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('.vmo-tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // Show selected tab
        document.getElementById(tabName + '-analysis')?.classList.add('active');
        event.target.classList.add('active');
    }
    
    downloadDocument(type) {
        const documents = this.comprehensiveBusinessResults?.legal_documents;
        if (!documents) {
            this.showToast('Legal documents not available', 'warning');
            return;
        }
        
        let content = '';
        let filename = '';
        
        switch (type) {
            case 'privacy':
                content = documents.privacy_policy || '';
                filename = 'privacy-policy.txt';
                break;
            case 'terms':
                content = documents.terms_of_service || '';
                filename = 'terms-of-service.txt';
                break;
            case 'disclaimer':
                content = documents.disclaimer || '';
                filename = 'disclaimer.txt';
                break;
        }
        
        if (content) {
            this.downloadTextFile(content, filename);
        } else {
            this.showToast(`${type} document not available`, 'warning');
        }
    }
    
    viewMarketingStrategy() {
        const strategy = this.comprehensiveBusinessResults?.marketing_strategy;
        if (strategy) {
            const modal = document.createElement('div');
            modal.className = 'vmo-modal-overlay';
            modal.innerHTML = `
                <div class="vmo-modal vmo-marketing-modal">
                    <div class="vmo-modal-header">
                        <h3>🚀 Digital Marketing Strategy</h3>
                        <button class="vmo-modal-close" onclick="this.closest('.vmo-modal-overlay').remove()">×</button>
                    </div>
                    <div class="vmo-modal-content">
                        <div class="vmo-marketing-tabs">
                            <button class="vmo-tab-btn active" onclick="vmoAI.showMarketingTab('seo')">SEO Strategy</button>
                            <button class="vmo-tab-btn" onclick="vmoAI.showMarketingTab('social')">Social Media</button>
                            <button class="vmo-tab-btn" onclick="vmoAI.showMarketingTab('content')">Content Plan</button>
                        </div>
                        <div class="vmo-marketing-content">
                            <div id="seo-strategy" class="vmo-tab-content active">
                                ${strategy.seo_strategy || 'SEO strategy will be displayed here.'}
                            </div>
                            <div id="social-strategy" class="vmo-tab-content">
                                ${strategy.social_media_plan || 'Social media strategy will be displayed here.'}
                            </div>
                            <div id="content-strategy" class="vmo-tab-content">
                                ${strategy.content_marketing || 'Content marketing plan will be displayed here.'}
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            this.showToast('Marketing strategy not available', 'warning');
        }
    }
    
    showMarketingTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.vmo-tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('.vmo-tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // Show selected tab
        document.getElementById(tabName + '-strategy')?.classList.add('active');
        event.target.classList.add('active');
    }
    
    downloadBusinessPlan() {
        const businessPlan = this.comprehensiveBusinessResults?.business_plan;
        if (businessPlan) {
            // If it's a PDF URL, open it
            if (businessPlan.includes('.pdf') || businessPlan.startsWith('http')) {
                window.open(businessPlan, '_blank');
            } else {
                // If it's text content, download as file
                this.downloadTextFile(businessPlan, 'business-plan.txt');
            }
        } else {
            this.showToast('Business plan not available', 'warning');
        }
    }
    
    configureOperations() {
        const operations = this.comprehensiveBusinessResults?.operational_systems;
        if (operations) {
            const modal = document.createElement('div');
            modal.className = 'vmo-modal-overlay';
            modal.innerHTML = `
                <div class="vmo-modal vmo-operations-modal">
                    <div class="vmo-modal-header">
                        <h3>⚙️ Operational Systems Configuration</h3>
                        <button class="vmo-modal-close" onclick="this.closest('.vmo-modal-overlay').remove()">×</button>
                    </div>
                    <div class="vmo-modal-content">
                        <div class="vmo-operations-content">
                            <h4>Payment Processing</h4>
                            <p>${operations.payment_setup || 'Payment processing configuration will be displayed here.'}</p>
                            
                            <h4>Contact Forms</h4>
                            <p>${operations.contact_forms || 'Contact form setup instructions will be displayed here.'}</p>
                            
                            <h4>Booking System</h4>
                            <p>${operations.booking_system || 'Booking system configuration will be displayed here.'}</p>
                            
                            <div class="vmo-operations-actions">
                                <button class="vmo-btn vmo-btn-primary" onclick="vmoAI.implementOperations()">
                                    <i class="fas fa-cogs"></i> Implement Now
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        } else {
            this.showToast('Operational systems not available', 'warning');
        }
    }
    
    implementOperations() {
        this.showToast('Operational systems implementation will be available in the next update', 'info');
    }
    
    async publishCompleteBusinessPackage() {
        if (!this.comprehensiveBusinessResults) {
            this.showToast('No business package to publish', 'warning');
            return;
        }
        
        try {
            this.addWizardMessage('ai', '🚀 Publishing your complete business package...');
            
            // Call the backend to publish everything
            const formData = new FormData();
            formData.append('action', 'vmo_publish_complete_business');
            formData.append('nonce', vmoAjax.nonce);
            formData.append('business_data', JSON.stringify(this.comprehensiveBusinessResults));
            formData.append('consultation_data', JSON.stringify(this.consultationData));
            
            const response = await fetch(vmoAjax.ajaxurl, {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            if (result.success) {
                this.addWizardMessage('ai', '🎉 Success! Your complete business package has been published. You can now access your website and all business documents.');
                this.showToast('Business package published successfully!', 'success');
                
                // Optionally open the published website
                if (result.data.website_url) {
                    setTimeout(() => {
                        window.open(result.data.website_url, '_blank');
                    }, 2000);
                }
            } else {
                throw new Error(result.data || 'Publishing failed');
            }
            
        } catch (error) {
            console.error('Business Package Publishing Error:', error);
            this.addWizardMessage('ai', '❌ There was an issue publishing your business package. Please try again or contact support.');
            this.showToast('Publishing failed. Please try again.', 'error');
        }
    }
    
    refineBusinessPackage() {
        this.addWizardMessage('ai', 'What would you like to refine about your business package? You can ask me to modify any aspect of your website, documents, or strategy.');
        
        // Switch back to conversation mode for refinements
        document.getElementById('vmo-wizard-results')?.style.setProperty('display', 'none');
        document.getElementById('vmo-wizard-conversation')?.style.setProperty('display', 'block');
        
        // Enable conversation mode
        document.getElementById('vmo-wizard-response').placeholder = 'Ask me to refine or modify anything about your business package...';
        document.getElementById('vmo-wizard-send')?.style.setProperty('display', 'block');
    }
    
    startNewConsultation() {
        if (confirm('Are you sure you want to start a new business consultation? This will clear your current session.')) {
            this.resetWizardState();
            this.openBusinessWizard();
        }
    }
    
    downloadTextFile(content, filename) {
        const blob = new Blob([content], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }
    
    async publishCompleteWebsite() {
        if (!this.businessResults) return;
        
        try {
            this.addWizardMessage('ai', 'Publishing your complete website...');
            
            // Call the existing VMO publish system with the generated content
            const formData = new FormData();
            formData.append('action', 'vmo_publish_website');
            formData.append('nonce', vmoAjax.nonce);
            formData.append('project_data', JSON.stringify({
                html: this.businessResults.website.main_page,
                title: this.wizardData.business_name || 'My Business Website',
                additional_pages: this.businessResults.website.additional_pages
            }));
            
            const response = await fetch(vmoAjax.ajaxurl, {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            if (result.success) {
                this.addWizardMessage('ai', `🎉 Success! Your website has been published and is now live at: <a href="${result.data.url}" target="_blank">${result.data.url}</a>`);
            } else {
                throw new Error(result.data || 'Publishing failed');
            }
        } catch (error) {
            console.error('Publishing error:', error);
            this.addWizardMessage('ai', 'There was an error publishing your website. Please try again or use the manual publish option.');
        }
    }
    
    closeBusinessWizard() {
        const modal = document.getElementById('vmo-business-wizard-modal');
        if (modal) {
            modal.style.display = 'none';
            // Remove background blur when closing
            document.body.classList.remove('vmo-wizard-active');
        }
        this.resetWizardState();
        if (typeof showToast === 'function') {
            showToast('Business Development Wizard closed', 'info');
        }
    }
    
    generateWizardSummary() {
        return `Based on our conversation, I'll create:

📌 **Business**: ${this.wizardData.business_name} (${this.wizardData.business_type})
🎯 **Target Audience**: ${this.wizardData.target_audience}
🎨 **Style**: ${this.wizardData.design_style}
${this.wizardData.brand_colors ? `🌈 **Colors**: ${this.wizardData.brand_colors}` : ''}
📄 **Pages**: ${this.wizardData.required_pages}
🚀 **Goal**: ${this.wizardData.website_goal}
💫 **Call-to-Action**: ${this.wizardData.call_to_action}

This will be a complete, professional website tailored specifically for your business.`;
    }
    
    startConversation(agentType = 'designer') {
        this.currentAgent = agentType;
        this.showModal('vmo-ai-conversation-modal');
        
        const agentNames = {
            'designer': 'VMO AI Designer',
            'business': 'VMO Business Analyst',
            'content': 'VMO Content Creator',
            'seo': 'VMO SEO Specialist'
        };
        
        document.getElementById('vmo-conversation-agent-name').textContent = agentNames[agentType] || 'VMO AI Designer';
        
        // Start with a greeting
        this.addConversationMessage('ai', 'Hi! I\'m your AI website designer. What kind of website would you like to create today?');
        
        this.showSuggestions([
            'Create a business website',
            'Build an e-commerce store',
            'Design a portfolio site',
            'Make a blog website'
        ]);
    }
    
    startVoiceSession() {
        this.isVoiceEnabled = true;
        this.startConversation('designer');
        this.addConversationMessage('ai', 'Voice mode activated! I can hear you and speak back. How can I help you create your website?');
        this.speak('Voice mode activated! How can I help you create your website?');
    }
    
    sendMessage() {
        const messageInput = document.getElementById('vmo-user-message');
        const message = messageInput.value.trim();
        
        if (!message) return;
        
        this.addConversationMessage('user', message);
        messageInput.value = '';
        
        // Check for wizard approval
        if (this.wizardStep >= this.wizardQuestions.length && message.toLowerCase().includes('approved')) {
            this.generateWebsiteFromWizard();
            return;
        }
        
        // Process the message with AI
        this.processAIMessage(message);
    }
    
    async processAIMessage(message) {
        // Prevent duplicate AI responses while already processing
        if (this.aiResponding) {
            console.log('AI already responding, ignoring duplicate request');
            return;
        }

        // Quick store ops: try to handle user-intentful commands without AI
        const handled = await this.tryHandleQuickStoreCommand(message);
        if (handled) return;

        const handledEmailOperator = await this.tryHandleJarvisEmailOperatorCommand(message);
        if (handledEmailOperator) return;

        // Jarvis nav routing: try to handle navigation commands locally
        if (typeof window.vmoJarvisRoute === 'function') {
            const route = window.vmoJarvisRoute(message);
            if (route && route.tab) {
                if (typeof switchTab === 'function') switchTab(route.tab, null);
                this.addConversationMessage('ai', 'Navigating to ' + route.tab + '.');
                return;
            }
            if (route && route.action && typeof window[route.action] === 'function') {
                window[route.action]();
                this.addConversationMessage('ai', 'Opening that for you now.');
                return;
            }
        }

        this.aiResponding = true;
        this.addConversationMessage('ai', 'Let me think about that...', true);

        try {
            const response = await this.callAIAgent(this.currentAgent, message);
            this.removeLoadingMessage();
            this.addConversationMessage('ai', response);
            if (this.isVoiceEnabled) {
                this.speak(response);
            }
            this.generateSuggestions(message, response);
        } catch (error) {
            this.removeLoadingMessage();
            this.addConversationMessage('ai', 'I apologize, but I encountered an error. Please try again.');
            console.error('AI processing error:', error);
        } finally {
            this.aiResponding = false;
        }
    }

    async tryHandleJarvisEmailOperatorCommand(message) {
        const text = String(message || '').trim();
        if (!text || !/\b(email|emails|inbox|mail|message|messages|reply|draft)\b/i.test(text)) {
            return false;
        }
        if (/^\s*(write|compose|create|send)\s+(?:an?\s+)?email\s*$/i.test(text)) {
            return false;
        }

        try {
            const response = await fetch((window.vmo_ajax?.ajaxurl) || vmoAjax.ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'vmo_jarvis_command',
                    security: (window.vmo_ajax?.nonce) || vmoAjax.nonce,
                    command: text
                })
            });
            const payload = await response.json();
            if (!payload || !payload.success || !payload.data || payload.data.type !== 'email_operator') {
                return false;
            }

            const data = payload.data;
            if (data.tab && typeof switchTab === 'function') {
                switchTab(data.tab, null);
            }
            const html = this.formatJarvisEmailOperatorResponse(data);
            this.addConversationMessage('ai', html);
            if (this.isVoiceEnabled) {
                this.speak(data.message || this.stripHtml(html));
            }
            if (data.operation === 'draft_reply' && typeof window.vmoSwitchMailFolder === 'function') {
                window.vmoSwitchMailFolder('drafts');
            } else if (data.operation === 'send_reply' && typeof window.vmoSwitchMailFolder === 'function') {
                window.vmoSwitchMailFolder('sent');
            } else if ((data.operation === 'sync_inbox' || data.operation === 'mark_done' || data.operation === 'list_emails' || data.operation === 'read_email') && typeof window.vmoSwitchMailFolder === 'function') {
                window.vmoSwitchMailFolder('inbox');
            }
            return true;
        } catch (error) {
            console.warn('Jarvis email operator command failed:', error);
            return false;
        }
    }

    formatJarvisEmailOperatorResponse(data) {
        const message = this.escapeHtml(data.message || 'Email command completed.');
        let html = `<div class="vmo-jarvis-email-response"><p>${message}</p>`;

        if (Array.isArray(data.emails) && data.emails.length) {
            html += '<div style="display:grid;gap:8px;margin-top:10px;">';
            data.emails.slice(0, 8).forEach(email => {
                html += `<div style="border:1px solid rgba(148,163,184,.25);border-radius:8px;padding:10px;background:rgba(255,255,255,.04);">
                    <div style="font-weight:700;">#${this.escapeHtml(email.index || '')} ${this.escapeHtml(email.subject || '(No subject)')}</div>
                    <div style="font-size:12px;opacity:.8;">From ${this.escapeHtml(email.from_email || 'unknown')} - ${this.escapeHtml(email.created_at || '')}</div>
                    <div style="font-size:12px;margin-top:4px;">${this.escapeHtml(email.snippet || '')}</div>
                </div>`;
            });
            html += '</div>';
        }

        if (data.email) {
            html += `<div style="border:1px solid rgba(148,163,184,.25);border-radius:8px;padding:10px;background:rgba(255,255,255,.04);margin-top:10px;">
                <div style="font-weight:700;">${this.escapeHtml(data.email.subject || '(No subject)')}</div>
                <div style="font-size:12px;opacity:.8;">From ${this.escapeHtml(data.email.from_email || 'unknown')} - ${this.escapeHtml(data.email.created_at || '')}</div>
                <div style="font-size:12px;margin-top:6px;white-space:pre-wrap;">${this.escapeHtml(data.email.body || data.email.snippet || '')}</div>
            </div>`;
        }

        if (data.draft_preview) {
            html += `<div style="border-left:3px solid #0fe1ff;padding:8px 10px;margin-top:10px;background:rgba(15,225,255,.08);font-size:12px;">
                <strong>Draft preview</strong><br>${this.escapeHtml(data.draft_preview)}
            </div>`;
        }

        html += '</div>';
        return html;
    }

    stripHtml(value) {
        const div = document.createElement('div');
        div.innerHTML = String(value || '');
        return div.textContent || div.innerText || '';
    }

    escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, char => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        }[char]));
    }

    // Try to parse and execute quick store operations directly from chat
    async tryHandleQuickStoreCommand(text) {
        const t = (text || '').toLowerCase();
        const paymentsEnabled = (window.vmo_ajax && !!vmo_ajax.payments_enabled) || (window.vmoAjax && !!vmoAjax.payments_enabled);
        if (!paymentsEnabled) return false;

        // Update stock: "update stock of Basic T-Shirt to 12" / "set stock Basic T-Shirt 12"
        let m = t.match(/(?:update|set)\s+stock\s+(?:of\s+)?(.+?)\s+(?:to\s+)?(\d{1,7})\b/);
        if (m && m[1] && m[2]) {
            const productName = m[1].trim();
            const qty = parseInt(m[2], 10);
            try {
                const found = await this.findProductByNameOrSlug(productName);
                if (!found) {
                    this.addConversationMessage('ai', `I couldn't find a product named "${productName}". You can add it with: Add product -> Name | 19.99 | usd | stock 10 | type item | ship yes`);
                    return true;
                }
                await this.upsertProductCatalog([{
                    name: found.name,
                    slug: found.slug,
                    product_type: found.product_type || 'item',
                    price_cents: parseInt(found.price_cents, 10) || 0,
                    currency: found.currency || 'usd',
                    stock_tracking: true,
                    stock_qty: qty,
                    shipping_required: !!found.shipping_required
                }]);
                this.addConversationMessage('ai', `✅ Stock for ${found.name} updated to ${qty}.`);
            } catch (e) {
                this.addConversationMessage('ai', 'Updating stock failed. Please try again or specify the product name and quantity clearly.');
            }
            return true;
        }

        // Add product lines: "add product(s): ..." using the same pipe format
        if (t.startsWith('add product') || t.startsWith('add products')) {
            const raw = text.split(':').slice(1).join(':').trim() || text.replace(/^add\s+products?/i, '').trim();
            const products = this.parseProductsList ? this.parseProductsList(raw) : [];
            if (!products.length) {
                this.addConversationMessage('ai', 'Please provide product details in the format: Name | 19.99 | usd | stock 10 | type item | ship yes');
                return true;
            }
            try {
                await this.upsertProductCatalog(products);
                this.addConversationMessage('ai', `✅ ${products.length} product(s) added/updated. I can generate the necessary pages when you're ready.`);
            } catch (e) {
                this.addConversationMessage('ai', 'Saving products failed. Please try again with the provided format.');
            }
            return true;
        }

        return false;
    }

    async findProductByNameOrSlug(q) {
        try {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) || (window.location.origin + '/wp-json/');
            const url = apiRoot + 'vmo-builder/v1/store/products';
            const res = await fetch(url, { method: 'GET' });
            const data = await res.json();
            if (!data || !data.products) return null;
            const needle = q.trim().toLowerCase();
            return data.products.find(p => (p.name||'').toLowerCase() === needle || (p.slug||'').toLowerCase() === needle) || null;
        } catch(e) { return null; }
    }
    
    async callAIAgent(agentType, message) {
        // Build OpenAI-style chat array from conversationHistory + latest user message
        const chat = [];
        if (window.vmoConsultationProfileSystem && String(window.vmoConsultationProfileSystem).trim()) {
            chat.push({ role: 'system', content: String(window.vmoConsultationProfileSystem).slice(0, 6000) });
        }
        // map prior history
        (this.conversationHistory || []).forEach(m => {
            const role = m.sender === 'ai' ? 'assistant' : 'user';
            chat.push({ role, content: m.message || '' });
        });
        // add current user message
        chat.push({ role: 'user', content: message });

        const response = await fetch((window.vmo_ajax?.ajaxurl) || vmoAjax.ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'vmo_conversation_chat',
                security: (window.vmo_ajax?.nonce) || vmoAjax.nonce,
                chat: JSON.stringify(chat)
            })
        });
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.data || 'AI processing failed');
        }
        
    return data.data.response;
    }
    
    async generateWebsiteFromWizard() {
        this.addWizardMessage('ai', 'Excellent! Starting website generation...');
        this.setWizardGenerationLocked(true);
        
        // Show toast for generation progress
        this.showToast('🔄 AI agents are working on your website...', 'info', 0);
        
        try {
            const payload = await this.callBusinessWebsiteGeneration(this.wizardData || {});

            // Hide loading toast
            this.hideToast();

            // Update the page content only when the preview gate allows HTML to be shown.
            const websiteDraft = payload.website_draft || {};
            const previewReady = !!(payload.preview_ready && payload.media_complete !== false);
            const html = previewReady ? (payload.html || payload.content || websiteDraft.homepage_html || websiteDraft.content || '') : '';
            const websiteContent = document.getElementById('vmo-website-content');
            if (html && websiteContent) {
                websiteContent.innerHTML = html;
            }

            this.showToast(
                previewReady
                    ? 'Your website has been generated successfully.'
                    : 'Your website draft is assembled. Required media is still generating before preview release.',
                previewReady ? 'success' : 'info'
            );

            if (previewReady) {
                this.setWizardGenerationLocked(false);
                this.closeWizard();
                this.showPublishOptions();
            } else {
                this.showMediaGenerationLock(payload);
                this.startConsultationMediaQueuePolling(payload);
            }
            
        } catch (error) {
            this.hideToast();
            this.setWizardGenerationLocked(false);
            this.showToast('❌ Generation failed. Please try again.', 'error');
            console.error('Website generation error:', error);
        }
    }

    setWizardGenerationLocked(isLocked) {
        const input = document.getElementById('vmo-wizard-response');
        const sendButton = document.getElementById('vmo-wizard-send');
        if (input) {
            input.disabled = !!isLocked;
            input.placeholder = isLocked ? 'VMO is finishing website media and final QA...' : '';
        }
        if (sendButton) {
            sendButton.disabled = !!isLocked;
        }
        document.querySelectorAll('#vmo-publish-btn, #vmo-update-live-btn, .vmo-publish-options button').forEach((button) => {
            button.disabled = !!isLocked;
            if (isLocked) {
                button.setAttribute('aria-disabled', 'true');
            } else {
                button.removeAttribute('aria-disabled');
            }
        });
    }

    showMediaGenerationLock(payload = {}) {
        const manifest = payload.media_manifest || payload.mediaManifest || payload.website_draft?.media_manifest || payload.qa_report?.media_manifest || {};
        const contract = manifest.strict_media_completion_contract || {};
        const queueCounts = manifest.queue_counts || payload.media_queue?.counts || payload.queue_counts || {};
        const pendingCount = Number(queueCounts.pending || 0) + Number(queueCounts.processing || 0);
        const missingCount = Number(contract.missing_media_count || manifest.queueable_placeholders || 0);
        const unassignedCount = Number(contract.unassigned_uploaded_media_count || manifest.unassigned_uploaded_media_count || 0);
        const qualityIssues = Array.isArray(contract.quality_issues || manifest.quality_issues) ? (contract.quality_issues || manifest.quality_issues) : [];
        const previewReady = !!(payload.preview_ready && payload.media_complete !== false);
        const items = [
            ['Website structure', true],
            ['Uploaded media mapped', unassignedCount === 0],
            ['Generated images and videos inserted', pendingCount === 0 && missingCount === 0],
            ['Product media packets complete', contract.product_media_ready !== false],
            ['Visual quality checks', qualityIssues.length === 0],
            ['Preview release', previewReady]
        ];
        const progressHtml = items.map(([label, complete]) => `<li data-ready="${complete ? 'true' : 'false'}"><strong>${complete ? 'Ready' : 'Locked'}</strong> ${label}</li>`).join('');
        const status = this.escapeHtml(payload.status || 'generating_media');
        const markup = `
            <div class="vmo-media-generation-lock" role="status" aria-live="polite">
                <h3>Website preview is locked while VMO finishes media</h3>
                <p>The consultation is still active. Your website will unlock only after required uploads are mapped, generated media is inserted, product packets are complete, and final QA passes.</p>
                <ul>${progressHtml}</ul>
                <p><strong>Current status:</strong> ${status}</p>
            </div>
        `;

        const existingLock = document.querySelector('#vmo-wizard-conversation .vmo-media-generation-lock');
        if (existingLock) {
            existingLock.outerHTML = markup;
            return;
        }

        this.addWizardMessage('system', markup);
    }

    getGeneratedProjectId(payload = {}) {
        const websiteDraft = payload.website_draft || payload.websiteDraft || {};
        const mediaQueue = payload.media_queue || payload.queue || {};
        return parseInt(
            payload.draft_id ||
            payload.post_id ||
            payload.project_id ||
            websiteDraft.post_id ||
            websiteDraft.draft_post_id ||
            mediaQueue.post_id ||
            0,
            10
        ) || 0;
    }

    startConsultationMediaQueuePolling(payload = {}) {
        const projectId = this.getGeneratedProjectId(payload);
        if (!projectId) {
            return false;
        }

        const generator = window.VMOMediaGenerator || window.vmoMediaGenerator;
        const handleUpdate = (queue) => {
            if (queue) {
                this.showMediaGenerationLock(this.normalizeQueueReadinessPayload(queue, payload));
            }
        };
        const handleComplete = async (queue) => {
            let readiness = queue || null;
            try {
                readiness = await this.fetchProjectMediaReadiness(projectId);
            } catch (error) {
                console.warn('VMO media readiness re-check failed:', error);
            }
            this.handleConsultationMediaReadiness(readiness || queue || {}, payload);
        };

        if (generator && typeof generator.startProjectQueuePolling === 'function') {
            generator.startProjectQueuePolling(projectId, {
                waitForCompletion: true,
                source: 'consultation_generation',
                onUpdate: handleUpdate,
                onComplete: handleComplete
            });
            return true;
        }

        this.pollConsultationMediaReadiness(projectId, payload);
        return true;
    }

    async fetchProjectMediaReadiness(projectId) {
        const response = await fetch(this.getAjaxUrl(), {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'vmo_get_project_media_queue',
                security: this.getNonce(),
                project_id: String(projectId)
            })
        });
        const result = await response.json();
        if (!result.success) {
            throw new Error((result.data && (result.data.message || result.data)) || 'Media readiness check failed');
        }
        return result.data || {};
    }

    async pollConsultationMediaReadiness(projectId, originalPayload = {}) {
        window.clearTimeout(this.consultationMediaPollTimer);
        try {
            const readiness = await this.fetchProjectMediaReadiness(projectId);
            this.showMediaGenerationLock(this.normalizeQueueReadinessPayload(readiness, originalPayload));
            const terminal = ['complete', 'failed', 'partial'].includes(String(readiness.status || '').toLowerCase());
            const previewReady = !!(readiness.preview_ready && readiness.media_complete !== false);
            if (terminal || previewReady) {
                this.handleConsultationMediaReadiness(readiness, originalPayload);
                return;
            }
        } catch (error) {
            console.warn('VMO media readiness poll failed:', error);
        }

        this.consultationMediaPollTimer = window.setTimeout(() => {
            this.pollConsultationMediaReadiness(projectId, originalPayload);
        }, 5000);
    }

    normalizeQueueReadinessPayload(queue = {}, originalPayload = {}) {
        return {
            ...originalPayload,
            ...queue,
            website_draft: {
                ...(originalPayload.website_draft || {}),
                post_id: queue.post_id || originalPayload.website_draft?.post_id || originalPayload.post_id || originalPayload.draft_id || 0,
                homepage_html: queue.homepage_html || originalPayload.website_draft?.homepage_html || '',
                content: queue.content || originalPayload.website_draft?.content || '',
                preview_url: queue.preview_ready ? (queue.preview_url || originalPayload.preview_url || '') : '',
                preview_ready: !!queue.preview_ready,
                media_complete: !!queue.media_complete,
                publish_ready: !!queue.publish_ready
            },
            media_queue: queue,
            media_manifest: queue.media_manifest || originalPayload.media_manifest || originalPayload.website_draft?.media_manifest || {},
            qa_report: queue.qa_report || originalPayload.qa_report || {},
            preview_url: queue.preview_ready ? (queue.preview_url || originalPayload.preview_url || '') : '',
            preview_ready: !!queue.preview_ready,
            media_complete: !!queue.media_complete,
            publish_ready: !!queue.publish_ready,
            status: queue.status || originalPayload.status || 'generating_media'
        };
    }

    handleConsultationMediaReadiness(readiness = {}, originalPayload = {}) {
        const payload = this.normalizeQueueReadinessPayload(readiness, originalPayload);
        const previewReady = !!(payload.preview_ready && payload.media_complete !== false);

        if (previewReady) {
            window.clearTimeout(this.consultationMediaPollTimer);
            const html = payload.homepage_html || payload.content || payload.website_draft?.homepage_html || payload.website_draft?.content || '';
            const websiteContent = document.getElementById('vmo-website-content');
            if (html && websiteContent) {
                websiteContent.innerHTML = html;
            }
            this.showMediaGenerationLock(payload);
            this.addWizardMessage('ai', 'All required website media has been generated, inserted, and cleared. Your preview is ready now.');
            this.setWizardGenerationLocked(false);
            this.closeWizard();
            this.showToast('Your website preview is ready for review.', 'success');
            this.showPublishOptions();
            return;
        }

        this.showMediaGenerationLock(payload);
        const status = String(payload.status || '').toLowerCase();
        if (status === 'failed' || status === 'partial') {
            this.showToast('Some required media still needs attention before preview can unlock.', 'warning');
        }
    }
    
    startVoiceInput() {
        if (!this.recognition) {
            this.showToast('Voice input not supported in your browser', 'warning');
            return;
        }
        
        const button = document.getElementById('vmo-voice-input');
        button.textContent = '🔴';
        button.disabled = true;
        
        this.recognition.start();
        
        this.recognition.onend = () => {
            button.textContent = '🎙️';
            button.disabled = false;
        };
    }
    
    // VOICE SYSTEM REMOVED: Voice conversation disabled for No Voice version
    startWizardVoice() {
        // No-op function - voice conversation completely disabled
        console.log('🔇 Voice conversation disabled - text-only mode');
        this.showToast('Voice input is disabled in this version. Please use text input.', 'info');
        return;
    }
    
    // VOICE SYSTEM REMOVED: Legacy voice conversation disabled for No Voice version
    startLegacyWizardVoice() {
        // No-op function - voice conversation completely disabled
        console.log('🔇 Voice conversation disabled - text-only mode');
        return;
    }
    
    // VOICE SYSTEM REMOVED: Voice transcription disabled for No Voice version
    startWizardTranscribe() {
        // No-op function - voice transcription completely disabled
        console.log('🔇 Voice transcription disabled - text-only mode');
        this.showToast('Voice input is disabled in this version. Please use text input.', 'info');
        return;
    }
    
    // VOICE SYSTEM REMOVED: Legacy voice transcription disabled for No Voice version
    startLegacyWizardTranscribe() {
        // No-op function - voice transcription completely disabled
        console.log('🔇 Voice transcription disabled - text-only mode');
        return;
    }
    
    // Add voice transcript to the business consultation chat history
    addVoiceTranscriptToWizard(message, isFromUser = true) {
        console.log('VMO Business Wizard: Adding voice transcript:', { message, isFromUser });
        
        // Use existing addWizardMessage method to add transcript
        if (isFromUser) {
            // Add user's voice input as transcript
            this.addWizardMessage(`🎤 [Voice Input]: ${message}`, false);
        } else {
            // Add AI's TTS response as transcript
            this.addWizardMessage(`🔊 [AI Voice Response]: ${message}`, true);
        }
    }
    
    updateInputField(text) {
        // Helper to update input field (for interim results)
        // Don't update if AI is currently responding (prevents overwriting during auto-submit)
        if (this.aiResponding) {
            console.log('⚠️ Skipping input update - AI is responding');
            return;
        }
        
        const wizardVisible = document.getElementById('vmo-business-wizard-modal')?.style.display !== 'none';
        if (wizardVisible) {
            const input = document.getElementById('vmo-wizard-response');
            if (input) input.value = text;
        } else {
            const input = document.getElementById('vmo-user-message');
            if (input) input.value = text;
        }
    }

    handleVoiceInput(transcript, isFinal = false) {
        // Update the input field with the transcript
        this.updateInputField(transcript);
        
        console.log('🎤 Voice input:', { transcript, isFinal, mode: this.voiceSessionActive ? 'conversation' : 'transcribe' });
        
        // In CONVERSATION MODE: Auto-submit after silence detection
        if (isFinal && this.voiceSessionActive) {
            console.log('🎤 Starting silence detection (6 seconds)...');
            clearTimeout(this.silenceTimer);
            this.silenceTimer = setTimeout(() => {
                console.log('✅ Silence detected - auto-submitting in conversation mode');
                this.submitCurrentMessage();
            }, this.silenceThreshold);
        }
        
        // In TRANSCRIBE MODE: Just populate field, user submits manually
        // (transcribeSessionActive = true, voiceSessionActive = false)
    }
    
    submitCurrentMessage() {
        // Submit the current message from the appropriate input field
        const wizardVisible = document.getElementById('vmo-business-wizard-modal')?.style.display !== 'none';
        
        if (wizardVisible) {
            const input = document.getElementById('vmo-wizard-response');
            const message = input?.value?.trim();
            if (message) {
                console.log('📤 Auto-submitting wizard message:', message);
                // Reset last processed to allow new input after this submission
                this.lastProcessedTranscript = '';
                // Trigger the wizard's send logic
                this.sendWizardResponse(); // ✅ FIXED: Correct function name
            }
        } else {
            const input = document.getElementById('vmo-user-message');
            const message = input?.value?.trim();
            if (message) {
                console.log('📤 Auto-submitting chat message:', message);
                // Reset last processed to allow new input after this submission
                this.lastProcessedTranscript = '';
                // Trigger the chat's send logic
                this.sendMessage();
            }
        }
    }
    
    // VOICE SYSTEM REMOVED: Speech synthesis disabled for No Voice version
    speak(text) {
        // No-op function - voice playback completely disabled
        return;
    }
    
    addConversationMessage(sender, message, isLoading = false) {
        const messagesContainer = document.getElementById('vmo-conversation-messages');
        const shouldAutoScroll = this.isContainerNearBottom(messagesContainer);
        const messageDiv = document.createElement('div');
        messageDiv.className = `vmo-message vmo-message-${sender}${isLoading ? ' vmo-message-loading' : ''}`;
        messageDiv.innerHTML = `
            <div class="vmo-message-content">
                ${isLoading ? '<div class="vmo-loading-dots"><span></span><span></span><span></span></div>' : message}
            </div>
        `;
        
        messagesContainer.appendChild(messageDiv);
        if (shouldAutoScroll) {
            this.scrollContainerToBottom(messagesContainer);
        }
        
        if (!isLoading) {
            this.conversationHistory.push({ sender, message });
        }
    }
    
    removeLoadingMessage() {
        const loadingMessage = document.querySelector('.vmo-message-loading');
        if (loadingMessage) {
            loadingMessage.remove();
        }
    }
    
    showSuggestions(suggestions) {
        const suggestionsContainer = document.getElementById('vmo-conversation-suggestions');
        suggestionsContainer.innerHTML = suggestions.map(suggestion => 
            `<button class="vmo-suggestion-btn" onclick="vmoAI.selectSuggestion('${suggestion}')">${suggestion}</button>`
        ).join('');
    }
    
    selectSuggestion(suggestion) {
        document.getElementById('vmo-user-message').value = suggestion;
        this.sendMessage();
    }
    
    generateSuggestions(userMessage, aiResponse) {
        // Generate contextual suggestions based on the conversation
        const suggestions = [];
        
        if (userMessage.toLowerCase().includes('business')) {
            suggestions.push('Add a contact form', 'Include customer testimonials', 'Show our services');
        } else if (userMessage.toLowerCase().includes('ecommerce') || userMessage.toLowerCase().includes('store')) {
            suggestions.push('Add product gallery', 'Include shopping cart', 'Add payment options');
        } else if (userMessage.toLowerCase().includes('portfolio')) {
            suggestions.push('Add image gallery', 'Include project descriptions', 'Add contact info');
        } else {
            suggestions.push('Make it more professional', 'Add more sections', 'Change the colors');
        }
        
        this.showSuggestions(suggestions);
    }
    
    showModal(modalId) {
        document.getElementById(modalId).style.display = 'flex';
    }
    
    closeConversation() {
        document.getElementById('vmo-ai-conversation-modal').style.display = 'none';
        this.conversationHistory = [];
    }
    
    closeWizard() {
        document.getElementById('vmo-business-wizard-modal').style.display = 'none';
    }
    
    openManualDesign() {
        this.showModal('vmo-manual-design-modal');
    }
    
    closeManualDesign() {
        document.getElementById('vmo-manual-design-modal').style.display = 'none';
    }
    
    showPublishOptions() {
        // Show publish options after website generation
        const publishHtml = `
            <div class="vmo-publish-options">
                <h3>🚀 Ready to Publish?</h3>
                <p>Your website is ready! Choose how you'd like to publish it:</p>
                <div class="vmo-publish-buttons">
                    <button class="vmo-btn vmo-btn-primary" onclick="vmoAI.publishWebsite()">
                        📤 Publish Website
                    </button>
                    <button class="vmo-btn vmo-btn-secondary" onclick="vmoAI.previewWebsite()">
                        👁️ Preview First
                    </button>
                </div>
            </div>
        `;
        
        // Add to the interface
        const container = document.querySelector('.vmo-builder-container');
        const publishDiv = document.createElement('div');
        publishDiv.innerHTML = publishHtml;
        container.appendChild(publishDiv);
    }
    
    async publishWebsite() {
        // Handle website publishing
        this.showToast('🚀 Publishing your website...', 'info', 0);
        
        try {
        const content = document.getElementById('vmo-website-content')?.innerHTML || '';
        const title = (this.wizardData && this.wizardData.business_name) ? `${this.wizardData.business_name} Website` : `VMO Website ${new Date().toLocaleString()}`;
        const response = await fetch((window.vmo_ajax?.ajaxurl) || vmoAjax.ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
            action: 'vmo_save_generated_page',
            security: (window.vmo_ajax?.nonce) || vmoAjax.nonce,
            title: title,
            content: content,
            type: 'page',
            status: 'draft'
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.hideToast();
                const id = data.data && data.data.id;
                this.showToast(id ? `✅ Saved draft page (ID ${id}). You can publish from Pages.` : '✅ Page saved.', 'success');
            } else {
                throw new Error(data.data || 'Publishing failed');
            }
            
        } catch (error) {
            this.hideToast();
            this.showToast('❌ Publishing failed. Please try again.', 'error');
            console.error('Publishing error:', error);
        }
    }
    
    previewWebsite() {
        // Open preview in new window
        const content = document.getElementById('vmo-website-content').innerHTML;
        const previewWindow = window.open('', '_blank');
        previewWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <title>Website Preview</title>
                <style>
                    body { margin: 0; padding: 0; font-family: system-ui, -apple-system, sans-serif; }
                </style>
            </head>
            <body>
                ${content}
            </body>
            </html>
        `);
        previewWindow.document.close();
    }
    
    showToast(message, type = 'info', duration = 5000) {
        // Use existing toast system
        if (window.vmoShowToast) {
            window.vmoShowToast(message, type);
        } else {
            // Only log toasts in debug mode to reduce console noise
            if (window.vmoDebug) {
                console.log(`Toast: ${message}`);
            }
        }
    }
    
    hideToast() {
        if (window.vmoHideToast) {
            window.vmoHideToast();
        }
    }

    // Render template preview iframe (fallback for legacy code)
    renderTemplatePreview(template, results) {
        if (template && template.ready) {
            const templateUrl = template.file.startsWith('http') 
                ? template.file 
                : `${window.location.origin}${window.location.pathname.replace(/[^/]*$/, '')}${template.file}`;
            
            return `
                <iframe src="${templateUrl}" 
                        style="width: 100%; height: 300px; border: 1px solid #ddd; border-radius: 8px;"
                        title="${template.name} Template Preview">
                </iframe>
                <div class="vmo-template-info">
                    <h4>🎯 ${template.name} Template Selected</h4>
                    <p>${template.description}</p>
                    <div class="vmo-template-features">
                        ${template.features.map(feature => `<span class="vmo-feature-badge">${feature}</span>`).join('')}
                    </div>
                </div>
            `;
        } else {
            // Fallback to generated content
            return `
                <iframe src="data:text/html,${encodeURIComponent(results.website?.main_page || '<h1>Your Professional Website</h1><p>Complete business website ready to launch!</p>')}" 
                        style="width: 100%; height: 250px; border: 1px solid #ddd; border-radius: 8px;">
                </iframe>
                <div class="vmo-template-info">
                    <p>🤖 AI-generated business website based on your consultation</p>
                </div>
            `;
        }
    }
    
    // Use selected business template
    useBusinessTemplate(templateId) {
        console.log('🚀 Using business template:', templateId);
        
        if (typeof VMOTemplates !== 'undefined') {
            VMOTemplates.useTemplate(templateId);
        } else {
            this.showToast('Template system not available', 'error');
        }
    }
    
    // BROWSER PREVIEW FUNCTIONALITY - FIX FOR DAMAGED PREVIEW BUTTON
    openBrowserPreview() {
        console.log('🌐 Opening browser preview...');
        
        let contentToPreview = '';

        // 1. Check comprehensive results (Wizard)
        if (this.comprehensiveBusinessResults && this.comprehensiveBusinessResults.website && this.comprehensiveBusinessResults.website.main_page) {
            console.log('Using comprehensiveBusinessResults');
            contentToPreview = this.comprehensiveBusinessResults.website.main_page;
        } 
        // 2. Check standard results
        else if (this.businessResults && this.businessResults.website && this.businessResults.website.main_page) {
            console.log('Using businessResults');
            contentToPreview = this.businessResults.website.main_page;
        }
        // 3. Check global last content
        else if (window.lastContent) {
            console.log('Using window.lastContent');
            contentToPreview = window.lastContent;
        }
        // 4. Check iframe content
        else {
            const iframe = document.getElementById('vmo-preview-iframe');
            if (iframe && iframe.contentDocument) {
                try {
                    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                    // Only use if it's not empty or about:blank
                    if (iframeDoc.body.innerHTML.length > 50) {
                        console.log('Using iframe content');
                        contentToPreview = iframeDoc.documentElement.outerHTML;
                    }
                } catch (error) {
                    console.error('Error accessing iframe content:', error);
                }
            }
        }

        if (contentToPreview && contentToPreview.length > 50) {
            this.showPreviewInNewWindow(contentToPreview);
        } else {
            console.warn('No website content found to preview');
            if (window.showToast) {
                window.showToast('No website content generated yet to preview.', 'warning');
            } else {
                alert('No website content generated yet to preview.');
            }
        }
    }
    
    showPreviewInNewWindow(content) {
        try {
            if (typeof window.vmoStripEditorOnlyMediaOverlays === 'function') {
                content = window.vmoStripEditorOnlyMediaOverlays(content);
            } else {
                content = String(content || '').replace(/<button\b[^>]*(?:data-replace-media|data-vmo-editor-only=["']media-replace-overlay["']|class=["'][^"']*(?:vmo-replace-overlay|vmo-replace-btn|vmo-replace-media-btn|replace-image-btn|replace-video-btn)[^"']*["'])[^>]*>[\s\S]*?<\/button>/gi, '');
            }
            const previewWindow = window.open('', '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes');
            
            if (!previewWindow) {
                if (window.showToast) {
                    window.showToast('Popup blocked! Please allow popups for this site to use browser preview.', 'error');
                }
                return;
            }
            
            // Check if content is a full HTML document
            const isFullHtml = content.trim().toLowerCase().startsWith('<!doctype') || content.trim().toLowerCase().startsWith('<html');
            
            if (isFullHtml) {
                // Write full HTML directly
                previewWindow.document.write(content);
            } else {
                // Wrap partial content
                previewWindow.document.write(`
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width, initial-scale=1.0">
                        <title>VMO AI Builder - Browser Preview</title>
                        <style>
                            body { 
                                font-family: Arial, sans-serif; 
                                margin: 0; 
                                padding: 0; 
                                line-height: 1.6; 
                            }
                            .vmo-preview-header {
                                background: #333;
                                color: white;
                                padding: 10px 20px;
                                font-size: 14px;
                            }
                            .vmo-preview-content {
                                padding: 20px;
                            }
                        </style>
                    </head>
                    <body>
                        <div class="vmo-preview-header">
                            🌐 VMO AI Builder - Browser Preview | Generated: ${new Date().toLocaleString()}
                        </div>
                        <div class="vmo-preview-content">
                            ${content}
                        </div>
                    </body>
                    </html>
                `);
            }
            
            previewWindow.document.close();
            previewWindow.focus();
            
            if (window.showToast) {
                window.showToast('✅ Content opened in browser preview window!', 'success');
            }
            
        } catch (error) {
            console.error('Error opening preview window:', error);
            if (window.showToast) {
                window.showToast('Failed to open preview window: ' + error.message, 'error');
            }
        }
    }
}

// Initialize the conversational AI when the page loads
document.addEventListener('DOMContentLoaded', () => {
    console.log('🎯 Initializing VMO Conversational AI (UNIFIED)');
    window.vmoAI = new VMOConversationalAI();
    window.vmoBusinessWizard = window.vmoAI; // Alias for voice system integration
    console.log('✅ VMO Conversational AI Ready (UNIFIED)', window.vmoAI);
});

// Add CSS for the conversational interface
const conversationalStyles = `
<style>
.vmo-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}

.vmo-modal-content {
    background: #1a1a1a;
    border-radius: 12px;
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    border: 1px solid #333;
}

.vmo-conversation-interface {
    height: 600px;
}

.vmo-conversation-header {
    display: flex;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #333;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px 12px 0 0;
    color: white;
}

.vmo-ai-avatar img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 15px;
}

.vmo-conversation-title {
    flex-grow: 1;
}

.vmo-conversation-title h3 {
    margin: 0;
    font-size: 1.2rem;
}

.vmo-conversation-title p {
    margin: 5px 0 0 0;
    opacity: 0.8;
    font-size: 0.9rem;
}

.vmo-conversation-messages {
    flex-grow: 1;
    padding: 20px;
    overflow-y: auto;
    background: #0f0f0f;
}

.vmo-message {
    margin-bottom: 15px;
    display: flex;
}

.vmo-message-ai {
    justify-content: flex-start;
}

.vmo-message-user {
    justify-content: flex-end;
}

.vmo-message-content {
    max-width: 70%;
    padding: 12px 16px;
    border-radius: 18px;
    font-size: 0.95rem;
    line-height: 1.4;
}

.vmo-message-ai .vmo-message-content {
    background: #333;
    color: #fff;
    border-bottom-left-radius: 6px;
}

.vmo-message-user .vmo-message-content {
    background: #667eea;
    color: white;
    border-bottom-right-radius: 6px;
}

.vmo-loading-dots {
    display: flex;
    gap: 4px;
}

.vmo-loading-dots span {
    width: 6px;
    height: 6px;
    background: #ccc;
    border-radius: 50%;
    animation: vmo-loading-bounce 1.4s infinite ease-in-out both;
}

.vmo-loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.vmo-loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes vmo-loading-bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
}

.vmo-conversation-input {
    padding: 20px;
    border-top: 1px solid #333;
    background: #1a1a1a;
    border-radius: 0 0 12px 12px;
}

.vmo-input-container {
    display: flex;
    gap: 10px;
    align-items: flex-end;
}

.vmo-input-container textarea {
    flex-grow: 1;
    background: #333;
    border: 1px solid #555;
    border-radius: 8px;
    padding: 12px;
    color: white;
    resize: none;
    font-family: inherit;
    font-size: 0.95rem;
}

.vmo-input-container textarea:focus {
    outline: none;
    border-color: #667eea;
}

.vmo-input-actions {
    display: flex;
    gap: 8px;
}

.vmo-btn-voice-input, .vmo-btn-send {
    padding: 12px 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
}

.vmo-btn-voice-input {
    background: #ff6b6b;
    color: white;
}

.vmo-btn-send {
    background: #667eea;
    color: white;
}

.vmo-btn-voice-input:hover {
    background: #ff5252;
}

.vmo-btn-send:hover {
    background: #5a6fd8;
}

.vmo-conversation-suggestions {
    display: flex;
    gap: 8px;
    margin-top: 12px;
    flex-wrap: wrap;
}

.vmo-suggestion-btn {
    background: #333;
    color: #ccc;
    border: 1px solid #555;
    border-radius: 20px;
    padding: 6px 12px;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.vmo-suggestion-btn:hover {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

.vmo-wizard-interface, .vmo-design-tools {
    height: 500px;
}

.vmo-wizard-header, .vmo-design-header {
    padding: 20px;
    border-bottom: 1px solid #333;
    background: #667eea;
    color: white;
    border-radius: 12px 12px 0 0;
}

.vmo-wizard-conversation {
    flex-grow: 1;
    padding: 20px;
    overflow-y: auto;
    background: #0f0f0f;
}

.vmo-wizard-input {
    padding: 20px;
    border-top: 1px solid #333;
    background: #1a1a1a;
}

.vmo-wizard-input textarea {
    width: 100%;
    background: #333;
    border: 1px solid #555;
    border-radius: 8px;
    padding: 12px;
    color: white;
    resize: none;
    font-family: inherit;
    margin-bottom: 12px;
}

.vmo-wizard-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.vmo-design-toolkit {
    padding: 20px;
    overflow-y: auto;
}

.vmo-tool-category {
    margin-bottom: 25px;
}

.vmo-tool-category h4 {
    color: #667eea;
    margin-bottom: 12px;
    font-size: 1.1rem;
}

.vmo-tool-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 10px;
}

.vmo-design-tool {
    background: #333;
    color: white;
    border: 1px solid #555;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.9rem;
}

.vmo-design-tool:hover {
    background: #667eea;
    border-color: #667eea;
}

.vmo-btn-close {
    background: transparent;
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    width: 32px;
    height: 32px;
    cursor: pointer;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
}

.vmo-btn-close:hover {
    background: rgba(255,255,255,0.1);
}

.vmo-publish-options {
    background: #1a1a1a;
    border: 1px solid #333;
    border-radius: 12px;
    padding: 25px;
    margin: 20px;
    text-align: center;
}

.vmo-publish-options h3 {
    color: #667eea;
    margin-bottom: 10px;
}

.vmo-publish-options p {
    color: #ccc;
    margin-bottom: 20px;
}

.vmo-publish-buttons {
    display: flex;
    gap: 15px;
    justify-content: center;
    flex-wrap: wrap;
}

@media (max-width: 768px) {
    .vmo-modal-content {
        width: 95%;
        height: 90vh;
    }
    
    .vmo-conversation-interface, .vmo-wizard-interface, .vmo-design-tools {
        height: 100%;
    }
    
    .vmo-input-container {
        flex-direction: column;
        gap: 12px;
    }
    
    .vmo-input-actions {
        justify-content: center;
    }
    
    .vmo-template-info {
        margin-top: 10px;
        padding: 15px;
        background: rgba(0, 123, 255, 0.1);
        border-radius: 8px;
        border-left: 3px solid #007bff;
    }
    
    .vmo-template-info h4 {
        color: #007bff;
        margin: 0 0 8px 0;
        font-size: 1rem;
    }
    
    .vmo-template-info p {
        color: #ccc;
        margin: 0 0 10px 0;
        font-size: 0.9rem;
    }
    
    .vmo-template-features {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
    }
    
    .vmo-feature-badge {
        background: rgba(0, 123, 255, 0.2);
        color: #007bff;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .vmo-btn-accent {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }
    
    .vmo-btn-accent:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
}
</style>
`;

// Inject the styles
document.head.insertAdjacentHTML('beforeend', conversationalStyles);
