 /**
 * VMO Business Dashboard System
 * Premium features for business consulting AI
 * Includes: Dashboard, Phone System, SEO Management, Lead Generation, Campaign Management, Legal Documents
 */

window.VMOBusinessDashboard = (function() {
    'use strict';
    
    let currentUser = null;
    let businessData = null;
    let dashboardContainer = null;
    
    // Initialize the business dashboard
    function init(userData, businessInfo) {
        console.log('🏢 VMO Business Dashboard - Initializing...');
        currentUser = userData;
        businessData = businessInfo;
        
        // Check if user has premium access
        if (!isPremiumUser()) {
            // ✅ FORCE REDIRECT: Send free users to "My Plan" page inside plugin
            console.log('🔒 User is not premium - Redirecting to My Plan');
            
            // Construct admin URL for the plans page
            let plansUrl = 'admin.php?page=vmo-my-plan';
            if (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl) {
                plansUrl = vmo_ajax.ajaxurl.replace('admin-ajax.php', 'admin.php?page=vmo-my-plan');
            }

            // Notify user
            const msg = 'Subscription Required. Redirecting to Plan Selection...';
            if (typeof showToast === 'function') {
                showToast(msg, 'warning');
            } else {
                // Fallback visual notice
                const notice = document.createElement('div');
                notice.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#333;color:white;padding:20px 40px;border-radius:8px;z-index:99999;font-size:18px;text-align:center;box-shadow:0 10px 30px rgba(0,0,0,0.3);';
                notice.innerHTML = '<strong>Account Activation Required</strong><br><br>Redirecting to Plans...';
                document.body.appendChild(notice);
            }

            // Redirect after brief delay
            setTimeout(() => {
                window.location.href = plansUrl;
            }, 2000);
            
            return;
        }
        
        createDashboard();
        setupNavigationHandlers();
        loadDashboardModules();
        
        // Post-Load Actions
        checkPostPurchaseContext();
        updateBalanceDisplay();
    }

    // Handle Post-Purchase Toast & URL cleanup
    function checkPostPurchaseContext() {
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('payment') === 'success') {
            const plan = urlParams.get('plan');
            let msg = 'Purchase Successful! Your dashboard has been updated.';
            
            // Customize message based on plan
            if (plan && plan.includes('phone') || plan === 'power_dialer') {
                 msg = '⚡ Power Pack Activated! Credits added to your balance.';
            } else if (plan) {
                 msg = `Subscription to ${plan.toUpperCase()} Plan Active!`;
            }

            // Show Toast
            if (typeof showToast === 'function') {
                showToast(msg, 'success');
            } else {
                 // Fallback Toast
                 const toast = document.createElement('div');
                 toast.innerHTML = `✅ <strong>Success!</strong><br>${msg}`;
                 toast.style.cssText = 'position:fixed; bottom:20px; right:20px; background:#10b981; color:white; padding:15px 25px; border-radius:8px; z-index:10000; box-shadow:0 10px 25px rgba(0,0,0,0.2); animation: slideIn 0.5s ease-out;';
                 document.body.appendChild(toast);
                 setTimeout(() => { toast.remove(); }, 5000);
            }

            // Clean URL (remove query params)
            const newUrl = window.location.pathname + window.location.hash;
            window.history.replaceState({}, document.title, newUrl);
        }
    }

    // Update Balance UI across the dashboard
    function updateBalanceDisplay() {
        // Get balance from user object (support multiple common keys)
        const balance = parseInt(currentUser?.token_balance || currentUser?.tokens || currentUser?.vmo_token_balance || 0);
        
        // CONVERT TO DOLLAR EQUIVALENT (Rate: 2500 tokens ~ $3.00 => 0.0012)
        const dollarValue = (balance * 0.0012);

        // Format number as Currency
        const formatBalance = (value) => {
            if (value > 9999) return '$' + (value / 1000).toFixed(1) + 'k';
            return '$' + value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
        };

        const formatted = formatBalance(dollarValue);

        // 1. Update Power Dialer Header (Voice Balance)
        const voiceBalanceEl = document.getElementById('vmo-voice-balance');
        if (voiceBalanceEl) {
            voiceBalanceEl.textContent = formatted;
            // Add color based on balance
            voiceBalanceEl.style.color = balance < 1000 ? '#ef4444' : '#10b981'; 
        }

        // 2. Update Main Overview Badge (if exists)
        const overviewBadge = document.getElementById('vmo-overview-balance-badge');
        if (overviewBadge) {
             overviewBadge.textContent = formatted; // "Credits" removed
        }
    }
    
    // Check if user has premium access
    function isPremiumUser() {
        // CLIENT VERSION: Only paid plans may access the full dashboard
        const plan = (currentUser?.plan || '').toLowerCase().trim();
        const allowedPlans = ['tester', 'starter', 'pro', 'elite', 'enterprise', 'premium', 'business'];
        return allowedPlans.includes(plan) && plan !== 'free';
    }
    
    // Create main dashboard container
    function createDashboard() {
        // PREVENT-OVERWRITE: Do not create the JS dashboard if the PHP Strategic Dashboard is present
        if (document.querySelector('.vmo-hud')) {
            console.log('✅ PHP Strategic Dashboard detected - Skipping JS Dashboard injection');
            dashboardContainer = document.querySelector('.vmo-hud'); // Bind logic to existing dashboard
            addDashboardStyles(); // Still ensure base styles are loaded
            return;
        }

        const dashboardHTML = `
            <div id="vmo-business-dashboard" class="vmo-dashboard-container">
            <!-- JS Dashboard Generated Here -->
                <div class="vmo-dashboard-sidebar">
                    <div class="vmo-dashboard-logo">
                        <h2>🏢 VMO Business Suite</h2>
                        <p>${businessData?.businessName || 'Your Business'}</p>
                    </div>
                    
                    <nav class="vmo-dashboard-nav">
                        <a href="#overview" class="vmo-nav-item active" data-section="overview">
                            <i class="📊"></i> Overview
                        </a>
                        <a href="#consulting" class="vmo-nav-item" data-section="consulting">
                            <i class="🎯"></i> Business Consulting
                        </a>
                        <a href="#seo" class="vmo-nav-item" data-section="seo">
                            <i class="🔍"></i> SEO Management
                        </a>
                        <a href="#leads" class="vmo-nav-item" data-section="leads">
                            <i class="🎯"></i> Lead Generation
                        </a>
                        <a href="#campaigns" class="vmo-nav-item" data-section="campaigns">
                            <i class="📧"></i> Campaigns
                        </a>
                        <a href="#phone" class="vmo-nav-item" data-section="phone">
                            <i class="📞"></i> Phone System
                        </a>
                        <a href="#legal" class="vmo-nav-item" data-section="legal">
                            <i class="📄"></i> Legal Documents
                        </a>
                        <a href="#business-plan" class="vmo-nav-item" data-section="business-plan">
                            <i class="📈"></i> Business Plan
                        </a>
                        <a href="#tasks" class="vmo-nav-item" data-section="tasks">
                            <i class="✅"></i> Task Manager
                        </a>
                        <a href="#affiliates" class="vmo-nav-item" data-section="affiliates">
                            <i class="🤝"></i> Affiliate Program
                        </a>
                        <a href="#payments-tax" class="vmo-nav-item" data-section="payments-tax">
                            <i class="💰"></i> Payments & Tax
                        </a>
                    </nav>
                </div>
                
                <div class="vmo-dashboard-content">
                    <div id="vmo-section-overview" class="vmo-dashboard-section active">
                        ${createOverviewSection()}
                    </div>
                    <div id="vmo-section-consulting" class="vmo-dashboard-section">
                        ${createConsultingSection()}
                    </div>
                    <div id="vmo-section-seo" class="vmo-dashboard-section">
                        ${createSEOSection()}
                    </div>
                    <div id="vmo-section-leads" class="vmo-dashboard-section">
                        ${createLeadsSection()}
                    </div>
                    <div id="vmo-section-campaigns" class="vmo-dashboard-section">
                        ${createCampaignsSection()}
                    </div>
                    <div id="vmo-section-phone" class="vmo-dashboard-section">
                        ${createPhoneSection()}
                    </div>
                    <div id="vmo-section-legal" class="vmo-dashboard-section">
                        ${createLegalSection()}
                    </div>
                    <div id="vmo-section-business-plan" class="vmo-dashboard-section">
                        ${createBusinessPlanSection()}
                    </div>
                    <div id="vmo-section-tasks" class="vmo-dashboard-section">
                        ${createTasksSection()}
                    </div>
                    <div id="vmo-section-affiliates" class="vmo-dashboard-section">
                         <div class="vmo-loading-state">
                            <span class="vmo-spinner"></span> Loading Affiliate Data...
                        </div>
                    </div>
                    <div id="vmo-section-payments-tax" class="vmo-dashboard-section">
                        ${createPaymentsTaxSection()}
                    </div>
                        ${createTasksSection()}
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing dashboard if it exists
        const existingDashboard = document.getElementById('vmo-business-dashboard');
        if (existingDashboard) {
            existingDashboard.remove();
        }
        
        // Add dashboard to page
        document.body.insertAdjacentHTML('beforeend', dashboardHTML);
        dashboardContainer = document.getElementById('vmo-business-dashboard');
        // Add dashboard styles
        addDashboardStyles();
        // Voice logic intentionally excluded here. Voice is handled in the main UI and Business Consultation wizard.
    }
    
    // Create overview section
    function createOverviewSection() {
        return `
            <div class="vmo-dashboard-header">
                <div style="display:flex; justify-content:space-between; align-items:center; width:100%; flex-wrap:wrap; gap:10px;">
                    <div>
                        <h1>Business Dashboard Overview</h1>
                        <p>Comprehensive business management and growth tools</p>
                    </div>
                    <div>
                        <div class="vmo-help-menu-wrapper" style="position:relative;">
                             <button class="vmo-help-trigger" onclick="VMOBusinessDashboard.toggleHelpMenu(event)" style="display:flex;align-items:center;gap:8px;padding:8px 16px;background:rgba(16, 185, 129, 0.1);color:#10b981;border:1px solid rgba(16, 185, 129, 0.2);border-radius:9999px;cursor:pointer;font-size:13px;font-weight:500;transition:all 0.2s ease;backdrop-filter:blur(10px);">
                                <span>🛡️</span> Help & Feedback
                            </button>
                            <div id="vmo-help-dropdown" style="display:none;position:absolute;right:0;top:120%;width:220px;background:#0f172a;border:1px solid rgba(255,255,255,0.1);border-radius:12px;box-shadow:0 20px 25px -5px rgba(0,0,0,0.3);z-index:9999;overflow:hidden;padding:4px;">
                                <a href="#" onclick="VMOBusinessDashboard.handleHelpAction('ticket', event)" style="display:flex;align-items:center;gap:10px;padding:10px 12px;color:#e2e8f0;text-decoration:none;border-radius:8px;transition:background 0.2s;font-size:13px;"><span>🎫</span> Support Ticket</a>
                                <a href="#" onclick="VMOBusinessDashboard.handleHelpAction('suggestion', event)" style="display:flex;align-items:center;gap:10px;padding:10px 12px;color:#e2e8f0;text-decoration:none;border-radius:8px;transition:background 0.2s;font-size:13px;"><span>💡</span> Submit Suggestion</a>
                                <a href="#" onclick="VMOBusinessDashboard.handleHelpAction('faq', event)" style="display:flex;align-items:center;gap:10px;padding:10px 12px;color:#e2e8f0;text-decoration:none;border-radius:8px;transition:background 0.2s;font-size:13px;"><span>📚</span> FAQ & Guide</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="vmo-dashboard-stats">
                <div class="vmo-stat-card">
                    <div class="vmo-stat-icon">📈</div>
                    <div class="vmo-stat-info">
                        <h3>Monthly Revenue</h3>
                        <p class="vmo-stat-value" id="monthly-revenue">$0</p>
                        <p class="vmo-stat-change positive">+0% this month</p>
                    </div>
                </div>
                
                <div class="vmo-stat-card">
                    <div class="vmo-stat-icon">👥</div>
                    <div class="vmo-stat-info">
                        <h3>Total Leads</h3>
                        <p class="vmo-stat-value" id="total-leads">0</p>
                        <p class="vmo-stat-change positive">+0 this week</p>
                    </div>
                </div>
                
                <div class="vmo-stat-card">
                    <div class="vmo-stat-icon">📞</div>
                    <div class="vmo-stat-info">
                        <h3>Phone Calls</h3>
                        <p class="vmo-stat-value" id="phone-calls">0</p>
                        <p class="vmo-stat-change neutral">Today</p>
                    </div>
                </div>

                <div class="vmo-stat-card">
                    <div class="vmo-stat-icon">⚡</div>
                    <div class="vmo-stat-info">
                        <h3>Universal Business Credits</h3>
                        <p class="vmo-stat-value" id="vmo-overview-balance-badge" style="color:#10b981;">Checking...</p>
                        <p class="vmo-stat-change positive" style="font-size:11px; opacity:0.8;">Valid for: Calls, Leads & AI Tasks</p>
                    </div>
                </div>
                
                <div class="vmo-stat-card">
                    <div class="vmo-stat-icon">📧</div>
                    <div class="vmo-stat-info">
                        <h3>Campaign Results</h3>
                        <p class="vmo-stat-value" id="campaign-results">0%</p>
                        <p class="vmo-stat-change positive">Open rate</p>
                    </div>
                </div>
            </div>
            
            <div class="vmo-dashboard-quick-actions">
                <h3>Quick Actions</h3>
                <div class="vmo-quick-actions-grid">
                    <button class="vmo-quick-action" onclick="VMOBusinessDashboard.startSEOAudit()">
                        <i class="🔍"></i>
                        <span>Run SEO Audit</span>
                    </button>
                    <button class="vmo-quick-action" onclick="VMOBusinessDashboard.generateLeads()">
                        <i class="🎯"></i>
                        <span>Generate Leads</span>
                    </button>
                    <button class="vmo-quick-action" onclick="VMOBusinessDashboard.createCampaign()">
                        <i class="📧"></i>
                        <span>New Campaign</span>
                    </button>
                    <button class="vmo-quick-action" onclick="VMOBusinessDashboard.generateDocument()">
                        <i class="📄"></i>
                        <span>Create Document</span>
                    </button>
                </div>
            </div>

            <div id="vmo-commerce-snapshot" style="margin-top: 1.5rem;">
                <h3>Commerce Snapshot</h3>
                <div class="vmo-dashboard-stats" style="grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));">
                    <div class="vmo-stat-card" style="display:block;">
                        <div style="display:flex;align-items:center;gap:.5rem;margin-bottom:.25rem"><div class="vmo-stat-icon">🧾</div><h3 style="margin:0;color:#4a5568;font-size:1rem">Recent Orders</h3></div>
                        <div id="vmo-recent-orders" style="font-size:.92rem;color:#1a202c">
                            <div style="color:#718096">Payments disabled or no orders yet.</div>
                        </div>
                    </div>
                    <div class="vmo-stat-card" style="display:block;">
                        <div style="display:flex;align-items:center;gap:.5rem;margin-bottom:.25rem"><div class="vmo-stat-icon">🔁</div><h3 style="margin:0;color:#4a5568;font-size:1rem">Subscriptions</h3></div>
                        <div id="vmo-subscriptions" style="font-size:.92rem;color:#1a202c">
                            <div style="color:#718096">Payments disabled or no subscriptions.</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Business Execution Roadmap & Progress Tracking -->
            <div id="vmo-roadmap-progress" style="margin-top: 1.5rem;">
                <h3>📍 Business Execution Roadmap</h3>
                <div style="display:flex; gap:10px; flex-wrap:wrap; margin: 10px 0 14px 0;">
                    <button class="vmo-btn-secondary" onclick="VMOBusinessDashboard.downloadRoadmapPDF()">⬇️ Download Roadmap (PDF)</button>
                    <button class="vmo-btn-secondary" onclick="VMOBusinessDashboard.downloadDailyActivitiesPDF()">⬇️ Download Daily Activities (PDF)</button>
                </div>
                <div id="vmo-progress-container" style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); border-radius: 12px; padding: 20px; margin-bottom: 1rem;">
                    <div id="vmo-schedule-health" style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;">
                        <div style="flex: 1;">
                            <div style="display: flex; justify-content: space-between; color: #e6f3ff; margin-bottom: 0.5rem;">
                                <span>Progress</span>
                                <span id="vmo-progress-percent">0%</span>
                            </div>
                            <div style="background: rgba(255,255,255,0.1); border-radius: 8px; height: 10px; overflow: hidden;">
                                <div id="vmo-progress-bar" style="height: 100%; background: linear-gradient(90deg, #4CAF50, #8BC34A); width: 0%; transition: width 0.5s ease;"></div>
                            </div>
                        </div>
                        <div id="vmo-health-badge" style="background: #4CAF50; color: white; padding: 5px 12px; border-radius: 20px; font-size: 0.85rem; font-weight: bold;">
                            On Track
                        </div>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; color: #e6f3ff;">
                        <div style="text-align: center;">
                            <div style="font-size: 1.5rem; font-weight: bold;" id="vmo-current-day">Day 1</div>
                            <div style="font-size: 0.85rem; opacity: 0.8;">Current Day</div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-size: 1.5rem; font-weight: bold;" id="vmo-activities-done">0 / 0</div>
                            <div style="font-size: 0.85rem; opacity: 0.8;">Activities Completed</div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-size: 1.5rem; font-weight: bold;" id="vmo-days-status">+0</div>
                            <div style="font-size: 0.85rem; opacity: 0.8;">Days Ahead/Behind</div>
                        </div>
                    </div>
                    
                    <!-- 🎯 Vision Target Date Display -->
                    <div id="vmo-vision-target-section" style="margin-top: 1.25rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.15);">
                        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 0.75rem;">
                            <div style="text-align: left;">
                                <div style="font-size: 0.85rem; opacity: 0.7; margin-bottom: 0.25rem;">🎯 Vision Achievement Date</div>
                                <div id="vmo-vision-target-date" style="font-size: 1.2rem; font-weight: bold; color: #ffc107;">Loading...</div>
                            </div>
                            <div style="text-align: right;">
                                <div style="font-size: 0.85rem; opacity: 0.7; margin-bottom: 0.25rem;">⏳ Time Remaining</div>
                                <div id="vmo-time-remaining" style="font-size: 1.2rem; font-weight: bold; color: #4fc3f7;">Loading...</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div style="display:flex; justify-content:space-between; align-items:center; margin-top:1.5rem;">
                    <h4 style="margin:0;">📋 Today's Activities</h4>
                    <button onclick="VMOBusinessDashboard.openTodaysTasks()" style="background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; border:none; padding:8px 18px; border-radius:8px; cursor:pointer; font-weight:600; font-size:0.85rem; box-shadow:0 2px 8px rgba(99,102,241,0.3);">📋 Today's Tasks Hub</button>
                </div>
                <div id="vmo-todays-activities" style="background: #f7fafc; border-radius: 8px; padding: 15px;">
                    <div style="color: #718096; text-align: center; padding: 20px;">
                        Loading activities...
                    </div>
                </div>
                
                <h4 style="margin-top: 1.5rem;">📅 Upcoming This Week</h4>
                <div id="vmo-upcoming-activities" style="background: #f7fafc; border-radius: 8px; padding: 15px;">
                    <div style="color: #718096; text-align: center; padding: 20px;">
                        Loading upcoming activities...
                    </div>
                </div>
            </div>
        `;
    }
    
    // Create business consulting section
    function createConsultingSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Business Consulting AI</h1>
                <p>Personalized business advice and strategic guidance</p>
            </div>
            <div class="vmo-consulting-interface">
                <div class="vmo-consultant-card">
                    <div class="vmo-consultant-avatar">🤖</div>
                    <div class="vmo-consultant-info">
                        <h3>VMO Business Consultant</h3>
                        <p>AI-powered strategic advisor trained on business best practices</p>
                        <div class="vmo-consultant-specialties">
                            <span class="specialty-tag">Strategy Development</span>
                            <span class="specialty-tag">Market Analysis</span>
                            <span class="specialty-tag">Growth Planning</span>
                            <span class="specialty-tag">Competitive Analysis</span>
                        </div>
                    </div>
                </div>
                <div class="vmo-consultation-chat">
                    <div class="vmo-chat-messages" id="consulting-chat">
                        <div class="vmo-message assistant">
                            <div class="vmo-message-content">
                                <p id="vmo-consulting-welcome">Welcome to the VMO Business Consultation Wizard!</p>
                                <p id="vmo-consulting-intro">I am your AI business consultant. I will guide you through every step of building your business and website. You can speak to me at any time, and I will respond with voice.</p>
                                <ul>
                                    <li>🎯 Strategic planning and goal setting</li>
                                    <li>📊 Market analysis and competitive research</li>
                                    <li>💰 Revenue optimization strategies</li>
                                    <li>🚀 Growth and expansion planning</li>
                                    <li>📈 Performance metrics and KPIs</li>
                                </ul>
                                <!-- Instruction removed per requirements -->
                            </div>
                        </div>
                    </div>
                    <div class="vmo-chat-input">
                        <!-- Start consultation button removed per requirements -->
                        <div class="vmo-consulting-mode-switch">
                            <label>Mode:</label>
                            <select id="vmo-consulting-mode">
                                <option value="voice" selected>Voice Conversation</option>
                                <option value="voice2text">Voice to Text (Transcription)</option>
                                <option value="text">Text Only</option>
                            </select>
                        </div>
                        <input type="text" id="consulting-input" placeholder="Type your question..." style="display:none;">
                        <button id="consulting-send-btn" style="display:none;">Send</button>
                    </div>
                </div>
            </div>
        `;
    }
    
    // Create SEO Management section
    function createSEOSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>SEO Management System</h1>
                <p>Automated SEO optimization and monitoring</p>
            </div>
            
            <div class="vmo-seo-dashboard">
                <div class="vmo-seo-overview">
                    <div class="vmo-seo-score">
                        <div class="vmo-score-circle">
                            <span class="vmo-score-value" id="seo-score">0</span>
                            <span class="vmo-score-label">SEO Score</span>
                        </div>
                    </div>
                    
                    <div class="vmo-seo-stats">
                        <div class="vmo-seo-stat">
                            <h4>Keyword Rankings</h4>
                            <p id="keyword-rankings">0 keywords tracked</p>
                        </div>
                        <div class="vmo-seo-stat">
                            <h4>Organic Traffic</h4>
                            <p id="organic-traffic">0 visitors</p>
                        </div>
                        <div class="vmo-seo-stat">
                            <h4>Backlinks</h4>
                            <p id="backlinks">0 links</p>
                        </div>
                    </div>
                </div>
                
                <div class="vmo-seo-actions">
                    <h3>SEO Tools</h3>
                    <div class="vmo-seo-tools">
                        <button class="vmo-seo-tool" onclick="VMOBusinessDashboard.runSEOAudit()">
                            <i class="🔍"></i>
                            <span>Full SEO Audit</span>
                        </button>
                        <button class="vmo-seo-tool" onclick="VMOBusinessDashboard.optimizeMetaTags()">
                            <i class="🏷️"></i>
                            <span>Optimize Meta Tags</span>
                        </button>
                        <button class="vmo-seo-tool" onclick="VMOBusinessDashboard.generateSitemap()">
                            <i class="🗺️"></i>
                            <span>Generate Sitemap</span>
                        </button>
                        <button class="vmo-seo-tool" onclick="VMOBusinessDashboard.keywordResearch()">
                            <i class="🔑"></i>
                            <span>Keyword Research</span>
                        </button>
                    </div>
                </div>
                
                <div class="vmo-seo-recommendations" id="seo-recommendations">
                    <h3>SEO Recommendations</h3>
                    <p>Run an SEO audit to get personalized recommendations.</p>
                </div>
            </div>
        `;
    }
    
    // Create Lead Generation section
    function createLeadsSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Lead Generation System</h1>
                <p>AI-powered lead discovery and outreach</p>
            </div>
            
            <div class="vmo-leads-dashboard">
                <div class="vmo-leads-config">
                    <h3>Lead Generation Settings</h3>
                    <form class="vmo-leads-form">
                        <div class="vmo-form-row">
                            <div class="vmo-form-group">
                                <label>Target Industry</label>
                                <select id="target-industry">
                                    <option value="">Select industry</option>
                                    <option value="technology">Technology</option>
                                    <option value="healthcare">Healthcare</option>
                                    <option value="finance">Finance</option>
                                    <option value="retail">Retail</option>
                                    <option value="manufacturing">Manufacturing</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="vmo-form-group">
                                <label>Company Size</label>
                                <select id="company-size">
                                    <option value="">Any size</option>
                                    <option value="startup">Startup (1-10)</option>
                                    <option value="small">Small (11-50)</option>
                                    <option value="medium">Medium (51-200)</option>
                                    <option value="large">Large (200+)</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="vmo-form-row">
                            <div class="vmo-form-group">
                                <label>Geographic Location</label>
                                <input type="text" id="target-location" placeholder="e.g., San Francisco, CA">
                            </div>
                            <div class="vmo-form-group">
                                <label>Keywords</label>
                                <input type="text" id="target-keywords" placeholder="e.g., digital marketing, SaaS">
                            </div>
                        </div>
                        
                        <button type="button" onclick="VMOBusinessDashboard.searchLeads()" class="vmo-btn-primary">
                            🎯 Find Leads
                        </button>
                    </form>
                </div>
                
                <div class="vmo-leads-results" id="leads-results">
                    <h3>Lead Results</h3>
                    <p>Configure your search criteria and click "Find Leads" to discover potential customers.</p>
                    
                    <!-- CSV Upload Section -->
                    <div class="vmo-csv-upload-section" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1);">
                        <h4>Import Contacts</h4>
                        <p>Upload a CSV file to add leads or customers.</p>
                        <input type="file" id="vmo-csv-upload" accept=".csv" style="display: none;" onchange="VMOBusinessDashboard.handleCSVUpload(this)">
                        <button class="vmo-btn-secondary" onclick="document.getElementById('vmo-csv-upload').click()">
                            📂 Upload CSV
                        </button>
                    </div>
                </div>
            </div>
        `;
    }
    
    // Create Campaigns section
    function createCampaignsSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Campaign Management</h1>
                <p>Email marketing and outreach automation</p>
            </div>
            
            <div class="vmo-campaigns-dashboard">
                <div class="vmo-campaign-actions">
                    <button class="vmo-btn-primary" onclick="vmoOpenEmailTool()">
                        📧 Open Email Marketing Suite
                    </button>
                </div>
                <div class="vmo-campaign-stats">
                    <div class="vmo-campaign-stat">
                        <h4>Active Campaigns</h4>
                        <p class="stat-value" id="active-campaigns">0</p>
                    </div>
                    <div class="vmo-campaign-stat">
                        <h4>Total Sent</h4>
                        <p class="stat-value" id="total-sent">0</p>
                    </div>
                    <div class="vmo-campaign-stat">
                        <h4>Open Rate</h4>
                        <p class="stat-value" id="open-rate">0%</p>
                    </div>
                    <div class="vmo-campaign-stat">
                        <h4>Click Rate</h4>
                        <p class="stat-value" id="click-rate">0%</p>
                    </div>
                </div>
                
                <div class="vmo-campaign-creator">
                    <h3>Create New Campaign</h3>
                    <button onclick="VMOBusinessDashboard.createEmailCampaign()" class="vmo-campaign-type">
                        <i class="📧"></i>
                        <div>
                            <h4>Email Campaign</h4>
                            <p>Send targeted emails to your leads</p>
                        </div>
                    </button>
                    
                    <button onclick="VMOBusinessDashboard.createFollowUpSequence()" class="vmo-campaign-type">
                        <i class="🔄"></i>
                        <div>
                            <h4>Follow-up Sequence</h4>
                            <p>Automated email sequences</p>
                        </div>
                    </button>
                    
                    <button onclick="VMOBusinessDashboard.createNewsletterCampaign()" class="vmo-campaign-type">
                        <i class="📰"></i>
                        <div>
                            <h4>Newsletter</h4>
                            <p>Regular updates to your audience</p>
                        </div>
                    </button>
                </div>
                
                <div class="vmo-campaigns-list" id="campaigns-list">
                    <h3>Recent Campaigns</h3>
                    <p>No campaigns created yet. Create your first campaign above!</p>
                </div>
            </div>
        `;
    }
    
    // Create Phone System section
    function createPhoneSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Autonomous Power Dialer & Phone System</h1>
                <p>Intelligent Robo-Sales Caller & Business Communications</p>
            </div>
            
            <div class="vmo-phone-dashboard">
            
                <div class="vmo-phone-stats" style="display:grid; grid-template-columns: repeat(3, 1fr); gap:15px; margin-bottom:30px;">
                    <div class="vmo-stat-card vmo-glass-panel">
                        <small>Voice Balance</small>
                        <h2 id="vmo-voice-balance">Loading...</h2>
                    </div>
                    <div class="vmo-stat-card vmo-glass-panel">
                         <small>Power Dialer Status</small>
                         <h2 class="status-active">Ready</h2>
                    </div>
                    <div class="vmo-stat-card vmo-glass-panel" style="background: linear-gradient(135deg, rgba(16,185,129,0.1), rgba(16,185,129,0.05)); border: 1px solid rgba(16,185,129,0.3);">
                         <small>Upgrade Capacity</small>
                         <button class="vmo-btn-primary small-btn" style="width:100%; margin-top:5px;" onclick="document.getElementById('vmo-power-dialer-plans').scrollIntoView({behavior:'smooth'})">⚡ Add Power Credits</button>
                    </div>
                </div>

                <div class="vmo-phone-setup">
                    <h3>Phone System Control Center</h3>
                    <div class="vmo-phone-options">
                        <div class="vmo-phone-option">
                            <h4>⚡ Power Dialer Campaign</h4>
                            <p>Launch autonomous AI sales calls to your lists.</p>
                            <button onclick="VMOBusinessDashboard.launchPowerDialer()" class="vmo-btn-primary">
                                Launch Power Dialer
                            </button>
                        </div>
                        
                        <div class="vmo-phone-option">
                            <h4>📞 Virtual Phone Number</h4>
                            <p>Get a professional business phone number</p>
                            <button onclick="VMOBusinessDashboard.setupVirtualNumber()" class="vmo-btn-secondary">
                                Set Up Number
                            </button>
                        </div>
                        
                        <div class="vmo-phone-option">
                            <h4>🤖 AI Receptionist</h4>
                            <p>Train your inbound call handling agent</p>
                            <button onclick="VMOBusinessDashboard.setupAIAssistant()" class="vmo-btn-secondary">
                                Configure AI Agent
                            </button>
                        </div>
                        
                        <div class="vmo-phone-option">
                            <h4>💬 SMS & Compliance</h4>
                            <p>Enable Messaging & A2P 10DLC</p>
                            <button onclick="VMOBusinessDashboard.setupSMS()" class="vmo-btn-secondary">
                                Configure SMS
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="vmo-power-dialer-plans" class="vmo-dialer-plans-integration" style="margin-top:40px; padding-top:30px; border-top:1px solid rgba(255,255,255,0.1);">
                    <h3>⚡ Upgrade Power Dialer Capacity</h3>
                    <p style="margin-bottom:20px; color:rgba(255,255,255,0.7);">
                        Purchase high-volume calling packs. <br>
                        <span style="color:#f59e0b; font-size:12px; background:rgba(245,158,11,0.1); padding:2px 6px; border-radius:4px; border:1px solid rgba(245,158,11,0.3);">⚠️ Note: These are Add-on Packs. An active Monthly Subscription is required to access the dashboard.</span>
                    </p>
                    
                    <div class="vmo-plans-grid mini-grid" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap:15px;">
                        
                        <!-- Pack M -->
                        <div class="vmo-plan-card mini" style="padding:20px; border:1px solid rgba(255,255,255,0.1); border-radius:12px; background:rgba(0,0,0,0.2);">
                            <h4 style="color:#10b981;">Phone Pack M</h4>
                            <div class="price" style="font-size:24px; font-weight:bold; margin:10px 0;">$99.99<small style="font-size:14px; color:#aaa;">/yr</small></div>
                            <ul style="font-size:13px; opacity:0.8; padding-left:15px; list-style:disc; margin-bottom:15px;">
                                <li>$300.00 in Credits</li>
                                <li>~252 Minutes</li>
                            </ul>
                            <button class="vmo-btn-secondary" data-plan="phone_m" onclick="VMOBusinessDashboard.buyPack('phone_m')" style="width:100%;">Purchase Pack M</button>
                        </div>

                        <!-- Pack L -->
                        <div class="vmo-plan-card mini" style="padding:20px; border:1px solid rgba(255,255,255,0.1); border-radius:12px; background:rgba(0,0,0,0.2);">
                            <h4 style="color:#10b981;">Phone Pack L</h4>
                            <div class="price" style="font-size:24px; font-weight:bold; margin:10px 0;">$249.99<small style="font-size:14px; color:#aaa;">/yr</small></div>
                             <ul style="font-size:13px; opacity:0.8; padding-left:15px; list-style:disc; margin-bottom:15px;">
                                <li>$750.00 in Credits</li>
                                <li>~630 Minutes</li>
                            </ul>
                            <button class="vmo-btn-secondary" data-plan="phone_l" onclick="VMOBusinessDashboard.buyPack('phone_l')" style="width:100%;">Purchase Pack L</button>
                        </div>

                        <!-- Power Dialer -->
                        <div class="vmo-plan-card mini" style="padding:20px; border:1px solid #f59e0b; border-radius:12px; background:linear-gradient(180deg, rgba(245,158,11,.1), rgba(0,0,0,0.3));">
                            <h4 style="color:#f59e0b;">Power Dialer</h4>
                            <div class="price" style="font-size:24px; font-weight:bold; margin:10px 0;">$499.99<small style="font-size:14px; color:#aaa;">/yr</small></div>
                             <ul style="font-size:13px; opacity:0.8; padding-left:15px; list-style:disc; margin-bottom:15px;">
                                <li>$1,680.00 in Credits</li>
                                <li>~1,417 Minutes</li>
                            </ul>
                            <button class="vmo-btn-primary" data-plan="power_dialer" onclick="VMOBusinessDashboard.buyPack('power_dialer')" style="width:100%; background:#f59e0b; border-color:#f59e0b;">Purchase Power Dialer</button>
                        </div>

                        <!-- Pro Call Center -->
                        <div class="vmo-plan-card mini" style="padding:20px; border:1px solid #ef4444; border-radius:12px; background:linear-gradient(180deg, rgba(239,68,68,.1), rgba(0,0,0,0.3));">
                            <h4 style="color:#ef4444;">Pro Call Center</h4>
                            <div class="price" style="font-size:24px; font-weight:bold; margin:10px 0;">$699.99<small style="font-size:14px; color:#aaa;">/yr</small></div>
                             <ul style="font-size:13px; opacity:0.8; padding-left:15px; list-style:disc; margin-bottom:15px;">
                                <li>$2,400.00 in Credits</li>
                                <li>~500 Calls (4m)</li>
                            </ul>
                            <button class="vmo-btn-primary" data-plan="phone_xl" onclick="VMOBusinessDashboard.buyPack('phone_xl')" style="width:100%; background:#ef4444; border-color:#ef4444;">Get Call Center</button>
                        </div>
                        
                    </div>
                </div>

                <div class="vmo-phone-features" style="margin-top:30px;">
                    <h3>Autonomous Features</h3>
                    <div class="vmo-features-grid">
                        <div class="vmo-feature">
                            <i class="📝"></i>
                            <h4>Call Transcription</h4>
                            <p>Automatic transcription of all calls</p>
                        </div>
                        <div class="vmo-feature">
                            <i class="📞"></i>
                            <h4>Call Forwarding</h4>
                            <p>Route calls to any device</p>
                        </div>
                        <div class="vmo-feature">
                            <i class="📧"></i>
                            <h4>Voicemail to Email</h4>
                            <p>Get voicemails in your inbox</p>
                        </div>
                        <div class="vmo-feature">
                            <i class="📈"></i>
                            <h4>Call Tracking</h4>
                            <p>Track marketing campaign calls</p>
                        </div>
                    </div>
                </div>
                
                <div class="vmo-recent-calls" id="recent-calls">
                    <h3>Recent Calls</h3>
                    <p>Set up your phone system to start tracking calls.</p>
                </div>
            </div>
        `;
    }
    
    // Create Legal Documents section
    function createLegalSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Legal Documents Generator</h1>
                <p>AI-generated legal documents for your business</p>
            </div>
            
            <div class="vmo-legal-dashboard">
                <div class="vmo-legal-categories">
                    <h3>Document Categories</h3>
                    <div class="vmo-legal-grid">
                        <div class="vmo-legal-category" onclick="VMOBusinessDashboard.showDocumentType('business-formation')">
                            <i class="🏢"></i>
                            <h4>Business Formation</h4>
                            <p>LLC, Corporation, Partnership</p>
                        </div>
                        
                        <div class="vmo-legal-category" onclick="VMOBusinessDashboard.showDocumentType('contracts')">
                            <i class="📋"></i>
                            <h4>Contracts & Agreements</h4>
                            <p>Service, Employment, NDA</p>
                        </div>
                        
                        <div class="vmo-legal-category" onclick="VMOBusinessDashboard.showDocumentType('policies')">
                            <i class="📄"></i>
                            <h4>Policies & Terms</h4>
                            <p>Privacy, Terms of Service</p>
                        </div>
                        
                        <div class="vmo-legal-category" onclick="VMOBusinessDashboard.showDocumentType('templates')">
                            <i class="📝"></i>
                            <h4>Business Templates</h4>
                            <p>Invoices, Proposals, Forms</p>
                        </div>
                    </div>
                </div>
                
                <div class="vmo-document-generator" id="document-generator">
                    <h3>Select a category above to generate documents</h3>
                    <p>Our AI will create customized legal documents based on your business information.</p>
                </div>
                
                <div class="vmo-generated-documents" id="generated-documents">
                    <h3>Your Generated Documents</h3>
                    <p>Generated documents will appear here for download and editing.</p>
                </div>
            </div>
        `;
    }
    
    // Create Business Plan section
    function createBusinessPlanSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Business Plan Generator</h1>
                <p>Comprehensive business plans and execution roadmaps</p>
            </div>
            
            <div class="vmo-business-plan-dashboard">
                <div class="vmo-plan-generator">
                    <h3>Generate Your Business Plan</h3>
                    <form class="vmo-business-plan-form">
                        <div class="vmo-form-section">
                            <h4>Business Overview</h4>
                            <div class="vmo-form-row">
                                <input type="text" id="business-name" placeholder="Business Name" required>
                                <select id="business-type" required>
                                    <option value="">Select Business Type</option>
                                    <option value="llc">LLC</option>
                                    <option value="corporation">Corporation</option>
                                    <option value="partnership">Partnership</option>
                                    <option value="sole-proprietorship">Sole Proprietorship</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="vmo-form-section">
                            <h4>Market Information</h4>
                            <textarea id="target-market" placeholder="Describe your target market and customers"></textarea>
                            <textarea id="competitive-advantage" placeholder="What makes your business unique?"></textarea>
                        </div>
                        
                        <div class="vmo-form-section">
                            <h4>Financial Projections</h4>
                            <div class="vmo-form-row">
                                <input type="number" id="startup-capital" placeholder="Startup Capital ($)">
                                <input type="number" id="revenue-year1" placeholder="Year 1 Revenue Goal ($)">
                            </div>
                        </div>
                        
                        <button type="button" onclick="VMOBusinessDashboard.generateBusinessPlan()" class="vmo-btn-primary">
                            📈 Generate Complete Business Plan
                        </button>
                    </form>
                </div>
                
                <div class="vmo-business-plan-results" id="business-plan-results">
                    <p>Fill out the form above to generate your comprehensive business plan.</p>
                </div>
            </div>
        `;
    }
    
    // Create Tasks section
    function createTasksSection() {
        return `
            <div class="vmo-dashboard-header">
                <h1>Business Task Manager</h1>
                <p>AI-generated action items and daily tasks</p>
            </div>
            
            <div class="vmo-tasks-dashboard">
                <div class="vmo-task-summary">
                    <div class="vmo-task-stat">
                        <h4>Today's Tasks</h4>
                        <p class="stat-value" id="today-tasks">0</p>
                    </div>
                    <div class="vmo-task-stat">
                        <h4>This Week</h4>
                        <p class="stat-value" id="week-tasks">0</p>
                    </div>
                    <div class="vmo-task-stat">
                        <h4>Completed</h4>
                        <p class="stat-value" id="completed-tasks">0</p>
                    </div>
                    <div class="vmo-task-stat">
                        <h4>Progress</h4>
                        <p class="stat-value" id="progress-percent">0%</p>
                    </div>
                </div>
                
                <div class="vmo-task-generator">
                    <button onclick="VMOBusinessDashboard.generateDailyTasks()" class="vmo-btn-primary">
                        ✨ Generate Today's Tasks
                    </button>
                    <button onclick="VMOBusinessDashboard.generateWeeklyPlan()" class="vmo-btn-secondary">
                        📅 Create Weekly Plan
                    </button>
                </div>
                
                <div class="vmo-tasks-list" id="tasks-list">
                    <h3>Your Business Tasks</h3>
                    <p>Generate daily tasks to get started with your business action plan.</p>
                </div>
            </div>
        `;
    }

    // ═══════════════════════════════════════════════════════════════════
    // PAYMENTS & TAX SECTION - VMO Pay white-labelled Stripe Tax
    // ═══════════════════════════════════════════════════════════════════

    function createPaymentsTaxSection() {
        return `
            <div class="vmo-dashboard-header">
                <div style="display:flex; justify-content:space-between; align-items:center; width:100%; flex-wrap:wrap; gap:10px;">
                    <div>
                        <h1>💰 Payments & Tax</h1>
                        <p>Revenue tracking, tax estimation, and financial planning — powered by VMO Pay</p>
                    </div>
                    <div style="display:flex;gap:8px;">
                        <select id="vmo-tax-period" onchange="VMOBusinessDashboard.changeTaxPeriod(this.value)" style="padding:8px 12px;border-radius:8px;background:#1e293b;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:13px;">
                            <option value="year">This Year</option>
                            <option value="quarter">This Quarter</option>
                            <option value="month">This Month</option>
                            <option value="all">All Time</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Country & Tax Settings -->
            <div style="background:linear-gradient(135deg,#1e3a5f 0%,#0f2940 100%);border-radius:16px;padding:24px;margin-bottom:1.5rem;border:1px solid rgba(59,130,246,0.3);">
                <h3 style="margin:0 0 16px 0;color:#93c5fd;font-size:1.1rem;">🌍 Tax Jurisdiction Settings</h3>
                <p style="color:#94a3b8;font-size:0.9rem;margin:0 0 16px 0;">Select your country to load applicable tax laws. VMO Pay automatically calculates your tax obligations.</p>
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;">
                    <div>
                        <label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:4px;">Country</label>
                        <select id="vmo-tax-country" onchange="VMOBusinessDashboard.onTaxCountryChange(this.value)" style="width:100%;padding:10px 12px;border-radius:8px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.15);font-size:14px;">
                            <option value="">— Select Your Country —</option>
                        </select>
                    </div>
                    <div id="vmo-state-container" style="display:none;">
                        <label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:4px;" id="vmo-state-label">State / Province</label>
                        <select id="vmo-tax-state" onchange="VMOBusinessDashboard.onTaxStateChange(this.value)" style="width:100%;padding:10px 12px;border-radius:8px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.15);font-size:14px;">
                            <option value="">— Select —</option>
                        </select>
                    </div>
                    <div>
                        <label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:4px;">Filing Status</label>
                        <select id="vmo-filing-status" style="width:100%;padding:10px 12px;border-radius:8px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.15);font-size:14px;">
                            <option value="single">Individual / Sole Proprietor</option>
                            <option value="married">Married Filing Jointly</option>
                            <option value="partnership">Partnership</option>
                            <option value="corporation">Corporation / LLC</option>
                        </select>
                    </div>
                    <div style="display:flex;align-items:flex-end;">
                        <button onclick="VMOBusinessDashboard.saveTaxSettings()" style="width:100%;padding:10px 16px;border-radius:8px;background:linear-gradient(135deg,#3b82f6,#2563eb);color:white;border:none;cursor:pointer;font-weight:600;font-size:14px;">
                            💾 Save Settings
                        </button>
                    </div>
                </div>
            </div>

            <!-- Revenue Summary -->
            <div class="vmo-dashboard-stats" style="grid-template-columns:repeat(auto-fit,minmax(180px,1fr));margin-bottom:1.5rem;">
                <div class="vmo-stat-card" style="background:linear-gradient(135deg,#064e3b,#065f46);border:1px solid rgba(16,185,129,0.3);">
                    <div class="vmo-stat-icon">💵</div>
                    <h4 style="color:#6ee7b7;margin:0 0 4px 0;">Gross Revenue</h4>
                    <p class="vmo-stat-value" id="vmo-tax-gross" style="color:#ecfdf5;font-size:1.5rem;margin:0;">$0.00</p>
                    <p style="color:#6ee7b7;font-size:0.8rem;margin:4px 0 0 0;" id="vmo-tax-orders">0 orders</p>
                </div>
                <div class="vmo-stat-card" style="background:linear-gradient(135deg,#7c2d12,#9a3412);border:1px solid rgba(251,146,60,0.3);">
                    <div class="vmo-stat-icon">📋</div>
                    <h4 style="color:#fed7aa;margin:0 0 4px 0;">Total Expenses</h4>
                    <p class="vmo-stat-value" id="vmo-tax-expenses" style="color:#fff7ed;font-size:1.5rem;margin:0;">$0.00</p>
                    <p style="color:#fed7aa;font-size:0.8rem;margin:4px 0 0 0;" id="vmo-tax-fees">Fees: $0.00</p>
                </div>
                <div class="vmo-stat-card" style="background:linear-gradient(135deg,#1e3a5f,#1e40af);border:1px solid rgba(96,165,250,0.3);">
                    <div class="vmo-stat-icon">📊</div>
                    <h4 style="color:#bfdbfe;margin:0 0 4px 0;">Net Profit</h4>
                    <p class="vmo-stat-value" id="vmo-tax-net" style="color:#eff6ff;font-size:1.5rem;margin:0;">$0.00</p>
                    <p style="color:#bfdbfe;font-size:0.8rem;margin:4px 0 0 0;" id="vmo-tax-net-label">Before tax</p>
                </div>
                <div class="vmo-stat-card" style="background:linear-gradient(135deg,#581c87,#7c3aed);border:1px solid rgba(167,139,250,0.3);">
                    <div class="vmo-stat-icon">🏛️</div>
                    <h4 style="color:#ddd6fe;margin:0 0 4px 0;">Estimated Tax</h4>
                    <p class="vmo-stat-value" id="vmo-tax-amount" style="color:#f5f3ff;font-size:1.5rem;margin:0;">$0.00</p>
                    <p style="color:#ddd6fe;font-size:0.8rem;margin:4px 0 0 0;" id="vmo-tax-rate">Effective: 0%</p>
                </div>
            </div>

            <!-- Tax Breakdown -->
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;margin-bottom:1.5rem;">
                <!-- Tax Breakdown Panel -->
                <div style="background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;border:1px solid rgba(255,255,255,0.08);">
                    <h3 style="color:#e2e8f0;margin:0 0 16px 0;font-size:1rem;">📑 Tax Breakdown</h3>
                    <div id="vmo-tax-breakdown" style="color:#94a3b8;font-size:0.9rem;">
                        <p style="text-align:center;padding:20px 0;color:#64748b;">Select your country above to see your tax breakdown</p>
                    </div>
                </div>

                <!-- Income vs Tax Visual -->
                <div style="background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;border:1px solid rgba(255,255,255,0.08);">
                    <h3 style="color:#e2e8f0;margin:0 0 16px 0;font-size:1rem;">📈 Income Distribution</h3>
                    <div id="vmo-income-distribution">
                        <div style="text-align:center;padding:20px 0;color:#64748b;">
                            <p>Your income distribution will appear here after tax calculation</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Expense Tracker -->
            <div style="background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;margin-bottom:1.5rem;border:1px solid rgba(255,255,255,0.08);">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                    <h3 style="color:#e2e8f0;margin:0;font-size:1rem;">📝 Business Expense Tracker</h3>
                    <button onclick="VMOBusinessDashboard.addExpenseRow()" style="padding:6px 14px;border-radius:8px;background:rgba(16,185,129,0.15);color:#10b981;border:1px solid rgba(16,185,129,0.3);cursor:pointer;font-size:0.85rem;font-weight:600;">
                        + Add Expense
                    </button>
                </div>
                <div id="vmo-expenses-list" style="color:#94a3b8;">
                    <p style="text-align:center;color:#64748b;font-size:0.9rem;">No expenses recorded yet. Add your business expenses to improve tax estimates.</p>
                </div>
                <div style="margin-top:12px;text-align:right;">
                    <button onclick="VMOBusinessDashboard.saveExpenses()" style="padding:8px 20px;border-radius:8px;background:linear-gradient(135deg,#3b82f6,#2563eb);color:white;border:none;cursor:pointer;font-weight:600;font-size:13px;">
                        💾 Save Expenses
                    </button>
                </div>
            </div>

            <!-- Manual Tax Calculator -->
            <div style="background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;margin-bottom:1.5rem;border:1px solid rgba(255,255,255,0.08);">
                <h3 style="color:#e2e8f0;margin:0 0 16px 0;font-size:1rem;">🧮 Tax Calculator</h3>
                <p style="color:#94a3b8;font-size:0.85rem;margin:0 0 16px 0;">Enter amounts manually or use your actual VMO Pay revenue for instant tax estimation.</p>
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-bottom:16px;">
                    <div>
                        <label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:4px;">Gross Income</label>
                        <input type="number" id="vmo-calc-income" placeholder="0.00" style="width:100%;padding:10px 12px;border-radius:8px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.15);font-size:14px;box-sizing:border-box;">
                    </div>
                    <div>
                        <label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:4px;">Total Expenses</label>
                        <input type="number" id="vmo-calc-expenses" placeholder="0.00" style="width:100%;padding:10px 12px;border-radius:8px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.15);font-size:14px;box-sizing:border-box;">
                    </div>
                </div>
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <button onclick="VMOBusinessDashboard.calculateTax(false)" style="padding:10px 20px;border-radius:8px;background:linear-gradient(135deg,#7c3aed,#6d28d9);color:white;border:none;cursor:pointer;font-weight:600;font-size:13px;">
                        🧮 Calculate Tax
                    </button>
                    <button onclick="VMOBusinessDashboard.calculateTax(true)" style="padding:10px 20px;border-radius:8px;background:linear-gradient(135deg,#10b981,#059669);color:white;border:none;cursor:pointer;font-weight:600;font-size:13px;">
                        📊 Use Actual VMO Pay Revenue
                    </button>
                    <button onclick="VMOBusinessDashboard.runAITaxAnalysis()" style="padding:10px 20px;border-radius:8px;background:linear-gradient(135deg,#f59e0b,#d97706);color:white;border:none;cursor:pointer;font-weight:600;font-size:13px;">
                        🤖 AI Tax Advisor
                    </button>
                </div>
            </div>

            <!-- AI Tax Analysis Results -->
            <div id="vmo-ai-tax-analysis" style="display:none;background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;margin-bottom:1.5rem;border:1px solid rgba(245,158,11,0.3);">
                <h3 style="color:#fbbf24;margin:0 0 12px 0;font-size:1rem;">🤖 AI Tax Analysis</h3>
                <div id="vmo-ai-tax-content" style="color:#e2e8f0;font-size:0.9rem;line-height:1.7;white-space:pre-wrap;"></div>
            </div>

            <!-- Indirect Tax Info -->
            <div id="vmo-indirect-tax-info" style="display:none;background:linear-gradient(135deg,#1a1a2e,#16213e);border-radius:16px;padding:20px;border:1px solid rgba(255,255,255,0.08);">
                <h3 style="color:#e2e8f0;margin:0 0 12px 0;font-size:1rem;">🏷️ Indirect Taxes (VAT / GST / Sales Tax)</h3>
                <div id="vmo-indirect-tax-content" style="color:#94a3b8;font-size:0.9rem;"></div>
                <p style="color:#64748b;font-size:0.8rem;margin:12px 0 0 0;font-style:italic;">Note: Indirect taxes (VAT/GST/Sales Tax) are collected from your customers, not levied on your income. They are shown here for reference.</p>
            </div>

            <div style="margin-top:1.5rem;padding:16px;background:rgba(245,158,11,0.08);border-radius:12px;border:1px solid rgba(245,158,11,0.2);">
                <p style="color:#fbbf24;font-size:0.85rem;margin:0;line-height:1.6;">
                    ⚠️ <strong>Disclaimer:</strong> Tax estimates are for planning purposes only and based on standard tax rates for your selected jurisdiction. 
                    Actual tax obligations may vary based on credits, deductions, filing status, and other factors. Always consult a qualified tax professional for official filing advice.
                </p>
            </div>
        `;
    }

    // ═══════════════════════════════════════════════════════════════════
    // PAYMENTS & TAX DATA LOADING & INTERACTION LOGIC
    // ═══════════════════════════════════════════════════════════════════

    function loadPaymentsTaxData() {
        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');

        // 1. Load countries into the dropdown
        fetch(apiRoot + 'vmo-builder/v1/tax/countries', { credentials: 'include' })
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                const sel = document.getElementById('vmo-tax-country');
                if (!sel) return;
                // Group countries by region
                const countries = data.countries;
                const sorted = Object.keys(countries).sort((a,b) => countries[a].name.localeCompare(countries[b].name));
                sel.innerHTML = '<option value="">— Select Your Country —</option>';
                sorted.forEach(code => {
                    const c = countries[code];
                    const opt = document.createElement('option');
                    opt.value = code;
                    opt.textContent = c.name + ' (' + c.currency + ')';
                    sel.appendChild(opt);
                });

                // 2. Load saved tax settings and apply
                return fetch(apiRoot + 'vmo-builder/v1/tax/settings', { credentials: 'include' }).then(r => r.json());
            })
            .then(data => {
                if (!data || !data.success) return;
                const s = data.settings;
                const countryEl = document.getElementById('vmo-tax-country');
                const filingEl = document.getElementById('vmo-filing-status');
                if (countryEl && s.country) {
                    countryEl.value = s.country;
                    VMOBusinessDashboard.onTaxCountryChange(s.country, s.state);
                }
                if (filingEl && s.filing_status) filingEl.value = s.filing_status;
            })
            .catch(e => console.warn('Tax settings load error:', e));

        // 3. Load tax summary (revenue + tax estimate)
        loadTaxSummary();
    }

    function loadTaxSummary() {
        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
        const period = document.getElementById('vmo-tax-period')?.value || 'year';

        fetch(apiRoot + 'vmo-builder/v1/tax/summary?period=' + period, { credentials: 'include' })
            .then(r => r.json())
            .then(data => {
                if (!data.success || !data.data) return;
                const d = data.data;
                const rev = d.revenue || {};
                const fmt = (v, cur) => {
                    const sym = cur === 'GBP' ? '£' : cur === 'EUR' ? '€' : cur === 'JPY' ? '¥' : '$';
                    return sym + parseFloat(v || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                };
                const cur = d.settings?.country ? (window._vmoTaxCurrency || 'USD') : 'USD';

                // Update stat cards
                const grossEl = document.getElementById('vmo-tax-gross');
                const expEl = document.getElementById('vmo-tax-expenses');
                const netEl = document.getElementById('vmo-tax-net');
                const taxEl = document.getElementById('vmo-tax-amount');
                const rateEl = document.getElementById('vmo-tax-rate');
                const ordersEl = document.getElementById('vmo-tax-orders');
                const feesEl = document.getElementById('vmo-tax-fees');

                if (grossEl) grossEl.textContent = fmt(rev.gross_income, cur);
                if (ordersEl) ordersEl.textContent = (rev.order_count || 0) + ' orders';
                if (expEl) expEl.textContent = fmt(d.total_expenses, cur);
                if (feesEl) feesEl.textContent = 'Fees: ' + fmt(rev.total_fees, cur);

                if (d.tax_estimate) {
                    const te = d.tax_estimate;
                    if (netEl) netEl.textContent = fmt(te.net_profit, cur);
                    if (taxEl) taxEl.textContent = fmt(te.total_tax, cur);
                    if (rateEl) rateEl.textContent = 'Effective: ' + (te.effective_rate || 0) + '%';

                    // Tax breakdown
                    renderTaxBreakdown(te, cur);
                    renderIncomeDistribution(te, cur);

                    // Indirect tax info
                    if (te.indirect_taxes) {
                        renderIndirectTaxInfo(te.indirect_taxes, te.sales_tax);
                    }
                } else {
                    const net = Math.max(0, (rev.gross_income || 0) - (d.total_expenses || 0));
                    if (netEl) netEl.textContent = fmt(net, cur);
                }

                // Load expenses
                if (d.expenses && d.expenses.length > 0) {
                    renderExpensesList(d.expenses);
                }
            })
            .catch(e => console.warn('Tax summary load error:', e));
    }

    function renderTaxBreakdown(taxEstimate, currency) {
        const container = document.getElementById('vmo-tax-breakdown');
        if (!container || !taxEstimate) return;
        const bd = taxEstimate.breakdown || [];
        const fmt = (v) => {
            const sym = currency === 'GBP' ? '£' : currency === 'EUR' ? '€' : '$';
            const val = parseFloat(v || 0);
            const sign = val < 0 ? '-' : '';
            return sign + sym + Math.abs(val).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        };

        if (bd.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:#64748b;">No tax data available</p>';
            return;
        }

        let html = '<div style="display:flex;flex-direction:column;gap:8px;">';
        bd.forEach(item => {
            const color = item.amount < 0 ? '#10b981' : '#f87171';
            const rateStr = item.rate ? ' (' + item.rate + '%)' : '';
            html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:8px 12px;background:rgba(255,255,255,0.03);border-radius:8px;">';
            html += '<div><span style="color:#e2e8f0;font-size:0.9rem;">' + item.label + rateStr + '</span>';
            if (item.note) html += '<div style="color:#64748b;font-size:0.75rem;margin-top:2px;">' + item.note + '</div>';
            html += '</div>';
            html += '<span style="color:' + color + ';font-weight:600;font-size:0.95rem;">' + fmt(item.amount) + '</span>';
            html += '</div>';
        });

        // Total
        html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:rgba(124,58,237,0.15);border-radius:8px;border:1px solid rgba(124,58,237,0.3);margin-top:4px;">';
        html += '<span style="color:#a78bfa;font-weight:700;font-size:1rem;">Total Estimated Tax</span>';
        html += '<span style="color:#c4b5fd;font-weight:700;font-size:1.1rem;">' + fmt(taxEstimate.total_tax) + '</span>';
        html += '</div>';

        if (taxEstimate.net_after_tax !== undefined) {
            html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:rgba(16,185,129,0.1);border-radius:8px;border:1px solid rgba(16,185,129,0.2);margin-top:4px;">';
            html += '<span style="color:#6ee7b7;font-weight:600;">Net After Tax</span>';
            html += '<span style="color:#a7f3d0;font-weight:700;font-size:1.1rem;">' + fmt(taxEstimate.net_after_tax) + '</span>';
            html += '</div>';
        }

        html += '</div>';

        if (taxEstimate.disclaimer) {
            html += '<p style="color:#64748b;font-size:0.75rem;margin:12px 0 0 0;font-style:italic;">' + taxEstimate.disclaimer + '</p>';
        }

        container.innerHTML = html;
    }

    function renderIncomeDistribution(taxEstimate, currency) {
        const container = document.getElementById('vmo-income-distribution');
        if (!container || !taxEstimate) return;
        const gross = parseFloat(taxEstimate.gross_income || 0);
        const expenses = parseFloat(taxEstimate.total_expenses || 0);
        const tax = parseFloat(taxEstimate.total_tax || 0);
        const net = parseFloat(taxEstimate.net_after_tax || 0);
        const total = gross || 1;

        const expPct = Math.round((expenses / total) * 100);
        const taxPct = Math.round((tax / total) * 100);
        const netPct = Math.max(0, 100 - expPct - taxPct);

        const fmt = (v) => {
            const sym = currency === 'GBP' ? '£' : currency === 'EUR' ? '€' : '$';
            return sym + parseFloat(v).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        };

        container.innerHTML = '<div style="margin-bottom:16px;">' +
            '<div style="display:flex;height:24px;border-radius:12px;overflow:hidden;background:rgba(255,255,255,0.05);">' +
                '<div style="width:' + netPct + '%;background:linear-gradient(90deg,#10b981,#34d399);transition:width 0.5s;" title="Net Income: ' + netPct + '%"></div>' +
                '<div style="width:' + expPct + '%;background:linear-gradient(90deg,#f59e0b,#fbbf24);transition:width 0.5s;" title="Expenses: ' + expPct + '%"></div>' +
                '<div style="width:' + taxPct + '%;background:linear-gradient(90deg,#ef4444,#f87171);transition:width 0.5s;" title="Tax: ' + taxPct + '%"></div>' +
            '</div>' +
        '</div>' +
        '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;text-align:center;">' +
            '<div>' +
                '<div style="display:flex;align-items:center;justify-content:center;gap:6px;margin-bottom:4px;">' +
                    '<div style="width:12px;height:12px;border-radius:50%;background:#10b981;"></div>' +
                    '<span style="color:#94a3b8;font-size:0.8rem;">Net Income</span>' +
                '</div>' +
                '<div style="color:#34d399;font-weight:700;font-size:1.1rem;">' + fmt(net) + '</div>' +
                '<div style="color:#6ee7b7;font-size:0.75rem;">' + netPct + '% of gross</div>' +
            '</div>' +
            '<div>' +
                '<div style="display:flex;align-items:center;justify-content:center;gap:6px;margin-bottom:4px;">' +
                    '<div style="width:12px;height:12px;border-radius:50%;background:#f59e0b;"></div>' +
                    '<span style="color:#94a3b8;font-size:0.8rem;">Expenses</span>' +
                '</div>' +
                '<div style="color:#fbbf24;font-weight:700;font-size:1.1rem;">' + fmt(expenses) + '</div>' +
                '<div style="color:#fcd34d;font-size:0.75rem;">' + expPct + '% of gross</div>' +
            '</div>' +
            '<div>' +
                '<div style="display:flex;align-items:center;justify-content:center;gap:6px;margin-bottom:4px;">' +
                    '<div style="width:12px;height:12px;border-radius:50%;background:#ef4444;"></div>' +
                    '<span style="color:#94a3b8;font-size:0.8rem;">Tax</span>' +
                '</div>' +
                '<div style="color:#f87171;font-weight:700;font-size:1.1rem;">' + fmt(tax) + '</div>' +
                '<div style="color:#fca5a5;font-size:0.75rem;">' + taxPct + '% of gross</div>' +
            '</div>' +
        '</div>';
    }

    function renderIndirectTaxInfo(indirectTax, salesTax) {
        const container = document.getElementById('vmo-indirect-tax-info');
        const content = document.getElementById('vmo-indirect-tax-content');
        if (!container || !content) return;

        let html = '';
        if (indirectTax) {
            html += '<div style="display:flex;gap:20px;flex-wrap:wrap;">';
            html += '<div style="padding:12px 20px;background:rgba(255,255,255,0.05);border-radius:8px;">';
            html += '<div style="color:#e2e8f0;font-weight:600;">' + indirectTax.type + ' Standard Rate</div>';
            html += '<div style="color:#10b981;font-size:1.3rem;font-weight:700;">' + indirectTax.standard_rate + '%</div>';
            html += '</div>';
            if (indirectTax.reduced_rate) {
                html += '<div style="padding:12px 20px;background:rgba(255,255,255,0.05);border-radius:8px;">';
                html += '<div style="color:#e2e8f0;font-weight:600;">' + indirectTax.type + ' Reduced Rate</div>';
                html += '<div style="color:#3b82f6;font-size:1.3rem;font-weight:700;">' + indirectTax.reduced_rate + '%</div>';
                html += '</div>';
            }
            html += '</div>';
        }
        if (salesTax) {
            html += '<div style="margin-top:12px;padding:12px 20px;background:rgba(255,255,255,0.05);border-radius:8px;">';
            html += '<div style="color:#e2e8f0;font-weight:600;">State Sales Tax Rate</div>';
            html += '<div style="color:#f59e0b;font-size:1.3rem;font-weight:700;">' + salesTax.state_rate + '%</div>';
            if (salesTax.note) html += '<div style="color:#94a3b8;font-size:0.8rem;margin-top:4px;">' + salesTax.note + '</div>';
            html += '</div>';
        }

        content.innerHTML = html;
        container.style.display = (html ? 'block' : 'none');
    }

    function renderExpensesList(expenses) {
        const container = document.getElementById('vmo-expenses-list');
        if (!container || !Array.isArray(expenses) || expenses.length === 0) return;

        const categories = {
            'software': '💻', 'marketing': '📢', 'hosting': '🌐', 'supplies': '📦',
            'travel': '✈️', 'office': '🏢', 'insurance': '🛡️', 'professional': '👔',
            'utilities': '⚡', 'other': '📎'
        };

        let html = '<div style="display:flex;flex-direction:column;gap:8px;">';
        expenses.forEach((exp, i) => {
            const icon = categories[exp.category] || '📎';
            html += '<div class="vmo-expense-row" data-index="' + i + '" style="display:grid;grid-template-columns:40px 1fr 1fr auto auto;gap:8px;align-items:center;padding:8px 12px;background:rgba(255,255,255,0.03);border-radius:8px;">';
            html += '<span style="font-size:1.3rem;">' + icon + '</span>';
            html += '<input type="text" value="' + (exp.description || '') + '" placeholder="Description" class="vmo-exp-desc" style="padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;">';
            html += '<select class="vmo-exp-cat" style="padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;">';
            Object.keys(categories).forEach(cat => {
                html += '<option value="' + cat + '"' + (exp.category === cat ? ' selected' : '') + '>' + categories[cat] + ' ' + cat.charAt(0).toUpperCase() + cat.slice(1) + '</option>';
            });
            html += '</select>';
            html += '<input type="number" value="' + (exp.amount || '') + '" placeholder="0.00" class="vmo-exp-amount" style="width:100px;padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;text-align:right;">';
            html += '<button onclick="this.closest(\'.vmo-expense-row\').remove()" style="padding:4px 8px;border-radius:6px;background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.3);cursor:pointer;font-size:0.8rem;">✕</button>';
            html += '</div>';
        });
        html += '</div>';
        container.innerHTML = html;
    }
    
    // Navigation handler
    function setupNavigationHandlers() {
        document.addEventListener('click', (e) => {
            if (e.target.matches('.vmo-nav-item')) {
                e.preventDefault();
                const section = e.target.dataset.section;
                if (section) {
                    showSection(section);
                    
                    // Update active nav item
                    document.querySelectorAll('.vmo-nav-item').forEach(item => item.classList.remove('active'));
                    e.target.classList.add('active');
                }
            }
            
            // Handle consultation button click
            if (e.target.matches('#vmo-start-consultation')) {
                e.preventDefault();
                console.log('Starting voice consultation...');
                VMOBusinessDashboard.startVoiceConsultation();
            }
        });
    }
    
    // Show specific dashboard section
    function showSection(sectionName) {
        // Hide all sections
        document.querySelectorAll('.vmo-dashboard-section').forEach(section => {
            section.classList.remove('active');
        });
        
        // Show selected section
        const targetSection = document.getElementById(`vmo-section-${sectionName}`);
        if (targetSection) {
            targetSection.classList.add('active');
        }
        
        // Load section-specific data
        loadSectionData(sectionName);
    }
    
    // Load data for specific section
    function loadSectionData(sectionName) {
        switch (sectionName) {
            case 'overview':
                loadOverviewData();
                break;
            case 'seo':
                loadSEOData();
                break;
            case 'leads':
                loadLeadsData();
                break;
            case 'campaigns':
                loadCampaignsData();
                break;
            case 'affiliates':
                VMOBusinessDashboard.loadAffiliateData();
                break;
            case 'payments-tax':
                loadPaymentsTaxData();
                break;
            // Add more cases as needed
        }
    }
    
    // Load overview data
    function loadOverviewData() {
        // Defaults while loading
        const $rev = document.getElementById('monthly-revenue');
        const $leads = document.getElementById('total-leads');
        const $calls = document.getElementById('phone-calls');
        const $camp = document.getElementById('campaign-results');
        if ($rev) $rev.textContent = '$0.00';
        if ($leads) $leads.textContent = '0';
        if ($calls) $calls.textContent = '0';
        if ($camp) $camp.textContent = '0%';

        // ── Fetch comprehensive KPIs from the vmo_get_dashboard_kpis endpoint ──
        if (typeof jQuery !== 'undefined' && typeof vmo_ajax !== 'undefined') {
            jQuery.post(vmo_ajax.ajaxurl, {
                action: 'vmo_get_dashboard_kpis',
                security: vmo_ajax.nonce || vmo_ajax.security,
                period: '30d'
            }).done(function(res) {
                if (res && res.success && res.data && res.data.kpis) {
                    var kpis = res.data.kpis;

                    // Revenue
                    if ($rev && kpis.revenue) {
                        var rev = parseFloat(kpis.revenue.total_revenue || 0);
                        $rev.textContent = '$' + rev.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }

                    // Leads
                    if ($leads && kpis.marketing) {
                        $leads.textContent = (parseInt(kpis.marketing.total_leads, 10) || 0).toLocaleString();
                    }

                    // Calls
                    if ($calls && kpis.calls) {
                        $calls.textContent = (parseInt(kpis.calls.total_calls, 10) || 0).toLocaleString();
                    }

                    // Campaign / task completion rate
                    if ($camp && kpis.tasks) {
                        $camp.textContent = (parseInt(kpis.tasks.completion_rate, 10) || 0) + '%';
                    }

                    // Health Score
                    var healthEl = document.getElementById('vmo-health-score');
                    if (healthEl && kpis.overall) {
                        healthEl.textContent = (kpis.overall.health_score || 0) + '%';
                        var statusClass = kpis.overall.status === 'good' ? '#10b981' : (kpis.overall.status === 'fair' ? '#f59e0b' : '#ef4444');
                        healthEl.style.color = statusClass;
                    }

                    // Visitors
                    var visitorsEl = document.getElementById('total-visitors');
                    if (visitorsEl && kpis.marketing) {
                        visitorsEl.textContent = (parseInt(kpis.marketing.total_visitors, 10) || 0).toLocaleString();
                    }

                    // Pageviews
                    var pvEl = document.getElementById('total-pageviews');
                    if (pvEl && kpis.marketing) {
                        pvEl.textContent = (parseInt(kpis.marketing.total_pageviews, 10) || 0).toLocaleString();
                    }

                    // Bounce rate
                    var bounceEl = document.getElementById('bounce-rate');
                    if (bounceEl && kpis.marketing) {
                        bounceEl.textContent = (parseFloat(kpis.marketing.bounce_rate) || 0).toFixed(1) + '%';
                    }

                    // Customers
                    var custEl = document.getElementById('total-customers');
                    if (custEl && kpis.customers) {
                        custEl.textContent = (parseInt(kpis.customers.total_customers, 10) || 0).toLocaleString();
                    }

                    // Goals
                    var goalsEl = document.getElementById('goals-completion');
                    if (goalsEl && kpis.goals) {
                        goalsEl.textContent = (parseInt(kpis.goals.completion_rate, 10) || 0) + '%';
                    }

                    // Market Intelligence
                    var compEl = document.getElementById('active-competitors');
                    if (compEl && kpis.market) {
                        compEl.textContent = (parseInt(kpis.market.active_competitors, 10) || 0).toLocaleString();
                    }

                    console.log('[VMO Dashboard] KPIs loaded from server:', kpis);
                }
            }).fail(function() {
                console.warn('[VMO Dashboard] Failed to load KPIs; falling back to payment API');
            });
        }

        // If Payments are enabled, also use real totals from report endpoint (last 30 days)
        const paymentsEnabled = (typeof window.vmo_ajax !== 'undefined' && !!vmo_ajax.payments_enabled);
        if (paymentsEnabled && typeof window.fetch === 'function') {
            try {
                const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
                const url = apiRoot + 'vmo-builder/v1/payments/report';
                fetch(url, { credentials: 'include' })
                    .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
                    .then(({ success, data }) => {
                        if (!success || !data) return;
                        // Use last_30d cents -> dollars
                        const cents = parseInt(data.comparative?.last_30d || 0, 10);
                        if ($rev) $rev.textContent = '$' + (cents / 100).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    })
                    .catch(() => { /* keep defaults */ });

                // Load Recent Orders (read-only)
                const ordersBox = document.getElementById('vmo-recent-orders');
                if (ordersBox) {
                    fetch(apiRoot + 'vmo-builder/v1/stripe/connect/orders', { credentials: 'include' })
                        .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
                        .then(({ orders }) => {
                            const list = Array.isArray(orders) ? orders.slice(0, 5) : [];
                            if (list.length === 0) {
                                ordersBox.innerHTML = '<div style="color:#718096">No orders yet.</div>';
                                return;
                            }
                            ordersBox.innerHTML = list.map(o => {
                                const amt = (parseInt(o.amount_total||0,10)/100).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
                                const name = (function(){ try{ const m=JSON.parse(o.metadata||'{}'); return m.product_name||'Order'; }catch(_){ return 'Order'; } })();
                                const date = (function(){
                                    const s = (o.created_at||'').toString();
                                    if(!s) return '';
                                    const t = Date.parse(s.replace(' ', 'T'));
                                    return isNaN(t) ? s : new Date(t).toLocaleString();
                                })();
                                const status = (o.status||'').toUpperCase();
                                // In-page only: do not link out. Show indicator if receipt exists.
                                const rec = o.receipt_url ? '<span style="margin-left:8px;color:#4a5568">Receipt available</span>' : '';
                                return '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #edf2f7">'+
                                       '<div><strong>'+name+'</strong><div style="color:#718096;font-size:.85rem">'+date+'</div></div>'+ 
                                       '<div style="text-align:right"><div>$'+amt+'</div><div style="font-size:.8rem;color:#718096">'+status+' '+rec+'</div></div>'+
                                       '</div>';
                            }).join('');
                        })
                        .catch(()=>{ ordersBox.innerHTML = '<div style="color:#718096">Could not load orders.</div>'; });
                }

                // Load Subscriptions (read-only)
                const subsBox = document.getElementById('vmo-subscriptions');
                if (subsBox) {
                    fetch(apiRoot + 'vmo-builder/v1/store/subscriptions', { credentials: 'include' })
                        .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
                        .then(({ success, subscriptions }) => {
                            const list = Array.isArray(subscriptions) ? subscriptions.slice(0, 5) : [];
                            if (!list.length) { subsBox.innerHTML = '<div style="color:#718096">No active subscriptions.</div>'; return; }
                            subsBox.innerHTML = list.map(s => {
                                const name = s.product_name || 'Subscription';
                                const status = (s.status||'').toUpperCase();
                                const end = (function(){
                                    const x = (s.current_period_end||'').toString();
                                    if(!x) return '';
                                    const t = Date.parse(x.replace(' ', 'T'));
                                    return isNaN(t) ? x : new Date(t).toLocaleDateString();
                                })();
                                return '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #edf2f7">'+
                                       '<div><strong>'+name+'</strong><div style="color:#718096;font-size:.85rem">Renews by '+end+'</div></div>'+ 
                                       '<div style="text-align:right"><div style="font-size:.9rem;color:#4a5568">'+status+'</div></div>'+
                                       '</div>';
                            }).join('');
                        })
                        .catch(()=>{ subsBox.innerHTML = '<div style="color:#718096">Could not load subscriptions.</div>'; });
                }
            } catch (_) { /* noop */ }
        }
    }

    // Minimal loaders for sections
    function loadSEOData() {
        // Load real SEO task data if endpoint is available
        if (typeof jQuery !== 'undefined' && typeof vmo_ajax !== 'undefined') {
            jQuery.post(vmo_ajax.ajaxurl, {
                action: 'vmo_list_seo_tasks',
                security: vmo_ajax.nonce || vmo_ajax.security
            }).done(function(res) {
                if (res && res.success && res.data && res.data.tasks) {
                    var tasksContainer = document.getElementById('seo-tasks-list');
                    if (tasksContainer && res.data.tasks.length > 0) {
                        tasksContainer.innerHTML = res.data.tasks.map(function(t) {
                            var statusColor = t.status === 'completed' ? '#10b981' : (t.status === 'in_progress' ? '#f59e0b' : '#94a3b8');
                            return '<div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #edf2f7">' +
                                '<span>' + (t.title || 'SEO Task') + '</span>' +
                                '<span style="color:' + statusColor + ';font-size:.85rem;text-transform:uppercase">' + (t.status || 'pending') + '</span></div>';
                        }).join('');
                    }
                }
            });
        }
    }

    function loadLeadsData() {
        // Load real leads count from KPIs endpoint
        if (typeof jQuery !== 'undefined' && typeof vmo_ajax !== 'undefined') {
            jQuery.post(vmo_ajax.ajaxurl, {
                action: 'vmo_get_dashboard_kpis',
                security: vmo_ajax.nonce || vmo_ajax.security,
                period: '30d'
            }).done(function(res) {
                if (res && res.success && res.data && res.data.kpis) {
                    var kpis = res.data.kpis;
                    var leadsCountEl = document.getElementById('leads-total-count');
                    if (leadsCountEl && kpis.marketing) {
                        leadsCountEl.textContent = (parseInt(kpis.marketing.total_leads, 10) || 0).toLocaleString();
                    }
                    var convRateEl = document.getElementById('leads-conversion-rate');
                    if (convRateEl && kpis.marketing) {
                        convRateEl.textContent = (parseFloat(kpis.marketing.conversion_rate) || 0).toFixed(1) + '%';
                    }
                }
            });
        }
    }

    function loadCampaignsData() {
        const list = document.getElementById('campaigns-list');
        if (list) {
            // Gentle prompt if empty
            const hasItems = list.querySelector('.vmo-campaign-item');
            if (!hasItems) {
                const msg = document.createElement('p');
                msg.style.color = '#4a5568';
                msg.textContent = 'Use "Create New Campaign" to generate 4 AI-crafted email templates and send to your leads.';
                // Clear previous simple placeholder once
                const ps = list.querySelectorAll('p'); ps.forEach((p,i)=>{ if(i===0) p.remove(); });
                list.appendChild(msg);
            }
        }
    }
    
    // Load dashboard modules on initialization
    function loadDashboardModules() {
        console.log('📦 Loading Dashboard Modules...');
        loadOverviewData();
        loadRoadmapProgress();
    }
    
    // Load Business Execution Roadmap & Progress Tracking
    function loadRoadmapProgress() {
        const progressContainer = document.getElementById('vmo-progress-container');
        const todaysActivities = document.getElementById('vmo-todays-activities');
        const upcomingActivities = document.getElementById('vmo-upcoming-activities');
        
        if (!progressContainer) return;
        
        // Load progress tracking data
        if (typeof jQuery !== 'undefined') {
            const ajaxUrl = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj && vmo_ajax_obj.ajax_url)
                ? vmo_ajax_obj.ajax_url
                : ((typeof vmo_ajax !== 'undefined' && vmo_ajax && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : '/wp-admin/admin-ajax.php');
            const nonce = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj && vmo_ajax_obj.nonce)
                ? vmo_ajax_obj.nonce
                : ((typeof vmo_ajax !== 'undefined' && vmo_ajax && vmo_ajax.nonce) ? vmo_ajax.nonce : '');
            
            // Fetch progress tracking
            jQuery.post(ajaxUrl, {
                action: 'vmo_get_progress_tracking',
                security: nonce,
                nonce: nonce
            }, function(response) {
                if (response && response.success && response.data && response.data.has_roadmap && response.data.progress) {
                    window.vmoProgressData = response.data.progress;
                    updateProgressDisplay(response.data.progress);
                } else {
                    window.vmoProgressData = null;
                    showNoRoadmapState();
                }
            }).fail(function() {
                window.vmoProgressData = null;
                showNoRoadmapState();
            });
            
            // Fetch today's activities
            jQuery.post(ajaxUrl, {
                action: 'vmo_get_todays_activities',
                security: nonce,
                nonce: nonce
            }, function(response) {
                const todayList = response?.data?.today || [];
                const upcomingList = response?.data?.upcoming || [];
                const dayNum = (window.vmoProgressData && window.vmoProgressData.current_day) ? window.vmoProgressData.current_day : 1;

                if (response && response.success && Array.isArray(todayList) && todayList.length > 0) {
                    displayTodaysActivities(todayList, dayNum);
                } else {
                    displayNoActivities(todaysActivities, "No activities scheduled for today");
                }

                if (response && response.success && Array.isArray(upcomingList) && upcomingList.length > 0) {
                    displayUpcomingActivities(upcomingList);
                } else {
                    displayNoActivities(upcomingActivities, "No upcoming activities in the next 7 days");
                }
            }).fail(function() {
                displayNoActivities(todaysActivities, "Could not load activities");
                displayNoActivities(upcomingActivities, "Could not load upcoming activities");
            });
            
            // Fetch roadmap (for downloads and metadata)
            jQuery.post(ajaxUrl, {
                action: 'vmo_get_business_roadmap',
                security: nonce,
                nonce: nonce
            }, function(response) {
                if (response && response.success && response.data && response.data.has_roadmap) {
                    window.vmoActiveRoadmapId = response.data.roadmap_id || '';
                    window.vmoActiveRoadmap = response.data.roadmap || null;
                } else {
                    window.vmoActiveRoadmapId = '';
                    window.vmoActiveRoadmap = null;
                }
            }).fail(function() {
                window.vmoActiveRoadmapId = '';
                window.vmoActiveRoadmap = null;
            });
        }
    }
    
    // Update progress display with data
    function updateProgressDisplay(data) {
        const progressPercent = document.getElementById('vmo-progress-percent');
        const progressBar = document.getElementById('vmo-progress-bar');
        const healthBadge = document.getElementById('vmo-health-badge');
        const currentDay = document.getElementById('vmo-current-day');
        const activitiesDone = document.getElementById('vmo-activities-done');
        const daysStatus = document.getElementById('vmo-days-status');
        
        if (progressPercent) {
            progressPercent.textContent = Math.round(data.progress_percentage || 0) + '%';
        }
        
        if (progressBar) {
            progressBar.style.width = (data.progress_percentage || 0) + '%';
            // Color based on health
            if (data.schedule_health === 'ahead') {
                progressBar.style.background = 'linear-gradient(90deg, #4CAF50, #8BC34A)';
            } else if (data.schedule_health === 'on_track') {
                progressBar.style.background = 'linear-gradient(90deg, #2196F3, #03A9F4)';
            } else if (data.schedule_health === 'behind') {
                progressBar.style.background = 'linear-gradient(90deg, #FF9800, #FFC107)';
            } else {
                progressBar.style.background = 'linear-gradient(90deg, #f44336, #FF5722)';
            }
        }
        
        if (healthBadge) {
            const healthLabels = {
                'ahead': '🚀 Ahead of Schedule',
                'on_track': '✅ On Track',
                'behind': '⚠️ Behind Schedule',
                'critical': '🚨 Critical'
            };
            const healthColors = {
                'ahead': '#4CAF50',
                'on_track': '#2196F3',
                'behind': '#FF9800',
                'critical': '#f44336'
            };
            healthBadge.textContent = healthLabels[data.schedule_health] || '📊 Tracking';
            healthBadge.style.background = healthColors[data.schedule_health] || '#4CAF50';
        }
        
        if (currentDay) {
            currentDay.textContent = 'Day ' + (data.current_day || 1);
        }
        
        if (activitiesDone) {
            activitiesDone.textContent = (data.actual_completed || 0) + ' / ' + (data.total_activities || 0);
        }
        
        if (daysStatus) {
            const daysDiff = Number.isFinite(data.days_ahead_behind) ? data.days_ahead_behind : 0;
            if (daysDiff >= 0) {
                daysStatus.textContent = '+' + daysDiff + ' days';
                daysStatus.style.color = '#4CAF50';
            } else {
                daysStatus.textContent = String(daysDiff) + ' days';
                daysStatus.style.color = '#f44336';
            }
        }
        
        // 🎯 Update Vision Target Date and Time Remaining
        updateVisionTargetDisplay(data);
    }
    
    /**
     * 🎯 Update the Vision Target Date display with Year:Month:Day format
     * @param {Object} data - Progress data including total_days and current_day
     */
    function updateVisionTargetDisplay(data) {
        const visionDateEl = document.getElementById('vmo-vision-target-date');
        const timeRemainingEl = document.getElementById('vmo-time-remaining');
        
        if (!visionDateEl || !timeRemainingEl) return;
        
        const totalDays = data.total_days || 365;
        const currentDay = data.current_day || 1;
        const daysRemaining = Math.max(0, totalDays - currentDay);
        
        // Calculate target date from today + remaining days
        const targetDate = new Date();
        targetDate.setDate(targetDate.getDate() + daysRemaining);
        
        // Format as Year : Month : Day
        const year = targetDate.getFullYear();
        const month = String(targetDate.getMonth() + 1).padStart(2, '0');
        const day = String(targetDate.getDate()).padStart(2, '0');
        
        visionDateEl.textContent = year + ' : ' + month + ' : ' + day;
        
        // Format time remaining as Years : Months : Days
        const years = Math.floor(daysRemaining / 365);
        const months = Math.floor((daysRemaining % 365) / 30);
        const days = daysRemaining % 30;
        
        let timeRemainingText = '';
        if (years > 0) {
            timeRemainingText = years + 'Y : ' + months + 'M : ' + days + 'D';
        } else if (months > 0) {
            timeRemainingText = months + 'M : ' + days + 'D';
        } else {
            timeRemainingText = days + ' Days';
        }
        
        timeRemainingEl.textContent = timeRemainingText;
        
        // Color code based on remaining time
        if (daysRemaining <= 30) {
            timeRemainingEl.style.color = '#ff6b6b'; // Urgent - red
        } else if (daysRemaining <= 90) {
            timeRemainingEl.style.color = '#ffc107'; // Soon - amber
        } else {
            timeRemainingEl.style.color = '#4fc3f7'; // Normal - blue
        }
        
        // If vision is achieved (0 days remaining), show celebration
        if (daysRemaining === 0) {
            visionDateEl.textContent = '🎉 TODAY!';
            visionDateEl.style.color = '#4CAF50';
            timeRemainingEl.textContent = '✨ Vision Achieved!';
            timeRemainingEl.style.color = '#4CAF50';
        }
    }
    
    // Show no roadmap state
    function showNoRoadmapState() {
        const container = document.getElementById('vmo-progress-container');
        if (container) {
            container.innerHTML = `
                <div style="text-align: center; padding: 30px; color: #e6f3ff;">
                    <div style="font-size: 2rem; margin-bottom: 10px;">📋</div>
                    <h4 style="margin: 0 0 10px 0;">Business Execution Roadmap</h4>
                    <p style="opacity: 0.8; margin: 0;">Complete Phase 4 of your Business Consultation to generate your personalized execution roadmap and daily activities plan.</p>
                </div>
            `;
        }
    }
    
    // Display today's activities
    function displayTodaysActivities(activities, dayNumber) {
        const container = document.getElementById('vmo-todays-activities');
        if (!container) return;
        
        let html = '<div style="margin-bottom: 10px; font-weight: 600; color: #2d3748;">Day ' + dayNumber + ' Activities</div>';
        
        const escAttr = (s) => String(s || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        const escJsSingle = (s) => String(s || '').replace(/\\/g,'\\\\').replace(/'/g,"\\'");

        activities.forEach(function(activity) {
            const status = activity.status || 'pending';
            const statusIcon = status === 'completed' ? '✅' : (status === 'in_progress' ? '🔄' : '⏳');
            const title = activity.activity_title || activity.title || '';
            const mins = activity.estimated_duration_minutes || 60;
            const activityId = activity.activity_id || activity.id || '';
            
            html += `
                <div style="display: flex; align-items: center; gap: 12px; padding: 12px; background: white; border-radius: 8px; margin-bottom: 8px; border-left: 4px solid ${status === 'completed' ? '#38a169' : '#4299e1'};">
                    <span style="font-size: 1.2rem;">${statusIcon}</span>
                    <div style="flex: 1;">
                        <div style="font-weight: 500; color: #2d3748;">${escAttr(title)}</div>
                        <div style="font-size: 0.85rem; color: #718096;">Est: ${escAttr(mins)} min</div>
                    </div>
                    ${status !== 'completed' ? `<button onclick="VMOBusinessDashboard.completeActivity('${escJsSingle(activityId)}')" style="background: #4CAF50; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 0.85rem;">Complete</button>` : ''}
                </div>
            `;
        });
        
        container.innerHTML = html;
    }
    
    // Display upcoming activities list
    function displayUpcomingActivities(activities) {
        const container = document.getElementById('vmo-upcoming-activities');
        if (!container) return;
        const esc = (s) => String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

        const items = (Array.isArray(activities) ? activities : []).slice(0, 10);
        if (items.length === 0) {
            displayNoActivities(container, 'No upcoming activities.');
            return;
        }

        let html = '';
        items.forEach(function(a) {
            const title = a.activity_title || a.title || '';
            const date = a.activity_date || '';
            const pri = a.priority || 3;
            html += `
                <div style="display:flex; align-items:center; gap:12px; padding:12px; background:white; border-radius:8px; margin-bottom:8px;">
                    <span style="font-size:1.1rem;">📅</span>
                    <div style="flex:1;">
                        <div style="font-weight:500; color:#2d3748;">${esc(title)}</div>
                        <div style="font-size:0.85rem; color:#718096;">${esc(date)} • Priority ${esc(pri)}</div>
                    </div>
                    <span style="background:#e2e8f0; color:#4a5568; padding:4px 8px; border-radius:4px; font-size:0.8rem;">pending</span>
                </div>
            `;
        });
        container.innerHTML = html;
    }
    
    // Display no activities message
    function displayNoActivities(container, message) {
        if (container) {
            container.innerHTML = `
                <div style="color: #718096; text-align: center; padding: 20px;">
                    ${message}
                </div>
            `;
        }
    }
    
    // Complete an activity
    function completeActivity(activityId) {
        if (typeof jQuery !== 'undefined') {
            const ajaxUrl = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj && vmo_ajax_obj.ajax_url)
                ? vmo_ajax_obj.ajax_url
                : ((typeof vmo_ajax !== 'undefined' && vmo_ajax && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : '/wp-admin/admin-ajax.php');
            const nonce = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj && vmo_ajax_obj.nonce)
                ? vmo_ajax_obj.nonce
                : ((typeof vmo_ajax !== 'undefined' && vmo_ajax && vmo_ajax.nonce) ? vmo_ajax.nonce : '');

            jQuery.post(ajaxUrl, {
                action: 'vmo_complete_activity',
                security: nonce,
                nonce: nonce,
                activity_id: activityId
            }, function(response) {
                if (response.success) {
                    // Reload progress display
                    loadRoadmapProgress();
                    // Show success message
                    showToast('✅ Activity completed!', 'success');
                } else {
                    showToast('Could not complete activity', 'error');
                }
            });
        }
    }
    
    // Show toast notification
    function showToast(message, type) {
        const toast = document.createElement('div');
        toast.textContent = message;
        toast.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 24px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 10001;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            animation: slideInRight 0.3s ease;
            background: ${type === 'success' ? '#38a169' : '#e53e3e'};
        `;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
    }
    
    // Premium upgrade modal
    function showPremiumUpgradeModal() {
        const modalHTML = `
            <div id="vmo-premium-modal" class="vmo-fs-modal" style="display:flex;">
                <div class="vmo-modal-overlay" data-close="vmo-premium-modal"></div>
                <div class="modal-content vmo-modal-panel">
                    <div class="vmo-premium-content">
                        <h2>🚀 Upgrade to VMO Business Suite</h2>
                        <p>Unlock powerful business tools and AI consulting features</p>
                        
                        <div class="vmo-premium-features">
                            <div class="vmo-feature-item">✅ Business Consulting AI</div>
                            <div class="vmo-feature-item">✅ Automated SEO Management</div>
                            <div class="vmo-feature-item">✅ Lead Generation System</div>
                            <div class="vmo-feature-item">✅ Email Campaign Manager</div>
                            <div class="vmo-feature-item">✅ Business Phone System</div>
                            <div class="vmo-feature-item">✅ Legal Document Generator</div>
                            <div class="vmo-feature-item">✅ Business Plan Creator</div>
                            <div class="vmo-feature-item">✅ Task & Project Management</div>
                        </div>
                        
                        <div class="vmo-premium-pricing">
                            <div class="vmo-price-plan">
                                <h3>Business Plan</h3>
                                <p class="vmo-price">$49/month</p>
                                <button onclick="VMOBusinessDashboard.upgradePlan('business')" class="vmo-btn-primary">
                                    Upgrade Now
                                </button>
                            </div>
                        </div>
                        
                        <button class="modal-close" data-close="vmo-premium-modal" type="button">×</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        // Wire close actions (overlay click and header close button)
        const modal = document.getElementById('vmo-premium-modal');
        if (modal) {
            modal.addEventListener('click', (e)=>{
                const t = e.target;
                const closeTarget = t && (t.getAttribute && t.getAttribute('data-close'));
                if (closeTarget === 'vmo-premium-modal' || (t.classList && t.classList.contains('vmo-modal-overlay'))) {
                    VMOBusinessDashboard.closePremiumModal();
                }
            });
        }
    }
    
    // Add dashboard styles
    function addDashboardStyles() {
        const styles = `
            <style>
            .vmo-dashboard-container {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: #f8f9fa;
                z-index: 10000;
                display: flex;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }
            
            .vmo-dashboard-sidebar {
                width: 280px;
                background: #1a202c;
                color: white;
                padding: 0;
                overflow-y: auto;
            }
            
            .vmo-dashboard-logo {
                padding: 2rem 1.5rem;
                border-bottom: 1px solid #2d3748;
            }
            
            .vmo-dashboard-logo h2 {
                margin: 0 0 0.5rem 0;
                font-size: 1.3rem;
            }
            
            .vmo-dashboard-logo p {
                margin: 0;
                color: #a0aec0;
                font-size: 0.9rem;
            }
            
            .vmo-dashboard-nav {
                padding: 1rem 0;
            }
            
            .vmo-nav-item {
                display: flex;
                align-items: center;
                padding: 0.75rem 1.5rem;
                color: #a0aec0;
                text-decoration: none;
                transition: all 0.2s;
                border-left: 3px solid transparent;
            }
            
            .vmo-nav-item:hover {
                color: white;
                background: #2d3748;
            }
            
            .vmo-nav-item.active {
                color: white;
                background: #2d3748;
                border-left-color: #4299e1;
            }
            
            .vmo-nav-item i {
                margin-right: 0.75rem;
                font-size: 1.1rem;
            }
            
            .vmo-dashboard-content {
                flex: 1;
                padding: 2rem;
                overflow-y: auto;
                background: #f8f9fa;
            }
            
            .vmo-dashboard-section {
                display: none;
            }
            
            .vmo-dashboard-section.active {
                display: block;
            }
            
            .vmo-dashboard-header {
                margin-bottom: 2rem;
            }
            
            .vmo-dashboard-header h1 {
                margin: 0 0 0.5rem 0;
                color: #1a202c;
                font-size: 2rem;
            }
            
            .vmo-dashboard-header p {
                margin: 0;
                color: #718096;
                font-size: 1rem;
            }
            
            .vmo-dashboard-stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 1.5rem;
                margin-bottom: 2rem;
            }
            
            .vmo-stat-card {
                background: white;
                padding: 1.5rem;
                border-radius: 8px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                display: flex;
                align-items: center;
            }
            
            .vmo-stat-icon {
                font-size: 2.5rem;
                margin-right: 1rem;
            }
            
            .vmo-stat-info h3 {
                margin: 0 0 0.5rem 0;
                color: #718096;
                font-size: 0.9rem;
                font-weight: 500;
            }
            
            .vmo-stat-value {
                margin: 0 0 0.25rem 0;
                font-size: 1.8rem;
                font-weight: 600;
                color: #1a202c;
            }
            
            .vmo-stat-change {
                margin: 0;
                font-size: 0.8rem;
            }
            
            .vmo-stat-change.positive { color: #38a169; }
            .vmo-stat-change.negative { color: #e53e3e; }
            .vmo-stat-change.neutral { color: #718096; }
            
            .vmo-quick-actions-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 1rem;
                margin-top: 1rem;
            }
            
            .vmo-quick-action {
                background: white;
                border: 1px solid #e2e8f0;
                padding: 1rem;
                border-radius: 8px;
                text-align: center;
                cursor: pointer;
                transition: all 0.2s;
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 0.5rem;
            }
            
            .vmo-quick-action:hover {
                border-color: #4299e1;
                transform: translateY(-2px);
            }
            
            .vmo-quick-action i {
                font-size: 1.5rem;
            }
            
            .vmo-btn-primary {
                background: #4299e1;
                color: white;
                border: none;
                padding: 0.75rem 1.5rem;
                border-radius: 6px;
                cursor: pointer;
                font-weight: 500;
                transition: all 0.2s;
            }
            
            .vmo-btn-primary:hover {
                background: #3182ce;
            }
            
            .vmo-btn-secondary {
                background: white;
                color: #4299e1;
                border: 1px solid #4299e1;
                padding: 0.75rem 1.5rem;
                border-radius: 6px;
                cursor: pointer;
                font-weight: 500;
                transition: all 0.2s;
            }
            
            .vmo-btn-secondary:hover {
                background: #4299e1;
                color: white;
            }
            
            .vmo-premium-modal .vmo-modal-content {
                max-width: 500px;
                background: white;
                border-radius: 12px;
                padding: 2rem;
                text-align: center;
                position: relative;
            }
            
            .vmo-premium-features {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 0.5rem;
                margin: 1.5rem 0;
            }
            
            .vmo-feature-item {
                text-align: left;
                color: #38a169;
                font-weight: 500;
            }
            
            .vmo-close-modal {
                position: absolute;
                top: 1rem;
                right: 1rem;
                background: none;
                border: none;
                font-size: 1.5rem;
                cursor: pointer;
                color: #718096;
            }
            
            .vmo-form-row {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 1rem;
                margin-bottom: 1rem;
            }
            
            .vmo-form-group {
                display: flex;
                flex-direction: column;
            }
            
            .vmo-form-group label {
                margin-bottom: 0.5rem;
                font-weight: 500;
                color: #4a5568;
            }
            
            .vmo-form-group input,
            .vmo-form-group select,
            .vmo-form-group textarea {
                padding: 0.75rem;
                border: 1px solid #e2e8f0;
                border-radius: 6px;
                font-size: 1rem;
            }
            
            .vmo-form-group textarea {
                resize: vertical;
                min-height: 100px;
            }
            
            @media (max-width: 768px) {
                .vmo-dashboard-container {
                    flex-direction: column;
                }
                
                .vmo-dashboard-sidebar {
                    width: 100%;
                    height: auto;
                }
                
                .vmo-dashboard-stats {
                    grid-template-columns: 1fr;
                }
                
                .vmo-form-row {
                    grid-template-columns: 1fr;
                }
            }
            </style>
        `;
        
        document.head.insertAdjacentHTML('beforeend', styles);
    }
    
    // Public API methods
    // Email Marketing: create campaign modal workflow using existing AJAX endpoints
    function openEmailCampaignModal(){
        const id = '__vmoEmailCampaign';
        let m = document.getElementById(id);
        if (!m) {
            m = document.createElement('div');
            m.id = id;
            m.style.position='fixed'; m.style.inset='0'; m.style.display='none'; m.style.alignItems='center'; m.style.justifyContent='center'; m.style.zIndex='100000';
            m.innerHTML = '<div class="vmo-modal-overlay" data-close="'+id+'" style="position:absolute;inset:0;background:rgba(0,0,0,.65);z-index:1"></div>'+
            '<div class="vmo-modal-panel" style="position:relative;width:min(980px,96vw);max-height:88vh;overflow:auto;background:#0b1117;border:1px solid rgba(255,255,255,.12);border-radius:14px;box-shadow:0 10px 36px rgba(0,0,0,.6);z-index:10">'+
              '<div style="display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid rgba(255,255,255,.08)">'+
                '<h3 style="margin:0;color:#e6f3ff;font-size:18px">✉️ Create Email Campaign</h3>'+
                '<div style="margin-left:auto;color:#9fb2c8;font-size:13px">AI will propose 4 templates</div>'+
                '<button type="button" data-close="'+id+'" style="margin-left:12px;background:none;border:1px solid rgba(255,255,255,.18);color:#9fb2c8;padding:3px 8px;border-radius:8px;cursor:pointer">Close</button>'+
              '</div>'+
              '<div class="vmo-modal-body" style="padding:14px 16px;color:#cfe7ff;line-height:1.55">'+
                '<div style="display:flex;gap:10px;align-items:center;margin-bottom:10px">'+
                  '<label style="color:#9fb2c8">Leads to generate:</label>'+
                  '<input id="vmo-email-lead-count" type="number" min="10" max="50" value="25" style="width:90px;background:#0f1722;border:1px solid rgba(255,255,255,.14);color:#e6f3ff;border-radius:8px;padding:6px 8px">'+
                  '<button id="vmo-email-generate" class="vmo-btn-primary" style="margin-left:auto">Generate Options</button>'+
                '</div>'+
                '<div id="vmo-email-status" style="color:#9fb2c8">Ready.</div>'+
                '<div id="vmo-email-options" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px;margin-top:12px"></div>'+
                '<div id="vmo-email-actions" style="display:none;margin-top:12px;display:flex;gap:10px;align-items:center">'+
                  '<button id="vmo-email-send" class="vmo-btn-primary">Approve & Send</button>'+
                  '<div id="vmo-email-send-status" style="color:#9fb2c8"></div>'+
                '</div>'+
              '</div>'+
            '</div>';
            document.body.appendChild(m);
            document.addEventListener('click', function(e){ const t=e.target; if (t && (t.getAttribute('data-close')===id || t.classList.contains('vmo-modal-overlay'))) { m.style.display='none'; } });
        }
        m.style.display='flex';

        const $status = m.querySelector('#vmo-email-status');
        const $options = m.querySelector('#vmo-email-options');
        const $sendBar = m.querySelector('#vmo-email-actions');
        const $sendBtn = m.querySelector('#vmo-email-send');
        let currentCampaignId = null; let selectedIndex = null;

        function renderOptions(opts) {
            $options.innerHTML = '';
            opts.forEach((opt, i) => {
                const card = document.createElement('div');
                card.style.border='1px solid rgba(255,255,255,.14)'; card.style.borderRadius='10px'; card.style.overflow='hidden'; card.style.background='#0f1722';
                card.innerHTML = '<div style="padding:10px;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;gap:8px">'+
                    '<input type="radio" name="vmoEmailOpt" value="'+i+'" style="accent-color:#4299e1">'+
                    '<div><div style="color:#e6f3ff;font-weight:600">'+(opt.subject||'')+'</div><div style="color:#9fb2c8;font-size:12px">'+(opt.preheader||'')+'</div></div></div>'+
                    '<div style="padding:10px;background:#0b1117;max-height:220px;overflow:auto">'+ (opt.html||'<em>No preview</em>') +'</div>';
                $options.appendChild(card);
            });
            $options.addEventListener('change', function(e){ if (e.target && e.target.name==='vmoEmailOpt') { selectedIndex = parseInt(e.target.value, 10); $sendBar.style.display='flex'; } });
        }

        const ajaxUrl = (window.vmo_ajax && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : (window.ajaxurl || '/wp-admin/admin-ajax.php');
        const sec = (window.vmo_ajax && vmo_ajax.nonce) ? vmo_ajax.nonce : (window.VMO_NONCE || '');

        m.querySelector('#vmo-email-generate').onclick = function(){
            const leadCount = Math.max(10, Math.min(50, parseInt(m.querySelector('#vmo-email-lead-count').value || '25', 10)));
            $status.textContent = 'Generating campaign options…';
            $options.innerHTML = '';
            $sendBar.style.display='none';
            selectedIndex = null; currentCampaignId = null;
            jQuery.post(ajaxUrl, {
                action: 'vmo_email_generate_campaign',
                security: sec,
                lead_count: leadCount
            }, function(resp){
                if (resp && resp.success) {
                    currentCampaignId = resp.data.campaign_id;
                    renderOptions(resp.data.options || []);
                    $status.textContent = (resp.data.leads?.length || 0) + ' leads proposed • Select an option to send';
                } else {
                    $status.textContent = (resp && resp.data && resp.data.message) ? resp.data.message : 'Generation failed';
                }
            }).fail(function(){ $status.textContent = 'Network error'; });
        };

        $sendBtn.onclick = function(){
            if (selectedIndex == null || currentCampaignId == null) return;
            const $sendStatus = m.querySelector('#vmo-email-send-status');
            $sendStatus.textContent = 'Sending…';
            jQuery.post(ajaxUrl, {
                action: 'vmo_email_send_campaign',
                security: sec,
                campaign_id: currentCampaignId,
                selected_index: selectedIndex
            }, function(resp){
                if (resp && resp.success) {
                    const sent = resp.data.sent || 0; const failed = resp.data.failed || 0;
                    $sendStatus.textContent = 'Sent: '+sent+' • Failed: '+failed;
                } else {
                    $sendStatus.textContent = (resp && resp.data && resp.data.message) ? resp.data.message : 'Send failed';
                }
            }).fail(function(){ $sendStatus.textContent = 'Network error'; });
        };
    }

    // --- AFFILIATE HELPERS ---
    function renderAffiliateRegistration(container) {
        container.innerHTML = `
            <div class="vmo-dashboard-header">
                <h1>Affiliate Partnership Program</h1>
                <p>Partner with VMO and earn recurring revenue.</p>
            </div>
            
            <div class="vmo-glass-panel" style="text-align:center; padding:60px 20px; max-width:800px; margin:0 auto;">
                <div style="font-size:60px; margin-bottom:20px;">🤝</div>
                <h2 style="color:#fff; font-size:32px; margin-bottom:15px;">Become a VMO Partner</h2>
                <p style="font-size:18px; color:rgba(255,255,255,0.7); line-height:1.6; max-width:600px; margin:0 auto 40px auto;">
                    Join the VMO ecosystem. Get a unique referral link and earn 25% recurring commission on every business you help launch with VMO.
                </p>
                
                <div style="display:grid; grid-template-columns:repeat(3, 1fr); gap:20px; margin-bottom:40px; text-align:left;">
                    <div class="vmo-feature-card" style="background:rgba(255,255,255,0.05); padding:20px; border-radius:12px;">
                        <h4 style="color:var(--cyan);">🚀 Viral Growth</h4>
                        <p>Share your link. When they install VMO, you get credit forever.</p>
                    </div>
                    <div class="vmo-feature-card" style="background:rgba(255,255,255,0.05); padding:20px; border-radius:12px;">
                        <h4 style="color:#10b981;">💰 Recurring Income</h4>
                        <p>Earn monthly as long as they subscribe. No caps.</p>
                    </div>
                    <div class="vmo-feature-card" style="background:rgba(255,255,255,0.05); padding:20px; border-radius:12px;">
                        <h4 style="color:#a855f7;">📊 Real-time Stats</h4>
                        <p>Track clicks, installs, and revenue instantly in this dashboard.</p>
                    </div>
                </div>

                <button class="vmo-btn-primary large-btn" onclick="VMOBusinessDashboard.registerAffiliate()">
                    Activate Affiliate Account
                </button>
                <p style="font-size:12px; margin-top:15px; opacity:0.5;">By activating, you agree to the VMO Partner Terms.</p>
            </div>
        `;
    }

    function renderAffiliateDashboard(container, data) {
         container.innerHTML = `
            <div class="vmo-dashboard-header">
                <div style="display:flex; justify-content:space-between; align-items:flex-end;">
                    <div>
                        <h1>Partner Dashboard</h1>
                        <p>Status: <span style="color:#10b981;">● Active</span> | ID: <code style="background:rgba(255,255,255,0.1); padding:2px 6px; border-radius:4px;">${data.code}</code></p>
                    </div>
                    <div style="text-align:right;">
                         <small style="opacity:0.6; display:block; margin-bottom:5px;">Unpaid Balance</small>
                         <h2 style="margin:0; color:#10b981;">$${(data.stats.earnings || 0).toFixed(2)}</h2>
                    </div>
                </div>
            </div>

            <!-- Stats Row -->
            <div class="vmo-phone-stats" style="display:grid; grid-template-columns: repeat(4, 1fr); gap:15px; margin-bottom:30px;">
                <div class="vmo-stat-card vmo-glass-panel">
                    <small>Total Referrals</small>
                    <h2>${data.stats.referrals || 0}</h2>
                </div>
                <div class="vmo-stat-card vmo-glass-panel">
                    <small>Active Subs</small>
                    <h2>${data.stats.active_subs || 0}</h2>
                </div>
                <div class="vmo-stat-card vmo-glass-panel">
                    <small>Conversion Rate</small>
                    <h2>${data.stats.conversion_rate || 0}%</h2>
                </div>
                <div class="vmo-stat-card vmo-glass-panel" style="background:linear-gradient(135deg, rgba(16,185,129,0.1), transparent); border-color:rgba(16,185,129,0.3);">
                    <small>Total Earned</small>
                    <h2 style="color:#10b981;">$${(data.stats.total_paid || 0).toFixed(2)}</h2>
                </div>
            </div>

            <div style="display:grid; grid-template-columns: 2fr 1fr; gap:20px;">
                
                <!-- Main Column: Link & Tools -->
                <div>
                     <div class="vmo-glass-panel" style="margin-bottom:20px;">
                        <h3>🔗 Your Smart Link</h3>
                        <p style="margin-bottom:15px; opacity:0.7;">Share this link to automatically attribute new installations to your account.</p>
                        
                        <div style="display:flex; gap:10px; background:rgba(0,0,0,0.3); padding:5px; border-radius:8px; border:1px solid rgba(255,255,255,0.1);">
                            <input type="text" value="${data.link}" readonly id="vmo-affiliate-link-input" style="flex:1; background:transparent; border:none; color:#fff; font-family:monospace; padding:10px;">
                            <button class="vmo-btn-primary" onclick="VMOBusinessDashboard.copyAffiliateLink()">Copy Link</button>
                        </div>
                        
                        <div style="margin-top:20px; display:flex; gap:10px;">
                             <a href="https://twitter.com/intent/tweet?text=Check+out+VMO!&url=${encodeURIComponent(data.link)}" target="_blank" class="vmo-btn-secondary small-btn">Twitter</a>
                             <a href="https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(data.link)}" target="_blank" class="vmo-btn-secondary small-btn">LinkedIn</a>
                             <a href="mailto:?subject=Transformation Tool&body=Check this out: ${encodeURIComponent(data.link)}" class="vmo-btn-secondary small-btn">Email</a>
                        </div>
                    </div>
                    
                    <div class="vmo-glass-panel">
                        <h3>Recent Referrals</h3>
                        ${renderReferralsList(data.referrals)}
                    </div>
                </div>

                <!-- Side Column: Payouts -->
                <div>
                    <div class="vmo-glass-panel">
                        <h3>Payout Details</h3>
                        <p style="font-size:13px; opacity:0.7; margin-bottom:15px;">Payouts are processed automatically via Stripe Connect on the 1st of every month.</p>
                        <button class="vmo-btn-secondary" style="width:100%;">Configure Payouts</button>
                    </div>
                     <div class="vmo-glass-panel" style="margin-top:20px; background:linear-gradient(180deg, rgba(88,28,135,0.2), transparent);">
                        <h3>🏆 Rank: Partner</h3>
                        <div style="display:flex; align-items:center; gap:10px; margin-top:10px;">
                             <div style="flex:1; height:6px; background:rgba(255,255,255,0.1); border-radius:3px; overflow:hidden;">
                                <div style="width:25%; height:100%; background:#a855f7;"></div>
                             </div>
                             <span style="font-size:12px;">25%</span>
                        </div>
                        <p style="font-size:12px; opacity:0.6; margin-top:5px;">Reach 100 sales to unlock 'Elite' status (40% comms).</p>
                    </div>
                </div>
            </div>
         `;
    }

    function renderReferralsList(list) {
        if(!list || list.length === 0) {
            return `<div style="padding:40px; text-align:center; opacity:0.5;">No referrals yet. Share your link to start growing!</div>`;
        }
        
        return `
            <table class="vmo-table" style="width:100%; border-collapse:collapse; margin-top:10px;">
                <thead>
                    <tr style="text-align:left; border-bottom:1px solid rgba(255,255,255,0.1);">
                        <th style="padding:10px; opacity:0.6; font-weight:normal;">User</th>
                        <th style="padding:10px; opacity:0.6; font-weight:normal;">Date</th>
                        <th style="padding:10px; opacity:0.6; font-weight:normal;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    ${list.map(ref => `
                        <tr style="border-bottom:1px solid rgba(255,255,255,0.05);">
                            <td style="padding:10px;">${ref.referred_email.replace(/(.{3})(.*)(@.*)/, "$1***$3")}</td>
                            <td style="padding:10px; opacity:0.7;">${new Date(ref.registered_at).toLocaleDateString()}</td>
                            <td style="padding:10px;"><span style="color:#10b981; font-size:12px;">● Signed Up</span></td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    }

    /* ══════════════════════════════════════════════════════
       TODAY'S TASKS HUB — Full-screen modal with:
       • Task checklist with completion
       • Overdue tasks carry-forward
       • Real-time progress ring
       • End-of-Day Report submission
       • Vision velocity projection
       • Historical report viewer
       ══════════════════════════════════════════════════════ */

    var _todaysTasksData = null; // cache for current load

    function openTodaysTasks() {
        var modalId = 'vmo-todays-tasks-modal';
        var existing = document.getElementById(modalId);
        if (existing) existing.remove();

        var modal = document.createElement('div');
        modal.id = modalId;
        modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);z-index:100000;display:flex;justify-content:center;align-items:flex-start;padding:30px;overflow-y:auto;font-family:Inter,system-ui,sans-serif;';
        modal.innerHTML = '<div style="background:#0f172a;border:1px solid rgba(99,102,241,0.3);border-radius:16px;width:900px;max-width:95%;max-height:90vh;overflow-y:auto;color:#e2e8f0;box-shadow:0 0 40px rgba(99,102,241,0.15);" id="vmo-tt-panel">' +
            '<div style="padding:25px 30px;border-bottom:1px solid rgba(255,255,255,0.08);display:flex;justify-content:space-between;align-items:center;">' +
                '<div><h2 style="margin:0;color:#fff;font-size:1.5rem;">📋 Today\'s Tasks Hub</h2><p style="margin:4px 0 0;color:#94a3b8;font-size:0.9rem;" id="vmo-tt-date">Loading...</p></div>' +
                '<button onclick="document.getElementById(\'' + modalId + '\').remove()" style="background:none;border:none;color:#94a3b8;font-size:1.8rem;cursor:pointer;line-height:1;">&times;</button>' +
            '</div>' +
            '<div style="display:flex;border-bottom:1px solid rgba(255,255,255,0.08);">' +
                '<button class="vmo-tt-tab active" data-tab="tasks" onclick="vmoSwitchTTTab(\'tasks\',this)" style="flex:1;padding:12px;background:rgba(99,102,241,0.15);color:#a5b4fc;border:none;cursor:pointer;font-weight:600;font-size:0.9rem;border-bottom:2px solid #6366f1;">📋 Tasks</button>' +
                '<button class="vmo-tt-tab" data-tab="report" onclick="vmoSwitchTTTab(\'report\',this)" style="flex:1;padding:12px;background:transparent;color:#94a3b8;border:none;cursor:pointer;font-weight:600;font-size:0.9rem;border-bottom:2px solid transparent;">📊 End-of-Day Report</button>' +
                '<button class="vmo-tt-tab" data-tab="history" onclick="vmoSwitchTTTab(\'history\',this)" style="flex:1;padding:12px;background:transparent;color:#94a3b8;border:none;cursor:pointer;font-weight:600;font-size:0.9rem;border-bottom:2px solid transparent;">📈 Report History</button>' +
            '</div>' +
            '<div id="vmo-tt-content" style="padding:25px 30px;">' +
                '<div style="text-align:center;padding:40px;color:#94a3b8;">Loading your tasks...</div>' +
            '</div>' +
        '</div>';
        document.body.appendChild(modal);

        // Close on backdrop click
        modal.addEventListener('click', function(e) { if (e.target === modal) modal.remove(); });

        // Tab switching
        window.vmoSwitchTTTab = function(tab, el) {
            modal.querySelectorAll('.vmo-tt-tab').forEach(function(t) {
                t.style.background = 'transparent';
                t.style.color = '#94a3b8';
                t.style.borderBottom = '2px solid transparent';
                t.classList.remove('active');
            });
            el.style.background = 'rgba(99,102,241,0.15)';
            el.style.color = '#a5b4fc';
            el.style.borderBottom = '2px solid #6366f1';
            el.classList.add('active');

            if (tab === 'tasks') renderTasksTab();
            else if (tab === 'report') renderReportTab();
            else if (tab === 'history') renderHistoryTab();
        };

        // Load data
        loadTodaysTasksData();
    }

    function getAjaxConfig() {
        var ajaxUrl = (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : '/wp-admin/admin-ajax.php';
        var nonce = (typeof vmo_ajax !== 'undefined' && vmo_ajax.nonce) ? vmo_ajax.nonce : '';
        return { url: ajaxUrl, nonce: nonce };
    }

    function loadTodaysTasksData() {
        var cfg = getAjaxConfig();
        jQuery.post(cfg.url, {
            action: 'vmo_get_todays_tasks_full',
            security: cfg.nonce
        }).done(function(res) {
            if (res && res.success && res.data) {
                _todaysTasksData = res.data;
                var dateEl = document.getElementById('vmo-tt-date');
                if (dateEl) {
                    var d = res.data.date || '';
                    dateEl.textContent = 'Day ' + (res.data.current_day || '?') + ' of ' + (res.data.total_days || '?') + ' — ' + d;
                }
                renderTasksTab();
            } else {
                var cnt = document.getElementById('vmo-tt-content');
                if (cnt) cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#f87171;">' + (res.data && res.data.message ? res.data.message : 'Could not load tasks.') + '</div>';
            }
        }).fail(function() {
            var cnt = document.getElementById('vmo-tt-content');
            if (cnt) cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#f87171;">Network error loading tasks.</div>';
        });
    }

    function esc(s) { return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

    function renderTasksTab() {
        var cnt = document.getElementById('vmo-tt-content');
        if (!cnt || !_todaysTasksData) return;
        var data = _todaysTasksData;
        var stats = data.stats || {};
        var vel = data.velocity || {};
        var tasks = data.tasks || [];
        var overdue = data.overdue || [];
        var pct = stats.total_planned > 0 ? Math.round((stats.completed / stats.total_planned) * 100) : 0;

        // Progress ring SVG
        var ringRadius = 40;
        var ringCirc = 2 * Math.PI * ringRadius;
        var ringOffset = ringCirc - (pct / 100) * ringCirc;
        var ringColor = pct >= 100 ? '#22c55e' : (pct >= 60 ? '#eab308' : '#ef4444');

        var html = '';

        // ─── Stats Bar ───
        html += '<div style="display:grid;grid-template-columns:auto 1fr 1fr 1fr;gap:20px;align-items:center;margin-bottom:25px;">';
        html += '<div style="text-align:center;">';
        html += '<svg width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="' + ringRadius + '" fill="none" stroke="#1e293b" stroke-width="8"/>';
        html += '<circle cx="50" cy="50" r="' + ringRadius + '" fill="none" stroke="' + ringColor + '" stroke-width="8" stroke-linecap="round" stroke-dasharray="' + ringCirc + '" stroke-dashoffset="' + ringOffset + '" transform="rotate(-90 50 50)" style="transition:stroke-dashoffset 0.5s ease"/>';
        html += '<text x="50" y="54" text-anchor="middle" fill="#fff" font-size="18" font-weight="bold">' + pct + '%</text></svg>';
        html += '</div>';
        html += '<div style="text-align:center;"><div style="font-size:2rem;font-weight:700;color:#fff;">' + stats.completed + ' / ' + stats.total_planned + '</div><div style="color:#94a3b8;font-size:0.85rem;">Completed Today</div></div>';
        html += '<div style="text-align:center;"><div style="font-size:2rem;font-weight:700;color:' + (vel.streak > 0 ? '#22c55e' : '#94a3b8') + ';">🔥 ' + (vel.streak || 0) + '</div><div style="color:#94a3b8;font-size:0.85rem;">Day Streak</div></div>';
        html += '<div style="text-align:center;"><div style="font-size:2rem;font-weight:700;color:' + (vel.cumulative_adj <= 0 ? '#22c55e' : '#ef4444') + ';">' + (vel.cumulative_adj <= 0 ? vel.cumulative_adj : '+' + vel.cumulative_adj) + '</div><div style="color:#94a3b8;font-size:0.85rem;">Days Adjusted</div></div>';
        html += '</div>';

        // ─── Vision Impact Banner ───
        if (data.vision_target) {
            var adj = vel.cumulative_adj || 0;
            var bannerColor = adj <= 0 ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)';
            var bannerBorder = adj <= 0 ? '#22c55e' : '#ef4444';
            var bannerText = adj === 0 ? 'Your business vision is on track for ' + data.vision_target :
                (adj < 0 ? 'You\'re ' + Math.abs(adj) + ' day(s) ahead! Vision now achievable by ' + data.vision_target :
                 'You\'re ' + adj + ' day(s) behind schedule. Vision date shifted to ' + data.vision_target);
            html += '<div style="background:' + bannerColor + ';border:1px solid ' + bannerBorder + ';border-radius:10px;padding:14px 18px;margin-bottom:20px;display:flex;align-items:center;gap:10px;">';
            html += '<span style="font-size:1.3rem;">' + (adj <= 0 ? '🚀' : '⚠️') + '</span>';
            html += '<span style="color:#e2e8f0;font-size:0.9rem;">' + esc(bannerText) + '</span>';
            html += '</div>';
        }

        // ─── Overdue Tasks ───
        if (overdue.length > 0) {
            html += '<div style="margin-bottom:20px;"><h4 style="color:#f87171;margin:0 0 10px;">⏰ Overdue (' + overdue.length + ')</h4>';
            overdue.forEach(function(t) {
                html += renderTaskCard(t, true);
            });
            html += '</div>';
        }

        // ─── Today's Tasks ───
        html += '<h4 style="color:#e2e8f0;margin:0 0 12px;">Today\'s Tasks (' + tasks.length + ')</h4>';
        if (tasks.length === 0) {
            html += '<div style="text-align:center;padding:30px;color:#94a3b8;">No tasks scheduled for today. 🎉</div>';
        } else {
            tasks.forEach(function(t) {
                html += renderTaskCard(t, false);
            });
        }

        // ─── Time Estimate ───
        if (stats.total_est_minutes > 0) {
            var remainMins = stats.total_est_minutes - stats.done_est_minutes;
            var hrs = Math.floor(remainMins / 60);
            var mins = remainMins % 60;
            html += '<div style="text-align:center;margin-top:15px;padding:12px;background:rgba(99,102,241,0.1);border-radius:8px;color:#a5b4fc;font-size:0.9rem;">';
            html += '⏱️ Estimated time remaining: <strong>' + (hrs > 0 ? hrs + 'h ' : '') + mins + 'm</strong> of ' + Math.round(stats.total_est_minutes / 60 * 10) / 10 + 'h total';
            html += '</div>';
        }

        cnt.innerHTML = html;
    }

    function renderTaskCard(task, isOverdue) {
        var status = task.status || 'pending';
        var isComplete = status === 'completed';
        var priorityColors = { 1:'#ef4444', 2:'#f59e0b', 3:'#3b82f6', 4:'#8b5cf6', 5:'#94a3b8' };
        var priColor = priorityColors[task.priority] || '#3b82f6';
        var priLabel = ['','Critical','High','Normal','Low','Optional'][task.priority] || 'Normal';
        var actId = esc(task.activity_id || '');
        var mins = task.estimated_duration_minutes || 60;
        var typeIcon = { task:'📝', ai_executed:'🤖', user_approval:'✋', user_action:'👤', milestone_check:'🏁' };
        var icon = typeIcon[task.activity_type] || '📝';

        var bgColor = isComplete ? 'rgba(34,197,94,0.08)' : (isOverdue ? 'rgba(239,68,68,0.08)' : 'rgba(255,255,255,0.03)');
        var borderColor = isComplete ? '#22c55e' : (isOverdue ? '#ef4444' : priColor);

        var html = '<div style="background:' + bgColor + ';border:1px solid ' + borderColor + '33;border-left:4px solid ' + borderColor + ';border-radius:10px;padding:14px 18px;margin-bottom:10px;display:flex;align-items:center;gap:14px;">';
        html += '<span style="font-size:1.4rem;">' + (isComplete ? '✅' : icon) + '</span>';
        html += '<div style="flex:1;">';
        html += '<div style="font-weight:600;color:' + (isComplete ? '#86efac' : '#e2e8f0') + ';' + (isComplete ? 'text-decoration:line-through;opacity:0.7;' : '') + '">' + esc(task.activity_title) + '</div>';
        if (task.activity_description) {
            html += '<div style="font-size:0.82rem;color:#94a3b8;margin-top:3px;">' + esc(task.activity_description).substring(0, 120) + '</div>';
        }
        html += '<div style="display:flex;gap:10px;margin-top:5px;flex-wrap:wrap;">';
        html += '<span style="font-size:0.75rem;padding:2px 8px;border-radius:4px;background:' + priColor + '22;color:' + priColor + ';">' + priLabel + '</span>';
        html += '<span style="font-size:0.75rem;color:#64748b;">⏱ ' + mins + ' min</span>';
        if (isOverdue && task.activity_date) {
            html += '<span style="font-size:0.75rem;color:#f87171;">Due: ' + esc(task.activity_date) + '</span>';
        }
        html += '</div></div>';

        if (!isComplete) {
            html += '<button onclick="VMOBusinessDashboard.completeTaskFromHub(\'' + actId + '\')" style="background:#22c55e;color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-weight:600;font-size:0.85rem;white-space:nowrap;">✓ Done</button>';
        }
        if (isComplete && task.completion_notes) {
            html += '<span style="font-size:0.8rem;color:#86efac;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + esc(task.completion_notes) + '">📝 ' + esc(task.completion_notes) + '</span>';
        }
        html += '</div>';
        return html;
    }

    function completeTaskFromHub(activityId) {
        var cfg = getAjaxConfig();
        var btn = event && event.target;
        if (btn) { btn.textContent = '...'; btn.disabled = true; }

        jQuery.post(cfg.url, {
            action: 'vmo_complete_activity',
            security: cfg.nonce,
            nonce: cfg.nonce,
            activity_id: activityId
        }).done(function(res) {
            if (res && res.success) {
                // Reload data to refresh stats + re-render
                loadTodaysTasksData();
                // Also refresh the main dashboard behind the modal
                loadRoadmapProgress();
            } else {
                if (btn) { btn.textContent = '✓ Done'; btn.disabled = false; }
                showToast('Could not complete task', 'error');
            }
        }).fail(function() {
            if (btn) { btn.textContent = '✓ Done'; btn.disabled = false; }
            showToast('Network error', 'error');
        });
    }

    /* ── End-of-Day Report Tab ── */
    function renderReportTab() {
        var cnt = document.getElementById('vmo-tt-content');
        if (!cnt || !_todaysTasksData) return;
        var data = _todaysTasksData;
        var stats = data.stats || {};
        var vel = data.velocity || {};
        var pct = stats.total_planned > 0 ? Math.round((stats.completed / stats.total_planned) * 100) : 0;
        var alreadySubmitted = data.report_submitted;

        var html = '';

        // Report Summary Card
        html += '<div style="background:linear-gradient(135deg,#1e293b,#0f172a);border:1px solid rgba(255,255,255,0.1);border-radius:14px;padding:25px;margin-bottom:25px;">';
        html += '<h3 style="margin:0 0 15px;color:#fff;">📊 Day ' + (data.current_day || '?') + ' Summary</h3>';
        html += '<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:15px;margin-bottom:20px;">';

        // Planned
        html += '<div style="text-align:center;padding:15px;background:rgba(99,102,241,0.1);border-radius:10px;">';
        html += '<div style="font-size:1.8rem;font-weight:700;color:#a5b4fc;">' + stats.total_planned + '</div>';
        html += '<div style="font-size:0.8rem;color:#94a3b8;">Planned</div></div>';

        // Completed
        html += '<div style="text-align:center;padding:15px;background:rgba(34,197,94,0.1);border-radius:10px;">';
        html += '<div style="font-size:1.8rem;font-weight:700;color:#86efac;">' + stats.completed + '</div>';
        html += '<div style="font-size:0.8rem;color:#94a3b8;">Completed</div></div>';

        // Score
        var scoreColor = pct >= 100 ? '#22c55e' : (pct >= 70 ? '#eab308' : '#ef4444');
        html += '<div style="text-align:center;padding:15px;background:rgba(255,255,255,0.05);border-radius:10px;">';
        html += '<div style="font-size:1.8rem;font-weight:700;color:' + scoreColor + ';">' + pct + '%</div>';
        html += '<div style="font-size:0.8rem;color:#94a3b8;">Day Score</div></div>';

        // Vision Impact
        var impactDays = 0;
        if (stats.total_planned > 0) {
            impactDays = stats.completed >= stats.total_planned ? Math.max(-1, -(stats.completed - stats.total_planned)) : Math.max(1, stats.total_planned - stats.completed);
        }
        var impactColor = impactDays <= 0 ? '#22c55e' : '#ef4444';
        var impactLabel = impactDays === 0 ? 'On Track' : (impactDays < 0 ? Math.abs(impactDays) + 'd faster' : '+' + impactDays + 'd slower');
        html += '<div style="text-align:center;padding:15px;background:' + (impactDays <= 0 ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)') + ';border-radius:10px;">';
        html += '<div style="font-size:1.8rem;font-weight:700;color:' + impactColor + ';">' + (impactDays <= 0 ? '🚀' : '⚠️') + '</div>';
        html += '<div style="font-size:0.8rem;color:#94a3b8;">' + impactLabel + '</div></div>';

        html += '</div>'; // grid

        // Velocity explanation
        html += '<div style="padding:12px 15px;background:rgba(255,255,255,0.03);border-radius:8px;margin-bottom:15px;">';
        html += '<p style="margin:0;color:#cbd5e1;font-size:0.88rem;line-height:1.5;">';
        if (pct >= 100) {
            html += '🎉 <strong>Excellent!</strong> You completed all today\'s tasks' + (vel.streak > 1 ? ' (' + vel.streak + '-day streak!)' : '') + '. ';
            html += 'Completing extra tasks accelerates your vision timeline.';
        } else if (pct >= 70) {
            html += '👍 <strong>Good progress</strong> — ' + stats.completed + ' of ' + stats.total_planned + ' tasks done. ';
            html += 'Try to complete the remaining ' + (stats.total_planned - stats.completed) + ' to stay on track.';
        } else if (pct >= 40) {
            html += '⚡ <strong>Moderate day</strong> — ' + stats.completed + ' of ' + stats.total_planned + ' tasks done. ';
            html += 'Uncompleted tasks push your vision date further out. Consider prioritizing critical items.';
        } else {
            html += '⚠️ <strong>Low completion</strong> — only ' + stats.completed + ' of ' + stats.total_planned + ' tasks done. ';
            html += 'This significantly impacts your timeline. Use tomorrow to catch up on overdue items.';
        }
        html += '</p></div>';

        html += '</div>'; // card

        // Submit Form
        if (alreadySubmitted) {
            html += '<div style="text-align:center;padding:25px;background:rgba(34,197,94,0.08);border:1px solid rgba(34,197,94,0.3);border-radius:12px;">';
            html += '<span style="font-size:2rem;">✅</span>';
            html += '<h4 style="color:#86efac;margin:10px 0 5px;">Today\'s Report Already Submitted</h4>';
            html += '<p style="color:#94a3b8;margin:0;">Score: ' + (data.report_score || pct) + '% • Come back tomorrow for a fresh start!</p>';
            html += '</div>';
        } else {
            html += '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.1);border-radius:12px;padding:20px;">';
            html += '<h4 style="color:#fff;margin:0 0 15px;">📝 Submit End-of-Day Report</h4>';
            html += '<div style="margin-bottom:12px;"><label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:5px;">🏆 What went well today?</label>';
            html += '<textarea id="vmo-tt-wins" rows="2" style="width:100%;background:#1e293b;border:1px solid #334155;border-radius:8px;color:#e2e8f0;padding:10px;font-size:0.9rem;resize:vertical;" placeholder="Wins, achievements, breakthroughs..."></textarea></div>';
            html += '<div style="margin-bottom:12px;"><label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:5px;">🚧 What blocked your progress?</label>';
            html += '<textarea id="vmo-tt-blockers" rows="2" style="width:100%;background:#1e293b;border:1px solid #334155;border-radius:8px;color:#e2e8f0;padding:10px;font-size:0.9rem;resize:vertical;" placeholder="Blockers, distractions, challenges..."></textarea></div>';
            html += '<div style="margin-bottom:15px;"><label style="color:#94a3b8;font-size:0.85rem;display:block;margin-bottom:5px;">📒 Additional Notes</label>';
            html += '<textarea id="vmo-tt-notes" rows="2" style="width:100%;background:#1e293b;border:1px solid #334155;border-radius:8px;color:#e2e8f0;padding:10px;font-size:0.9rem;resize:vertical;" placeholder="Any other observations..."></textarea></div>';
            html += '<button onclick="VMOBusinessDashboard.submitDailyReport()" id="vmo-tt-submit-btn" style="width:100%;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border:none;padding:14px;border-radius:10px;cursor:pointer;font-weight:700;font-size:1rem;">📊 Submit Report & Calculate Vision Impact</button>';
            html += '</div>';
        }

        cnt.innerHTML = html;
    }

    function submitDailyReport() {
        if (!_todaysTasksData || !_todaysTasksData.roadmap_id) return;
        var btn = document.getElementById('vmo-tt-submit-btn');
        if (btn) { btn.textContent = 'Submitting...'; btn.disabled = true; }

        var cfg = getAjaxConfig();
        jQuery.post(cfg.url, {
            action: 'vmo_submit_daily_report',
            security: cfg.nonce,
            roadmap_id: _todaysTasksData.roadmap_id,
            wins: (document.getElementById('vmo-tt-wins') || {}).value || '',
            blockers: (document.getElementById('vmo-tt-blockers') || {}).value || '',
            notes: (document.getElementById('vmo-tt-notes') || {}).value || ''
        }).done(function(res) {
            if (res && res.success && res.data) {
                var d = res.data;
                var cnt = document.getElementById('vmo-tt-content');
                if (!cnt) return;

                var scoreColor = d.day_score >= 90 ? '#22c55e' : (d.day_score >= 60 ? '#eab308' : '#ef4444');
                var adjText = d.day_adjustment === 0 ? 'No change to your timeline' :
                    (d.day_adjustment < 0 ? '🚀 Vision ' + Math.abs(d.day_adjustment) + ' day(s) closer!' : '⚠️ Vision pushed ' + d.day_adjustment + ' day(s) further');
                var adjColor = d.day_adjustment <= 0 ? '#22c55e' : '#ef4444';

                var html = '<div style="text-align:center;padding:30px;">';
                html += '<div style="font-size:4rem;margin-bottom:10px;">' + (d.day_score >= 90 ? '🏆' : (d.day_score >= 60 ? '👍' : '💪')) + '</div>';
                html += '<h2 style="color:#fff;margin:0 0 5px;">Day ' + (_todaysTasksData.current_day || '?') + ' Report Submitted</h2>';

                // Score ring
                html += '<div style="margin:20px auto;width:120px;height:120px;position:relative;">';
                var r2 = 50; var c2 = 2 * Math.PI * r2; var o2 = c2 - (d.day_score / 100) * c2;
                html += '<svg width="120" height="120" viewBox="0 0 120 120"><circle cx="60" cy="60" r="' + r2 + '" fill="none" stroke="#1e293b" stroke-width="10"/>';
                html += '<circle cx="60" cy="60" r="' + r2 + '" fill="none" stroke="' + scoreColor + '" stroke-width="10" stroke-linecap="round" stroke-dasharray="' + c2 + '" stroke-dashoffset="' + o2 + '" transform="rotate(-90 60 60)"/>';
                html += '<text x="60" y="65" text-anchor="middle" fill="#fff" font-size="24" font-weight="bold">' + d.day_score + '</text></svg>';
                html += '</div>';

                html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:15px;margin:20px 0;">';
                html += '<div style="padding:15px;background:rgba(255,255,255,0.05);border-radius:10px;"><div style="font-size:1.3rem;font-weight:700;color:#a5b4fc;">' + d.completed + '/' + d.planned + '</div><div style="font-size:0.8rem;color:#94a3b8;">Tasks Done</div></div>';
                html += '<div style="padding:15px;background:rgba(255,255,255,0.05);border-radius:10px;"><div style="font-size:1.3rem;font-weight:700;color:#fbbf24;">' + (d.streak > 0 ? '🔥 ' + d.streak : '—') + '</div><div style="font-size:0.8rem;color:#94a3b8;">Day Streak</div></div>';
                html += '<div style="padding:15px;background:rgba(255,255,255,0.05);border-radius:10px;"><div style="font-size:1.3rem;font-weight:700;color:' + adjColor + ';">' + adjText + '</div><div style="font-size:0.8rem;color:#94a3b8;">Vision Impact</div></div>';
                html += '</div>';

                // Assessment
                html += '<div style="padding:15px;background:rgba(99,102,241,0.1);border:1px solid rgba(99,102,241,0.2);border-radius:10px;margin:15px 0;text-align:left;">';
                html += '<p style="margin:0;color:#cbd5e1;font-size:0.9rem;line-height:1.5;">' + esc(d.assessment) + '</p></div>';

                // New Vision Date
                if (d.new_vision_date) {
                    html += '<div style="margin-top:10px;color:#94a3b8;font-size:0.9rem;">🎯 Updated Vision Date: <strong style="color:#fbbf24;">' + esc(d.new_vision_date) + '</strong></div>';
                }

                html += '</div>';
                cnt.innerHTML = html;

                // Refresh main dashboard data
                loadRoadmapProgress();
                _todaysTasksData.report_submitted = true;
            } else {
                if (btn) { btn.textContent = '📊 Submit Report & Calculate Vision Impact'; btn.disabled = false; }
                showToast(res.data && res.data.message ? res.data.message : 'Report submission failed', 'error');
            }
        }).fail(function() {
            if (btn) { btn.textContent = '📊 Submit Report & Calculate Vision Impact'; btn.disabled = false; }
            showToast('Network error submitting report', 'error');
        });
    }

    /* ── Report History Tab ── */
    function renderHistoryTab() {
        var cnt = document.getElementById('vmo-tt-content');
        if (!cnt || !_todaysTasksData || !_todaysTasksData.roadmap_id) {
            if (cnt) cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8;">No roadmap data available.</div>';
            return;
        }
        cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8;">Loading report history...</div>';

        var cfg = getAjaxConfig();
        jQuery.post(cfg.url, {
            action: 'vmo_get_daily_reports_history',
            security: cfg.nonce,
            roadmap_id: _todaysTasksData.roadmap_id,
            limit: 14
        }).done(function(res) {
            if (!res || !res.success || !res.data || !res.data.reports || res.data.reports.length === 0) {
                cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8;">No reports yet. Submit your first End-of-Day report from the Report tab!</div>';
                return;
            }
            var reports = res.data.reports;
            var html = '<h3 style="color:#fff;margin:0 0 20px;">📈 Recent Daily Reports</h3>';

            // Trend chart (simple bar visualization)
            html += '<div style="display:flex;align-items:flex-end;gap:6px;height:120px;padding:10px;background:rgba(255,255,255,0.03);border-radius:10px;margin-bottom:20px;">';
            var reversed = reports.slice().reverse(); // oldest first
            reversed.forEach(function(r) {
                var score = parseInt(r.day_score, 10) || 0;
                var barH = Math.max(4, Math.round(score * 1.0));
                var barColor = score >= 90 ? '#22c55e' : (score >= 60 ? '#eab308' : '#ef4444');
                html += '<div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;">';
                html += '<div style="font-size:0.65rem;color:#94a3b8;">' + score + '</div>';
                html += '<div style="width:100%;height:' + barH + 'px;background:' + barColor + ';border-radius:4px 4px 0 0;min-height:4px;" title="Day ' + (r.day_number || '?') + ': ' + score + '%"></div>';
                html += '<div style="font-size:0.6rem;color:#64748b;">D' + (r.day_number || '?') + '</div>';
                html += '</div>';
            });
            html += '</div>';

            // Report list
            reports.forEach(function(r) {
                var score = parseInt(r.day_score, 10) || 0;
                var scoreColor = score >= 90 ? '#22c55e' : (score >= 60 ? '#eab308' : '#ef4444');
                var adj = parseInt(r.estimated_completion_adjustment, 10) || 0;
                var cumAdj = parseInt(r.cumulative_adjustment, 10) || 0;
                var streak = parseInt(r.streak_count, 10) || 0;

                html += '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:10px;padding:14px 18px;margin-bottom:8px;display:flex;align-items:center;gap:15px;">';
                html += '<div style="text-align:center;min-width:50px;"><div style="font-size:1.4rem;font-weight:700;color:' + scoreColor + ';">' + score + '</div><div style="font-size:0.7rem;color:#64748b;">score</div></div>';
                html += '<div style="flex:1;">';
                html += '<div style="font-weight:600;color:#e2e8f0;">Day ' + (r.day_number || '?') + ' — ' + (r.report_date || '') + '</div>';
                html += '<div style="font-size:0.82rem;color:#94a3b8;margin-top:2px;">' + (r.completed_activities_count || 0) + '/' + (r.planned_activities_count || 0) + ' tasks done';
                if (streak > 0) html += ' • 🔥 ' + streak + '-day streak';
                html += '</div>';
                if (r.wins) html += '<div style="font-size:0.8rem;color:#86efac;margin-top:3px;">🏆 ' + esc(r.wins).substring(0, 80) + '</div>';
                if (r.blockers) html += '<div style="font-size:0.8rem;color:#fca5a5;margin-top:2px;">🚧 ' + esc(r.blockers).substring(0, 80) + '</div>';
                html += '</div>';
                html += '<div style="text-align:center;min-width:70px;"><div style="font-size:0.9rem;font-weight:600;color:' + (adj <= 0 ? '#22c55e' : '#ef4444') + ';">' + (adj <= 0 ? adj : '+' + adj) + 'd</div>';
                html += '<div style="font-size:0.7rem;color:#64748b;">cum: ' + (cumAdj <= 0 ? cumAdj : '+' + cumAdj) + 'd</div></div>';
                html += '</div>';
            });

            cnt.innerHTML = html;
        }).fail(function() {
            cnt.innerHTML = '<div style="text-align:center;padding:40px;color:#f87171;">Could not load report history.</div>';
        });
    }

    return {
        init: init,
        openTodaysTasks: openTodaysTasks,
        completeTaskFromHub: completeTaskFromHub,
        submitDailyReport: submitDailyReport,
        
        /**
         * Purchase a Power Pack (Phone/Dialer)
         * @param {string} planKey - The plan ID (phone_m, phone_l, phone_xl, power_dialer)
         */
        buyPack: function(planKey) {
            console.log('Purchasing pack:', planKey);
            
            if (!confirm('Proceed to secure checkout for this Power Pack? (1-Year Access)')) return;

            // Find button to show loading state
            const btn = document.querySelector(`button[data-plan="${planKey}"]`);
            let originalText = 'Purchase';
            if(btn) {
                originalText = btn.innerHTML;
                btn.innerHTML = 'Processing...'; 
                btn.disabled = true; 
            }

            const ajaxURL = (window.vmo_ajax && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : (window.ajaxurl || '/wp-admin/admin-ajax.php');
            const nonce = (window.vmo_ajax && vmo_ajax.nonce) ? vmo_ajax.nonce : (window.vmo_nonce || '');

            jQuery.post(ajaxURL, {
                action: 'vmo_subscription_checkout',
                security: nonce,
                plan: planKey,
                billing_cycle: 'annual'
            }, function(response) {
                if (response.success && response.data && response.data.checkout_url) {
                    window.location.href = response.data.checkout_url;
                } else {
                    if(btn) { btn.innerHTML = originalText; btn.disabled = false; }
                    alert('Checkout Error: ' + (response.data?.message || 'Unknown error'));
                }
            }).fail(function() {
                if(btn) { btn.innerHTML = originalText; btn.disabled = false; }
                alert('Network error. Please try again.');
            });
        },

        launchPowerDialer: function() {
            if (typeof window.vmoOpenPowerDialer === 'function') {
                window.vmoOpenPowerDialer();
            } else {
                alert('Power Dialer module is initializing. Please wait...');
            }
        },

        setupSMS: function() {
            if (typeof window.openSMSActivation === 'function') {
                window.openSMSActivation();
                return;
            }

            const inlineActivationButton = document.getElementById('vmo-activate-sms-btn');
            if (inlineActivationButton && typeof inlineActivationButton.click === 'function') {
                inlineActivationButton.click();
                return;
            }

            const modalId = 'vmo-sms-setup-modal';
            const existing = document.getElementById(modalId);
            if (existing) existing.remove();

            const ajaxObj = window.vmo_ajax || window.vmo_ajax_obj || window.vmo_dashboard_data || {};
            const dashboardUrl = ajaxObj.ajaxurl
                ? ajaxObj.ajaxurl.replace('admin-ajax.php', 'admin.php?page=vmo-ai-dashboard')
                : 'admin.php?page=vmo-ai-dashboard';
            
            const html = `
            <div id="${modalId}" class="vmo-fs-modal" style="display:flex; z-index:100000; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); backdrop-filter:blur(5px); justify-content:center; align-items:center; font-family:'Inter',sans-serif;">
                <div class="vmo-modal-panel" style="background:rgba(23, 30, 48, 0.95); padding:40px; border-radius:16px; width:600px; max-width:90%; border:1px solid rgba(16, 185, 129, 0.4); box-shadow: 0 0 30px rgba(16, 185, 129, 0.1); color:#fff; position:relative;">
                    <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:20px;">
                        <div>
                            <h2 style="margin:0; color:#10b981; font-size:1.8rem;">📱 SMS Configuration & Compliance</h2>
                            <p style="color:#94a3b8; font-size:0.95rem; margin-top:5px;">Activate Text Messaging capabilities for your business line.</p>
                        </div>
                        <button onclick="document.getElementById('${modalId}').remove()" style="background:none; border:none; color:#94a3b8; cursor:pointer; font-size:1.5rem;">&times;</button>
                    </div>

                    <div style="background:rgba(255,255,255,0.05); padding:20px; border-radius:8px; margin-bottom:20px; border-left:4px solid #f59e0b;">
                        <h4 style="margin:0 0 10px 0; color:#f59e0b;">⚠️ US Carrier Requirements (A2P 10DLC)</h4>
                        <p style="font-size:0.9rem; line-height:1.5; color:#cbd5e1; margin:0;">
                            To send SMS traffic to US numbers, carriers now mandate <strong>A2P 10DLC Registration</strong> (Application-to-Person 10-Digit Long Code).
                            Without registration, your messages will be blocked.
                        </p>
                    </div>

                    <div style="margin-bottom:30px;">
                        <h4 style="color:#fff; margin-bottom:10px;">Use the integrated VMO activation flow:</h4>
                        <ol style="color:#cbd5e1; line-height:1.6; padding-left:20px;">
                            <li>Open the VMO SMS Activation center.</li>
                            <li>Submit or refresh your brand and campaign status inside VMO.</li>
                            <li>VMO will keep checking the number and switch SMS to active when the carrier reports approval.</li>
                        </ol>
                    </div>
                    
                    <div style="display:flex; gap:15px; justify-content:flex-end;">
                        <button onclick="document.getElementById('${modalId}').remove()" style="padding:12px 25px; background:transparent; border:1px solid #475569; color:#94a3b8; border-radius:8px; cursor:pointer; font-weight:500;">Close</button>
                        <button onclick="window.location.href='${dashboardUrl}';" style="padding:12px 25px; background:#10b981; border:none; color:white; border-radius:8px; cursor:pointer; font-weight:600; box-shadow:0 4px 12px rgba(16, 185, 129, 0.3);">
                            Open SMS Activation Center &rarr;
                        </button>
                    </div>
                </div>
            </div>`;
            document.body.insertAdjacentHTML('beforeend', html);
        },
        
        // ADDED: Drop/Release Number Functionality
        dropNumber: function() {
            const confirmed = confirm("⚠️ DANGER: Are you sure you want to drop your business phone number?\n\n• You will lose this number permanently.\n• It will stop working immediately.\n• Getting a new number later will incur an ACTIVATION FEE.\n\nType 'OK' to confirm.");
            // Actually, standard confirm is safer for UI.
            if (!confirm("Are you absolutely sure you want to delete your phone number? This cannot be undone.")) {
                return;
            }

            const btn = document.activeElement;
            if(btn) {
                btn.innerText = 'Releasing...';
                btn.disabled = true;
            }

            const ajaxObj = window.vmo_ajax || window.vmo_ajax_obj;
            const ajaxURL = ajaxObj ? (ajaxObj.ajaxurl || ajaxObj.ajax_url) : '/wp-admin/admin-ajax.php';
            const nonce = ajaxObj ? (ajaxObj.vmo_nonce || ajaxObj.nonce) : '';
            
            // We need to get the number from the DOM if possible, or backend will find it.
            // Backend finds 'active' number for user, so we don't need to send it explicitly if we trust the session.
            const displayEl = document.getElementById('vmo-assigned-number');
            let phone = '';
            if (displayEl) phone = displayEl.innerText.trim();
            if (phone === '—' || phone === '') {
                 alert("You don't have an active number to drop.");
                 if(btn) { btn.innerText = 'Drop Number'; btn.disabled = false; }
                 return;
            }

            jQuery.post(ajaxURL, {
                action: 'vmo_release_phone_number',
                nonce: nonce,
                phone_number: phone // Optional verification
            }, function(response) {
                if (response.success) {
                    alert('Number released successfully.');
                    window.location.reload();
                } else {
                    let msg = response.data ? (response.data.message || 'Unknown error') : 'Unknown error';
                    alert('Error: ' + msg);
                    if(btn) { btn.innerText = 'Drop Number'; btn.disabled = false; }
                }
            }).fail(function() {
                alert('Connection failed.');
                if(btn) { btn.innerText = 'Drop Number'; btn.disabled = false; }
            });
        },

        setupVirtualNumber: function() {
            // Updated State & Area Code Data with Descriptions
            const VMO_US_STATES = {
                "AL": { name: "Alabama", codes: { "205": "Birmingham, Tuscaloosa", "251": "Mobile, Gulf Shores", "256": "Huntsville, Decatur", "334": "Montgomery, Auburn", "938": "Huntsville (overlay)" } },
                "AK": { name: "Alaska", codes: { "907": "Entire State" } },
                "AZ": { name: "Arizona", codes: { "480": "Scottsdale, East Valley", "520": "Tucson", "602": "Phoenix (Central)", "623": "Glendale, West Valley", "928": "Flagstaff, Yuma" } },
                "AR": { name: "Arkansas", codes: { "479": "Fayetteville, Fort Smith", "501": "Little Rock, Central AR", "870": "Jonesboro, Pine Bluff" } },
                "CA": { name: "California", codes: { "209": "Stockton, Modesto", "213": "Los Angeles (Downtown)", "310": "Los Angeles (West/Coastal)", "323": "Los Angeles (Central/Hollywood)", "408": "San Jose, Silicon Valley", "415": "San Francisco, Marin", "510": "Oakland, East Bay", "530": "Redding, Davis", "559": "Fresno, Visalia", "562": "Long Beach", "619": "San Diego", "626": "Pasadena", "650": "Palo Alto, San Mateo", "661": "Bakersfield, Santa Clarita", "707": "Santa Rosa, Napa", "714": "Anaheim, Orange County", "760": "Palm Springs, Oceanside", "805": "Santa Barbara, Ventura", "818": "San Fernando Valley", "831": "Monterey, Santa Cruz", "858": "San Diego (North)", "909": "San Bernardino", "916": "Sacramento", "925": "Concord, Walnut Creek", "949": "Irvine, South OC", "951": "Riverside" } },
                "CO": { name: "Colorado", codes: { "303": "Denver, Boulder", "719": "Colorado Springs", "970": "Fort Collins, Aspen", "720": "Denver (overlay)" } },
                "CT": { name: "Connecticut", codes: { "203": "New Haven, Stamford", "860": "Hartford", "475": "New Haven (overlay)" } },
                "DE": { name: "Delaware", codes: { "302": "Entire State" } },
                "FL": { name: "Florida", codes: { "239": "Fort Myers, Naples", "305": "Miami, Key West", "321": "Orlando, Space Coast", "352": "Gainesville, Ocala", "386": "Daytona Beach", "407": "Orlando", "561": "West Palm Beach, Boca Raton", "727": "St. Petersburg, Clearwater", "772": "Stuart, Port St. Lucie", "813": "Tampa", "850": "Tallahassee, Pensacola", "863": "Lakeland", "904": "Jacksonville", "941": "Sarasota, Bradenton", "954": "Fort Lauderdale", "786": "Miami (overlay)" } },
                "GA": { name: "Georgia", codes: { "229": "Albany, Valdosta", "404": "Atlanta (Inside Perimeter)", "470": "Atlanta (overlay)", "478": "Macon", "678": "Atlanta (Metro)", "706": "Augusta, Athens, Columbus", "762": "Augusta (overlay)", "770": "Atlanta (Suburbs/Exurbs)", "912": "Savannah" } },
                "HI": { name: "Hawaii", codes: { "808": "Entire State" } },
                "ID": { name: "Idaho", codes: { "208": "Entire State", "986": "Idaho (overlay)" } },
                "IL": { name: "Illinois", codes: { "217": "Springfield, Champaign", "224": "Evanston (overlay)", "309": "Peoria, Bloomington", "312": "Chicago (Downtown)", "331": "Aurora (overlay)", "618": "Southern Illinois", "630": "Aurora, Naperville", "708": "Chicago South Suburbs", "773": "Chicago (Outside Loop)", "815": "Joliet, Rockford", "847": "Evanston, Schaumburg" } },
                "IN": { name: "Indiana", codes: { "219": "Gary, Hammond", "260": "Fort Wayne", "317": "Indianapolis", "463": "Indianapolis (overlay)", "574": "South Bend", "765": "Lafayette, Muncie", "812": "Evansville, Bloomington", "930": "Southern IN (overlay)" } },
                "IA": { name: "Iowa", codes: { "319": "Cedar Rapids, Waterloo", "515": "Des Moines", "563": "Davenport, Dubuque", "641": "Mason City", "712": "Sioux City, Council Bluffs" } },
                "KS": { name: "Kansas", codes: { "316": "Wichita", "620": "Dodge City, Emporia", "785": "Topeka, Lawrence", "913": "Kansas City, Overland Park" } },
                "KY": { name: "Kentucky", codes: { "270": "Bowling Green", "364": "Western KY (overlay)", "502": "Louisville, Frankfort", "606": "Ashland, Somerset", "859": "Lexington, Covington" } },
                "LA": { name: "Louisiana", codes: { "225": "Baton Rouge", "318": "Shreveport, Monroe", "337": "Lafayette, Lake Charles", "504": "New Orleans", "985": "North Shore, Houma" } },
                "ME": { name: "Maine", codes: { "207": "Entire State" } },
                "MD": { name: "Maryland", codes: { "240": "Western MD (overlay)", "301": "Western MD", "410": "Baltimore, Eastern Shore", "443": "Baltimore (overlay)", "667": "Eastern MD (overlay)" } },
                "MA": { name: "Massachusetts", codes: { "339": "Boston Suburbs (overlay)", "351": "North Shore (overlay)", "413": "Springfield, Western MA", "508": "Worcester, Cape Cod", "617": "Boston, Cambridge", "774": "Worcester (overlay)", "781": "Boston Suburbs", "857": "Boston (overlay)", "978": "Lowell, North Shore" } },
                "MI": { name: "Michigan", codes: { "231": "Traverse City", "248": "Troy, Oakland County", "269": "Kalamazoo, Battle Creek", "313": "Detroit", "517": "Lansing", "586": "Warren, Macomb County", "616": "Grand Rapids", "734": "Ann Arbor, Monroe", "810": "Flint", "906": "Upper Peninsula", "947": "Troy (overlay)", "989": "Saginaw, Midland" } },
                "MN": { name: "Minnesota", codes: { "218": "Duluth", "320": "St. Cloud", "507": "Rochester, Mankato", "612": "Minneapolis", "651": "St. Paul", "763": "Brooklyn Park", "952": "Bloomington" } },
                "MS": { name: "Mississippi", codes: { "228": "Gulfport, Biloxi", "601": "Jackson", "662": "Tupelo, Greenville", "769": "Jackson (overlay)" } },
                "MO": { name: "Missouri", codes: { "314": "St. Louis", "417": "Springfield, Joplin", "573": "Columbia, Jefferson City", "636": "St. Charles, Chesterfield", "660": "Sedalia, Kirksville", "816": "Kansas City, St. Joseph" } },
                "MT": { name: "Montana", codes: { "406": "Entire State" } },
                "NE": { name: "Nebraska", codes: { "308": "Grand Island, North Platte", "402": "Omaha, Lincoln", "531": "Omaha (overlay)" } },
                "NV": { name: "Nevada", codes: { "702": "Las Vegas", "725": "Las Vegas (overlay)", "775": "Reno, Carson City" } },
                "NH": { name: "New Hampshire", codes: { "603": "Entire State" } },
                "NJ": { name: "New Jersey", codes: { "201": "Hackensack, Jersey City", "551": "Jersey City (overlay)", "609": "Trenton, Atlantic City", "732": "New Brunswick", "848": "New Brunswick (overlay)", "856": "Camden, Cherry Hill", "862": "Newark (overlay)", "908": "Elizabeth", "973": "Newark, Paterson" } },
                "NM": { name: "New Mexico", codes: { "505": "Albuquerque, Santa Fe", "575": "Las Cruces, Roswell" } },
                "NY": { name: "New York", codes: { "212": "Manhattan", "315": "Syracuse, Utica", "516": "Nassau County (Long Island)", "518": "Albany", "585": "Rochester", "607": "Binghamton, Ithaca", "631": "Suffolk County (Long Island)", "646": "Manhattan (overlay)", "716": "Buffalo, Niagara Falls", "718": "Brooklyn, Queens, Bronx", "845": "Poughkeepsie", "914": "Westchester", "917": "NYC Mobile", "929": "NYC (overlay)" } },
                "NC": { name: "North Carolina", codes: { "252": "Greenville, Rocky Mount", "336": "Greensboro, Winston-Salem", "704": "Charlotte", "828": "Asheville", "910": "Fayetteville, Wilmington", "919": "Raleigh, Durham", "980": "Charlotte (overlay)", "984": "Raleigh (overlay)" } },
                "ND": { name: "North Dakota", codes: { "701": "Entire State" } },
                "OH": { name: "Ohio", codes: { "216": "Cleveland", "234": "Akron (overlay)", "330": "Akron, Canton, Youngstown", "419": "Toledo", "440": "Lorain, Elyria", "513": "Cincinnati", "567": "Toledo (overlay)", "614": "Columbus", "740": "Marion, Lancaster", "937": "Dayton" } },
                "OK": { name: "Oklahoma", codes: { "405": "Oklahoma City", "539": "Tulsa (overlay)", "580": "Lawton, Enid", "918": "Tulsa" } },
                "OR": { name: "Oregon", codes: { "458": "Eugene (overlay)", "503": "Portland, Salem", "541": "Eugene, Medford", "971": "Portland (overlay)" } },
                "PA": { name: "Pennsylvania", codes: { "215": "Philadelphia", "267": "Philadelphia (overlay)", "272": "Scranton (overlay)", "412": "Pittsburgh", "484": "Allentown (overlay)", "570": "Scranton, Wilkes-Barre", "610": "Allentown, Reading", "717": "Harrisburg, Lancaster", "724": "New Castle", "814": "Erie, State College", "878": "Pittsburgh (overlay)" } },
                "RI": { name: "Rhode Island", codes: { "401": "Entire State" } },
                "SC": { name: "South Carolina", codes: { "803": "Columbia, Rock Hill", "843": "Charleston, Myrtle Beach", "864": "Greenville, Spartanburg" } },
                "SD": { name: "South Dakota", codes: { "605": "Entire State" } },
                "TN": { name: "Tennessee", codes: { "423": "Chattanooga, Johnson City", "615": "Nashville", "731": "Jackson", "865": "Knoxville", "901": "Memphis", "931": "Clarksville" } },
                "TX": { name: "Texas", codes: { "210": "San Antonio", "214": "Dallas", "254": "Waco, Killeen", "281": "Houston (Suburbs)", "325": "Abilene, San Angelo", "361": "Corpus Christi", "409": "Beaumont, Galveston", "469": "Dallas (overlay)", "512": "Austin", "713": "Houston (Central)", "737": "Austin (overlay)", "806": "Lubbock, Amarillo", "817": "Fort Worth", "830": "New Braunfels", "832": "Houston (overlay)", "903": "Tyler, Longview", "915": "El Paso", "936": "Huntsville", "940": "Denton, Wichita Falls", "956": "Laredo, McAllen", "972": "Dallas (Suburbs)", "979": "College Station" } },
                "UT": { name: "Utah", codes: { "385": "Salt Lake City (overlay)", "435": "St. George, Logan", "801": "Salt Lake City, Provo" } },
                "VT": { name: "Vermont", codes: { "802": "Entire State" } },
                "VA": { name: "Virginia", codes: { "276": "Bristol, Martinsville", "434": "Charlottesville, Lynchburg", "540": "Roanoke, Harrisonburg", "571": "Arlington (overlay)", "703": "Arlington, Alexandria", "757": "Virginia Beach, Norfolk", "804": "Richmond" } },
                "WA": { name: "Washington", codes: { "206": "Seattle", "253": "Tacoma", "360": "Olympia, Vancouver", "425": "Bellevue, Everett", "509": "Spokane, Yakima" } },
                "WV": { name: "West Virginia", codes: { "304": "Entire State", "681": "Entire State (overlay)" } },
                "WI": { name: "Wisconsin", codes: { "262": "Racine, Kenosha", "414": "Milwaukee", "534": "Eau Claire (overlay)", "608": "Madison", "715": "Eau Claire, Wausau", "920": "Green Bay, Appleton" } },
                "WY": { name: "Wyoming", codes: { "307": "Entire State" } },
                "DC": { name: "Washington DC", codes: { "202": "District of Columbia" } }
            };

            // Create modal HTML with Glassymorphism & Dark Theme
            const modalId = 'vmo-phone-setup-modal';
            const existingModal = document.getElementById(modalId);
            if (existingModal) existingModal.remove();

            // GENERATE OPTIONS
            let stateOptions = '<option value="">Select State</option>';
            Object.keys(VMO_US_STATES).sort().forEach(code => {
                stateOptions += `<option value="${code}">${VMO_US_STATES[code].name}</option>`;
            });

            const modalHTML = `
                <div id="${modalId}" class="vmo-fs-modal" style="display:flex; z-index:100000; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); backdrop-filter:blur(5px); justify-content:center; align-items:center; font-family:'Inter',sans-serif;">
                    <div class="vmo-modal-panel" style="background:rgba(23, 30, 48, 0.95); padding:30px; border-radius:16px; width:480px; max-width:90%; border:1px solid rgba(6, 182, 212, 0.5); box-shadow: 0 0 30px rgba(6, 182, 212, 0.15); color:#fff; position:relative; overflow:hidden;">
                        <!-- Glow Effect -->
                        <div style="position:absolute; top:-50%; left:-50%; width:200%; height:200%; background:radial-gradient(circle, rgba(6,182,212,0.05) 0%, transparent 70%); pointer-events:none;"></div>
                        
                        <div style="position:relative; z-index:1;">
                            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                                <h3 style="margin:0; color:#fff; font-size:1.4rem;">📞 Select Business Line</h3>
                                <button onclick="document.getElementById('${modalId}').remove()" style="background:none; border:none; color:#94a3b8; cursor:pointer; font-size:1.2rem;">&times;</button>
                            </div>
                            
                            <p style="color:#94a3b8; margin-bottom:25px; font-size:0.95rem;">Choose your local presence. Select a state to see available area codes.</p>
                            
                            <!-- STEP 1: SEARCH -->
                            <div id="vmo-phone-step-1">
                                <!-- GLOBAL COUNTRY SELECTOR -->
                                <div style="margin-bottom:15px;">
                                    <label style="display:block; margin-bottom:8px; font-weight:500; color:#22d3ee; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px;">Country</label>
                                    <select id="vmo-phone-country" style="width:100%; padding:12px; background:rgba(0,0,0,0.3); border:1px solid #334155; border-radius:8px; color:#fff; font-size:1rem; outline:none; transition:border-color 0.2s;">
                                        <option value="US">🇺🇸 United States</option>
                                        <option value="CA">🇨🇦 Canada</option>
                                        <option value="GB">🇬🇧 United Kingdom</option>
                                        <option value="AU">🇦🇺 Australia</option>
                                        <option value="DE">🇩🇪 Germany</option>
                                        <option value="FR">🇫🇷 France</option>
                                        <option value="Other">🌍 Other / Manual Code</option>
                                    </select>
                                </div>

                                <!-- US OPTION: STATE DROPDOWN -->
                                <div id="vmo-us-state-container" style="margin-bottom:15px;">
                                    <label style="display:block; margin-bottom:8px; font-weight:500; color:#22d3ee; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px;">Location (State)</label>
                                    <select id="vmo-phone-state" style="width:100%; padding:12px; background:rgba(0,0,0,0.3); border:1px solid #334155; border-radius:8px; color:#fff; font-size:1rem; outline:none; transition:border-color 0.2s;">
                                        ${stateOptions}
                                    </select>
                                </div>
                                
                                <div style="margin-bottom:25px;">
                                    <label style="display:block; margin-bottom:8px; font-weight:500; color:#22d3ee; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.5px;">Area Code</label>
                                    <!-- US AREA DROPDOWN -->
                                    <select id="vmo-phone-area-select" disabled style="width:100%; padding:12px; background:rgba(0,0,0,0.3); border:1px solid #334155; border-radius:8px; color:#94a3b8; font-size:1rem; outline:none; transition:all 0.2s; cursor:not-allowed;">
                                        <option value="">Select State First</option>
                                    </select>
                                    <!-- INTERNATIONAL MANUAL INPUT -->
                                    <input type="text" id="vmo-phone-area-input" placeholder="e.g. 20 for London, 416 for Toronto..." style="display:none; width:100%; padding:12px; background:rgba(0,0,0,0.3); border:1px solid #334155; border-radius:8px; color:#fff; font-size:1rem; outline:none; transition:border-color 0.2s;">
                                </div>
                                
                                <!-- CHANGE NUMBER CHECKBOX -->
                                <div style="margin-bottom:15px; display:flex; align-items:flex-start; gap:10px;">
                                    <input type="checkbox" id="vmo-replace-number-check" style="margin-top:4px;">
                                    <div>
                                        <label for="vmo-replace-number-check" style="display:block; color:#fff; font-weight:500;">Replace my existing number</label>
                                        <small style="color:#94a3b8; display:block; line-height:1.4;">Check this if you want to switch numbers. Your old number will be released.</small>
                                    </div>
                                </div>

                                <div style="display:flex; gap:10px; justify-content:flex-end;">
                                    <button onclick="document.getElementById('${modalId}').remove()" style="padding:10px 20px; border:1px solid #334155; background:transparent; color:#94a3b8; border-radius:8px; cursor:pointer; font-weight:500; transition:all 0.2s;">Cancel</button>
                                    <button id="vmo-phone-search-btn" disabled style="padding:10px 25px; border:none; background:#0891b2; color:white; border-radius:8px; cursor:not-allowed; font-weight:600; box-shadow:0 4px 6px rgba(0,0,0,0.2); transition:all 0.2s; opacity:0.5;">
                                        Find Numbers
                                    </button>
                                </div>
                            </div>

                            <!-- STEP 2: RESULTS -->
                            <div id="vmo-phone-step-2" style="display:none;">
                                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                                    <p style="font-weight:600; color:#fff; margin:0;">Available Numbers:</p>
                                    <span style="font-size:0.8rem; color:#22d3ee; background:rgba(34, 211, 238, 0.1); padding:2px 8px; border-radius:12px;">Memorable First</span>
                                </div>
                                
                                <div id="vmo-phone-results" style="max-height:220px; overflow-y:auto; border:1px solid #334155; margin-bottom:20px; border-radius:8px; background:rgba(0,0,0,0.2);">
                                    <div style="padding:20px; color:#94a3b8; text-align:center;">Searching inventory...</div>
                                </div>

                                <div style="margin-bottom:15px; text-align:left;">
                                    <label style="display:block; margin-bottom:5px; font-size:0.85rem; color:#94a3b8;">Phone Identity (Optional)</label>
                                    <input type="text" id="vmo-phone-label-input" placeholder="e.g. Sales Line, Support Desk" style="width:100%; padding:8px 12px; background:rgba(0,0,0,0.3); border:1px solid #334155; border-radius:6px; color:#fff; font-size:0.9rem; outline:none; transition:border 0.2s;" onfocus="this.style.borderColor='#22d3ee'" onblur="this.style.borderColor='#334155'">
                                    <small style="color:#64748b; font-size:0.75rem; display:block; margin-top:4px;">Customize how this number appears in your Caller ID settings.</small>
                                </div>
                                
                                <div style="display:flex; gap:10px; justify-content:flex-end;">
                                    <button onclick="document.getElementById('vmo-phone-step-1').style.display='block'; document.getElementById('vmo-phone-step-2').style.display='none';" style="padding:10px 20px; border:1px solid #334155; background:transparent; color:#94a3b8; border-radius:8px; cursor:pointer; font-weight:500;">Back</button>
                                    <button id="vmo-phone-buy-btn" disabled style="padding:10px 25px; border:none; background:#0891b2; color:white; border-radius:8px; cursor:not-allowed; font-weight:600; box-shadow:0 4px 6px rgba(0,0,0,0.2); opacity:0.5; transition:all 0.2s;">
                                        Activate Selected
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', modalHTML);

            let selectedNumber = null;
            const countrySelect = document.getElementById('vmo-phone-country');
            const stateContainer = document.getElementById('vmo-us-state-container');
            const stateSelect = document.getElementById('vmo-phone-state');
            const areaSelect = document.getElementById('vmo-phone-area-select');
            const areaInput = document.getElementById('vmo-phone-area-input');
            const searchBtn = document.getElementById('vmo-phone-search-btn');

            // --- COUNTRY CHANGE LOGIC ---
            countrySelect.onchange = function() {
                const country = this.value;
                if (country === 'US') {
                    // Show US UI
                    stateContainer.style.display = 'block';
                    areaSelect.style.display = 'block';
                    areaInput.style.display = 'none';
                    // Reset Button State based on US logic (needs State selection)
                    if (stateSelect.value) {
                         searchBtn.disabled = false; searchBtn.style.opacity = '1'; searchBtn.style.cursor = 'pointer';
                    } else {
                         searchBtn.disabled = true; searchBtn.style.opacity = '0.5'; searchBtn.style.cursor = 'not-allowed';
                    }
                } else if (country === 'Other') {
                    // Show Manual Input
                    stateContainer.style.display = 'none';
                    areaSelect.style.display = 'none';
                    areaInput.style.display = 'block';
                    areaInput.placeholder = "Enter Country + Area Code (e.g. 331 for Paris)";
                    // Always enable search for manual mode, let user try
                    searchBtn.disabled = false; searchBtn.style.opacity = '1'; searchBtn.style.cursor = 'pointer';
                } else {
                    // International Specific (CA, GB, etc)
                    stateContainer.style.display = 'none';
                    areaSelect.style.display = 'none';
                    areaInput.style.display = 'block';
                    areaInput.placeholder = `Enter Area/City Code for ${country}`;
                     // Always enable search
                    searchBtn.disabled = false; searchBtn.style.opacity = '1'; searchBtn.style.cursor = 'pointer';
                }
            };

            // STATE CHANGE HANDLER (US ONLY)
            stateSelect.onchange = function() {
                const state = this.value;
                areaSelect.innerHTML = '<option value="">All Area Codes</option>';
                
                if (state && VMO_US_STATES[state]) {
                    // Iterate object keys for codes
                    const codes = VMO_US_STATES[state].codes;
                    Object.keys(codes).forEach(code => {
                         const city = codes[code];
                         areaSelect.innerHTML += `<option value="${code}">${code} - ${city}</option>`;
                    });
                    areaSelect.disabled = false;
                    areaSelect.style.color = '#fff';
                    areaSelect.style.cursor = 'pointer';
                    
                    searchBtn.disabled = false;
                    searchBtn.style.opacity = '1';
                    searchBtn.style.cursor = 'pointer';
                } else {
                    areaSelect.disabled = true;
                    areaSelect.style.color = '#94a3b8';
                    searchBtn.disabled = true;
                    searchBtn.style.opacity = '0.5';
                }
            };
            

            // SEARCH LOGIC
            searchBtn.onclick = function() {
                const btn = this;
                let country = countrySelect.value;
                let areaCode = '';

                // Logic to get correct Area Code
                if (country === 'US') {
                    areaCode = areaSelect.value;
                } else if (country === 'Other') {
                    // Start from Input, user might type country code too? 
                    // For simplicity, we fallback to US if they chose Other but let them type whatever
                    // But actually plugin expects ISO country code.
                    const val = areaInput.value.trim();
                    // If user selects Other, we might just pass 'US' and hope their area code finds something or default??
                    // Better: Prompt user for ISO code if they choose 'Other'? Default to US for now.
                    country = 'US'; 
                    areaCode = val;
                } else {
                    // CA, GB, etc.
                    areaCode = areaInput.value.trim();
                }
                
                btn.innerHTML = '<span class="vmo-spinner"></span> Searching...';
                btn.disabled = true;

                const ajaxObj = window.vmo_ajax || window.vmo_ajax_obj;
                const ajaxURL = ajaxObj ? (ajaxObj.ajaxurl || ajaxObj.ajax_url) : '/wp-admin/admin-ajax.php';
                const nonce = ajaxObj ? (ajaxObj.vmo_nonce || ajaxObj.nonce) : '';

                const replaceMode = document.getElementById('vmo-replace-number-check') ? document.getElementById('vmo-replace-number-check').checked : false;

                jQuery.post(ajaxURL, {
                    action: 'vmo_search_phone_numbers',
                    nonce: nonce,
                    country: country,
                    area_code: areaCode,
                    replace_mode: replaceMode ? 1 : 0
                }, function(res) {
                    btn.innerHTML = 'Find Numbers';
                    btn.disabled = false;

                    console.log('[VMO Phone Search] Response:', JSON.stringify(res));
                    if (res.data && res.data.debug) console.log('[VMO Phone Search] Debug:', JSON.stringify(res.data.debug, null, 2));
                    if (res.success && res.data.numbers && res.data.numbers.length > 0) {
                        // Switch to step 2
                        document.getElementById('vmo-phone-step-1').style.display = 'none';
                        document.getElementById('vmo-phone-step-2').style.display = 'block';

                        const list = document.getElementById('vmo-phone-results');
                        list.innerHTML = '';
                        res.data.numbers.forEach(num => {
                            const row = document.createElement('div');
                            row.className = 'vmo-phone-option';
                            const isOwned = num.is_owned ? '<span style="color:#10b981;font-size:0.7em;border:1px solid #10b981;padding:1px 4px;border-radius:4px;margin-left:5px;">OWNED</span>' : '';
                            const friendlyName = num.friendlyName || num.phoneNumber;
                            // Clean up friendly name if it contains "[OWNED]" already from server + our extra badge
                            // Server returns "FriendlyName - VMO... [OWNED]" optionally. 
                            // Visually, we just want to make sure the number is visible.
                            
                            row.style.cssText = 'padding:12px; border-bottom:1px solid #334155; cursor:pointer; display:flex; justify-content:space-between; align-items:center; color:#e2e8f0; transition:background 0.2s;';
                            // Ensure phoneNumber is always visible:
                            row.innerHTML = `<span style="font-weight:500; font-family:monospace; font-size:1.1rem;">${num.phoneNumber} ${isOwned}</span> <small style="color:#94a3b8; text-align:right;">${num.locality || 'Region'}<br><span style="font-size:0.8em;opacity:0.7">${friendlyName}</span></small>`;
                            
                            row.onclick = function() {
                                // Select visual
                                Array.from(list.children).forEach(c => {
                                    c.style.background = 'transparent';
                                    c.style.color = '#e2e8f0';
                                });
                                row.style.background = 'rgba(6, 182, 212, 0.2)'; // Cyan tint
                                row.style.color = '#22d3ee';
                                selectedNumber = num.phoneNumber;
                                
                                // Enable buy button
                                const buyBtn = document.getElementById('vmo-phone-buy-btn');
                                buyBtn.disabled = false;
                                buyBtn.style.opacity = '1';
                                buyBtn.style.background = '#0891b2'; // Cyan
                                buyBtn.style.cursor = 'pointer';
                                buyBtn.innerText = num.is_owned ? 'Re-Connect Number' : 'Activate Selected';
                            };
                            list.appendChild(row);
                        });
                    } else {
                        var errorMsg = (res && res.data && res.data.message) ? res.data.message : 'No numbers found for this area code. Please try another one or leave Area Code empty to search the whole state.';
                        console.error('[VMO Phone Search] Failed:', errorMsg, res);
                        alert(errorMsg);
                    }
                }).fail(function(xhr, status, err) {
                    console.error('[VMO Phone Search] AJAX Failed:', status, err, 'HTTP', xhr.status);
                    alert('Search failed (HTTP ' + xhr.status + '). Check console for details.');
                    btn.innerText = 'Find Numbers';
                    btn.disabled = false;
                });
            };

            // BUY LOGIC
            document.getElementById('vmo-phone-buy-btn').onclick = function() {
                if (!selectedNumber) return;
                
                const btn = this;
                const originalText = btn.innerText;
                const replaceMode = document.getElementById('vmo-replace-number-check') ? document.getElementById('vmo-replace-number-check').checked : false;
                const phoneLabel = document.getElementById('vmo-phone-label-input') ? document.getElementById('vmo-phone-label-input').value.trim() : '';

                btn.innerText = 'Activating...';
                btn.disabled = true;
                btn.style.opacity = '0.7';

                const ajaxObj = window.vmo_ajax || window.vmo_ajax_obj;
                const ajaxURL = ajaxObj ? (ajaxObj.ajaxurl || ajaxObj.ajax_url) : '/wp-admin/admin-ajax.php';
                const nonce = ajaxObj ? (ajaxObj.vmo_nonce || ajaxObj.nonce) : '';
                
                // Use selected country from dropdown
                const selectedCountry = countrySelect.value === 'Other' ? 'US' : countrySelect.value;
                
                if (replaceMode && !confirm("Warning: You are about to replace your existing phone number.\n\nChanging your number requires a new line activation. An Activation Fee of $3.00 will be deducted from your balance to cover carrier setup costs.\n\nYour old number will be permanently released. Do you want to continue?")) {
                    btn.innerText = originalText;
                    btn.disabled = false;
                    btn.style.opacity = '1';
                    return;
                }

                jQuery.post(ajaxURL, {
                    action: 'vmo_auto_provision_phone',
                    nonce: nonce,
                    selected_number: selectedNumber,
                    country: selectedCountry,
                    replace_existing: replaceMode ? 1 : 0,
                    phone_label: phoneLabel // Pass custom label
                }, function(response) {
                    if (response.success) {
                        // Success Animation or Logic
                        const provisionedDisplay = (response.data && response.data.formatted) ? response.data.formatted : selectedNumber;
                        const provisionedRaw = (response.data && response.data.number) ? response.data.number : selectedNumber;

                        // Persist locally so the dashboard can update without forcing a reload.
                        window.__vmoLatestProvisionedNumber = provisionedRaw;

                        document.getElementById('vmo-phone-results').innerHTML = `
                            <div style="text-align:center; padding:40px;">
                                <div style="font-size:3rem; margin-bottom:10px;">🎉</div>
                                <h3 style="color:#fff;">Activation Successful!</h3>
                                <p style="color:#94a3b8;">Your business line is ready.</p>
                                <p style="color:#22d3ee; font-size:1.2rem; font-family:monospace;">${provisionedDisplay}</p>
                                <div style="margin-top:18px; display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">
                                    <button id="vmo-phone-success-close" style="padding:10px 18px; border:none; background:#0891b2; color:white; border-radius:8px; cursor:pointer; font-weight:600; box-shadow:0 4px 6px rgba(0,0,0,0.2);">Close</button>
                                </div>
                            </div>
                        `;
                        document.getElementById('vmo-phone-buy-btn').style.display = 'none';

                        // Update Assigned Number UI immediately when present
                        try {
                            const assigned = document.getElementById('vmo-assigned-number');
                            if (assigned) assigned.textContent = provisionedRaw;
                        } catch(e) {}

                        // Keep the Phone tab open (no forced reload). Only close when user clicks.
                        const closeBtn = document.getElementById('vmo-phone-success-close');
                        if (closeBtn) {
                            closeBtn.onclick = function() {
                                try {
                                    const m = document.getElementById(modalId);
                                    if (m) m.remove();
                                } catch(e) {}
                                // Refresh phone panel widgets if available
                                try { if (typeof window.loadPhoneOverview === 'function') window.loadPhoneOverview(); } catch(e) {}
                                try { if (typeof window.loadPhoneAnalytics === 'function') window.loadPhoneAnalytics(); } catch(e) {}
                                // Ensure phone section remains active if tab system exists
                                try { if (typeof window.switchTab === 'function') window.switchTab('phone'); } catch(e) {}
                            };
                        }
                    } else {
                        // Parse JSON error from PHP
                        let errorMsg = response.data ? (response.data.message || 'Unknown error') : 'Unknown error';
                        alert('Error: ' + errorMsg);
                        btn.innerText = originalText;
                        btn.disabled = false;
                        btn.style.opacity = '1';
                    }
                }).fail(function(xhr, status, error) {
                     // Check if it's the HTML error
                     let msg = error;
                     if (xhr.responseText && xhr.responseText.includes('<')) {
                         msg = "Server returned an HTML error. Please check logs.";
                         console.error("VMO Fatal:", xhr.responseText);
                     } else if (xhr.responseJSON && xhr.responseJSON.data) {
                         msg = xhr.responseJSON.data.message;
                     }
                     alert('Activation failed: ' + msg);
                     btn.innerText = originalText;
                     btn.disabled = false;
                     btn.style.opacity = '1';
                });
            };
        },

        setupAIAssistant: function() {
            alert('Configure your Autonomous Receptionist in the "Voice & AI" settings tab.');
        },

        toggleCallRecording: function(enabled) {
            console.log('Call recording toggled:', enabled);
            if (currentUser) {
                currentUser.call_recording_enabled = enabled;
            }

            const ajaxObj = window.vmo_ajax || window.vmo_ajax_obj;
            const ajaxURL = ajaxObj ? (ajaxObj.ajaxurl || ajaxObj.ajax_url) : '/wp-admin/admin-ajax.php';
            const nonce = ajaxObj ? (ajaxObj.vmo_nonce || ajaxObj.nonce) : '';

            jQuery.post(ajaxURL, {
                action: 'vmo_update_user_preference',
                nonce: nonce,
                preference: 'call_recording_enabled',
                value: enabled ? 1 : 0
            }, function(response) {
                if (response.success) {
                     const toggle = document.getElementById('vmo_call_recording_toggle');
                     if(toggle) toggle.parentElement.style.opacity = '0.5';
                     setTimeout(() => { if(toggle) toggle.parentElement.style.opacity = '1'; }, 200);
                     
                     // Simple toast
                     const toast = document.createElement('div');
                     toast.textContent = enabled ? 'Call Recording Enabled' : 'Call Recording Disabled';
                     toast.style.cssText = 'position: fixed; bottom: 20px; right: 20px; background: #2d3748; color: white; padding: 12px 24px; border-radius: 4px; z-index: 10000; box-shadow: 0 4px 6px rgba(0,0,0,0.1); animation: fadeIn 0.3s ease-out;';
                     document.body.appendChild(toast);
                     setTimeout(() => {
                         toast.style.opacity = '0';
                         setTimeout(() => toast.remove(), 300);
                     }, 3000);
                } else {
                    alert('Failed to save setting. Please try again.');
                     const toggle = document.getElementById('vmo_call_recording_toggle');
                     if(toggle) toggle.checked = !enabled;
                }
            });
        },
        show: function() {
            if (dashboardContainer) {
                dashboardContainer.style.display = 'flex';
            }
        },
        hide: function() {
            if (dashboardContainer) {
                dashboardContainer.style.display = 'none';
            }
        },
        destroy: function() {
            if (dashboardContainer) {
                dashboardContainer.remove();
                dashboardContainer = null;
            }
        },
        
        // Public methods for UI interactions
        handleCSVUpload: function(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    const text = e.target.result;
                    // Simple CSV parser (assumes header row)
                    const lines = text.split('\n');
                    
                    let count = 0;
                    const leads = [];
                    
                    // Parse CSV
                    for(let i = 1; i < lines.length; i++) {
                        if(lines[i].trim()) {
                            const cols = lines[i].split(',');
                            if (cols.length >= 2) {
                                leads.push({
                                    name: cols[0].trim(),
                                    email: cols[1].trim(),
                                    phone: cols[2] ? cols[2].trim() : '',
                                    company: cols[3] ? cols[3].trim() : ''
                                });
                                count++;
                            }
                        }
                    }
                    
                    if (count > 0) {
                        // Send to backend
                        jQuery.post(vmo_ajax_obj.ajax_url, {
                            action: 'vmo_import_leads_csv',
                            nonce: vmo_ajax_obj.nonce,
                            leads: leads
                        }, function(response) {
                            if (response.success) {
                                alert(`Successfully imported ${count} contacts!`);
                                VMOBusinessDashboard.generateLeads(); 
                            } else {
                                alert('Import failed: ' + (response.data.message || 'Unknown error'));
                            }
                        });
                    } else {
                        alert('No valid contacts found in CSV.');
                    }
                };
                
                reader.readAsText(file);
            }
        },

        searchLeads: function() {
            const results = document.getElementById('leads-results');
            results.innerHTML = '<div class="vmo-loading-spinner"></div> Searching for leads...';

            const industry = (document.getElementById('target-industry')?.value || '').trim();
            const companySize = (document.getElementById('company-size')?.value || '').trim();
            const location = (document.getElementById('target-location')?.value || '').trim();
            const keywords = (document.getElementById('target-keywords')?.value || '').trim();
            const search = [industry, companySize, location, keywords].filter(Boolean).join(' ').trim();

            const ajaxURL = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj.ajax_url) ? vmo_ajax_obj.ajax_url : (typeof ajaxurl !== 'undefined' ? ajaxurl : '/wp-admin/admin-ajax.php');
            const nonce = (typeof vmo_ajax_obj !== 'undefined' && vmo_ajax_obj.nonce) ? vmo_ajax_obj.nonce : (typeof vmo_ajax !== 'undefined' ? vmo_ajax.nonce : '');

            jQuery.ajax({
                url: ajaxURL,
                type: 'POST',
                timeout: 30000,
                data: {
                    action: 'vmo_get_leads_data',
                    nonce,
                    search,
                    offset: 0,
                    limit: 50
                },
                success: function(response) {
                if (!response || !response.success) {
                    const msg = response?.data?.message || 'Failed to load leads.';
                    results.innerHTML = `<div class="vmo-empty-state"><p>${msg}</p></div>`;
                    return;
                }

                const leads = Array.isArray(response.data?.leads) ? response.data.leads : [];
                const total = Number(response.data?.total || leads.length || 0);

                let html = `
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; gap:12px; flex-wrap:wrap;">
                        <h3>Found ${total} Lead${total === 1 ? '' : 's'}</h3>
                        <button class="vmo-btn-primary" onclick="VMOBusinessDashboard.emailSelectedContacts()">
                            📧 Email Selected
                        </button>
                    </div>
                `;

                if (!leads.length) {
                    html += `<div class="vmo-empty-state"><p>No leads found. Import contacts via CSV to get started.</p></div>`;
                } else {
                    html += `
                        <table class="vmo-table">
                            <thead>
                                <tr>
                                    <th width="40"><input type="checkbox" onclick="document.querySelectorAll('.vmo-lead-checkbox').forEach(cb => cb.checked = this.checked)"></th>
                                    <th>Company / Contact</th>
                                    <th>Email</th>
                                    <th>Stage</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;

                    leads.forEach(lead => {
                        const name = (lead.full_name || lead.company || 'Contact');
                        const company = (lead.company || '');
                        const email = (lead.email || '');
                        const stage = (lead.lifecycle_stage || 'new');
                        const stageLabel = String(stage).replace(/_/g, ' ');
                        const badgeClass = String(stage).toLowerCase();

                        html += `
                            <tr>
                                <td><input type="checkbox" class="vmo-lead-checkbox"></td>
                                <td>
                                    <strong>${name}</strong>${company && company !== name ? `<br><span style="font-size:12px; color:var(--muted);">${company}</span>` : ''}
                                </td>
                                <td>${email}</td>
                                <td><span class="vmo-badge ${badgeClass}">${stageLabel}</span></td>
                                <td>
                                    <button class="vmo-btn-icon" title="View Details" onclick="(function(){ try{ if(window.VMOBusinessDashboard && typeof VMOBusinessDashboard.showContactDetails==='function'){ VMOBusinessDashboard.showContactDetails(${lead.id}); } }catch(e){} })()">👁️</button>
                                    <button class="vmo-btn-icon" title="Mark as Customer" onclick="(function(){ try{ if(window.VMOBusinessDashboard && typeof VMOBusinessDashboard.markLeadAsCustomer==='function'){ VMOBusinessDashboard.markLeadAsCustomer(${lead.id}); } }catch(e){} })()">✅</button>
                                </td>
                            </tr>
                        `;
                    });

                    html += `</tbody></table>`;
                }

                html += `
                    <!-- CSV Upload Section -->
                    <div class="vmo-csv-upload-section" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1);">
                        <h4>Import Contacts</h4>
                        <p>Upload a CSV file to add leads or customers.</p>
                        <input type="file" id="vmo-csv-upload" accept=".csv" style="display: none;" onchange="VMOBusinessDashboard.handleCSVUpload(this)">
                        <button class="vmo-btn-secondary" onclick="document.getElementById('vmo-csv-upload').click()">
                            📂 Upload CSV
                        </button>
                    </div>
                `;

                results.innerHTML = html;

                const statEl = document.getElementById('total-leads');
                if (statEl) statEl.textContent = String(total);
                },
                error: function() {
                    results.innerHTML = `<div class="vmo-empty-state"><p>Failed to load leads. Please try again.</p></div>`;
                }
            });
        },

        generateLeads: function() {
            this.searchLeads();
        },

        runSEOAudit: function() {
            const container = document.getElementById('seo-recommendations');
            container.innerHTML = '<div class="vmo-loading-spinner"></div> Running comprehensive SEO audit...';
            setTimeout(() => {
                container.innerHTML = `
                    <div class="vmo-audit-results">
                        <div class="vmo-score-card">
                            <div class="score">85</div>
                            <div class="label">SEO Score</div>
                        </div>
                        <div class="vmo-issues-list">
                            <h4>Issues Found</h4>
                            <ul>
                                <li>⚠️ Missing meta description on 3 pages</li>
                                <li>⚠️ H1 tag missing on Contact page</li>
                                <li>✅ Mobile responsiveness is good</li>
                                <li>✅ SSL certificate is valid</li>
                            </ul>
                            <button class="vmo-btn-primary" style="margin-top:10px;">Fix All Issues</button>
                        </div>
                    </div>
                `;
            }, 2000);
        },

        showDocumentType: function(type) {
            const generator = document.getElementById('document-generator');
            const titles = {
                'business-formation': 'Business Formation Documents',
                'contracts': 'Contracts & Agreements',
                'policies': 'Policies & Terms',
                'templates': 'Business Templates'
            };
            
            generator.innerHTML = `
                <h3>${titles[type]}</h3>
                <div class="vmo-doc-options">
                    <div class="vmo-form-group">
                        <label>Select Document</label>
                        <select id="doc-select">
                            <option>Operating Agreement</option>
                            <option>Articles of Organization</option>
                            <option>Meeting Minutes</option>
                        </select>
                    </div>
                    <div class="vmo-form-group">
                        <label>State/Jurisdiction</label>
                        <input type="text" placeholder="e.g., Delaware">
                    </div>
                    <button class="vmo-btn-primary" onclick="alert('Generating document...')">Generate Document</button>
                </div>
            `;
        },

        // Voice consultation system
        startVoiceConsultation: function() {
            console.log('🎯 Starting voice business consultation...');
            $.ajax({
                url: vmo_ajax.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmo_get_consultation_context',
                    security: vmo_ajax.nonce,
                    force_new_session: 1
                },
                success: function(response) {
                    if (response.success) {
                        window.currentConsultationId = response.data.session_id;
                        window.currentConsultationContext = response.data.data || {};

                        // Kick off the elite consultation flow and speak the first question.
                        VMOBusinessDashboard.sendConsultationMessage('Start the business consultation and ask me the first required question.');
                    } else {
                        console.error('Failed to start consultation:', response.data?.message || response.data);
                    }
                },
                error: function() {
                    console.error('Error starting consultation');
                }
            });
        },
        
        sendConsultationMessage: function(message) {
            if (!window.currentConsultationId || !message) return;
            
            $.ajax({
                url: vmo_ajax.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmo_process_consultation_message',
                    security: vmo_ajax.nonce,
                    session_id: window.currentConsultationId,
                    message: message,
                    context: JSON.stringify({
                        consultation_data: window.currentConsultationContext || {}
                    })
                },
                success: function(response) {
                    if (response.success) {
                        const aiText = response.data?.response || '';
                        if (response.data?.consultation_data) {
                            window.currentConsultationContext = response.data.consultation_data;
                        }

                        if (response.data?.isComplete) {
                            VMOBusinessDashboard.speakMessage(aiText);
                            // Refresh KPIs/dashboard after completion.
                            try {
                                if (typeof window.vmoReloadDashboardStats === 'function') {
                                    window.vmoReloadDashboardStats();
                                } else {
                                    document.dispatchEvent(new CustomEvent('vmo:refresh-kpis'));
                                }
                            } catch (_) {}
                        } else {
                            VMOBusinessDashboard.speakMessage(aiText);
                            VMOBusinessDashboard.startListeningForResponse();
                        }
                    } else {
                        console.error('Consultation processing failed:', response.data?.message || response.data);
                    }
                },
                error: function() {
                    console.error('Error sending consultation message');
                }
            });
        },
        
        completeConsultation: function() {
            $.ajax({
                url: vmo_ajax.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmo_complete_consultation',
                    security: vmo_ajax.nonce,
                    consultation_id: window.currentConsultationId
                },
                success: function(response) {
                    if (response.success) {
                        if (response.data.summary_message) {
                            VMOBusinessDashboard.speakMessage(response.data.summary_message);
                        }
                        // Update live preview iframe if website_data exists
                        try {
                            const iframe = document.getElementById('vmo-preview-iframe');
                            const website = response?.data?.website_data;
                            let html = (typeof website?.content === 'string' && website.content.trim())
                                ? website.content.trim()
                                : '';
                            if (!html && typeof website?.main_page === 'string' && website.main_page.trim()) {
                                html = website.main_page.trim();
                            }
                            if (!html && typeof website?.website?.main_page === 'string' && website.website.main_page.trim()) {
                                html = website.website.main_page.trim();
                            }
                            if (iframe && html && !window.vmoPreviewIsLive) {
                                const hasDoc = /<html[\s\S]*<\/html>/i.test(html);
                                if (!hasDoc) {
                                    html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Draft Preview</title><style>body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;padding:24px;line-height:1.6}</style></head><body>${html}</body></html>`;
                                }
                                iframe.srcdoc = html;
                            }
                        } catch (e) { console.warn('Preview iframe refresh failed:', e); }

                        // Refresh KPIs on the strategic dashboard if present
                        try {
                            if (typeof window.vmoReloadDashboardStats === 'function') {
                                window.vmoReloadDashboardStats();
                            } else {
                                // Lightweight fallback: dispatch event others can pick up
                                document.dispatchEvent(new CustomEvent('vmo:refresh-kpis'));
                            }
                        } catch (_) {}
                    }
                }
            });
        },
        
        speakMessage: function(text) {
            // VOICE SYSTEM REMOVED: Voice TTS removed for No Voice version
            // Web Speech API (if available) handles all TTS
            if (window.vmoVoice && window.vmoVoice.speak) {
                window.vmoVoice.speak(text);
            }
        },
        
        startListeningForResponse: function() {
            if (window.vmoVoice && window.vmoVoice.startVoiceToTextTranscription) {
                // Use voice-to-text for consultation responses
                window.vmoVoice.startVoiceToTextTranscription();
                // Set up listener for when transcription completes
                const checkForResponse = setInterval(() => {
                    const inputValue = document.getElementById('consulting-input')?.value || document.getElementById('vmo-prompt-input')?.value;
                    if (inputValue && inputValue.trim()) {
                        clearInterval(checkForResponse);
                        VMOBusinessDashboard.sendConsultationMessage(inputValue.trim());
                        // Clear the input
                        if (document.getElementById('consulting-input')) document.getElementById('consulting-input').value = '';
                        if (document.getElementById('vmo-prompt-input')) document.getElementById('vmo-prompt-input').value = '';
                    }
                }, 1000);
            }
        },
        
        // Individual function implementations would go here
        startSEOAudit: function() {
            console.log('🔍 Starting SEO Audit...');
            // Implementation for SEO audit
        },
        
        generateLeads: function() {
            this.searchLeads();
        },
        
        createCampaign: function() {
            if (typeof window.vmoOpenEmailTool === 'function') {
                window.vmoOpenEmailTool();
            }
        },
        
        generateDocument: function() {
            try {
                if (typeof this.showDocumentType === 'function') {
                    this.showDocumentType('templates');
                }
            } catch (e) {}
        },
        
        // Launch Email Campaign creator (in-page, no external links)
        createEmailCampaign: function(){ openEmailCampaignModal(); },
        
        // Business Execution Roadmap methods
        completeActivity: completeActivity,
        refreshRoadmap: loadRoadmapProgress,

        // ═══════════════════════════════════════════════════════════════
        // PAYMENTS & TAX PUBLIC METHODS
        // ═══════════════════════════════════════════════════════════════

        changeTaxPeriod: function(period) {
            loadTaxSummary();
        },

        onTaxCountryChange: function(countryCode, presetState) {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
            const stateContainer = document.getElementById('vmo-state-container');
            const stateSelect = document.getElementById('vmo-tax-state');
            const stateLabel = document.getElementById('vmo-state-label');

            if (!countryCode) {
                if (stateContainer) stateContainer.style.display = 'none';
                return;
            }

            // Fetch country tax rates
            fetch(apiRoot + 'vmo-builder/v1/tax/rates', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ country: countryCode })
            })
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                const info = data.data;
                window._vmoTaxCurrency = info.currency || 'USD';

                // Show state/province selector if applicable
                if (info.has_states && info.available_states) {
                    if (stateContainer) stateContainer.style.display = 'block';
                    if (stateLabel) stateLabel.textContent = 'State';
                    if (stateSelect) {
                        stateSelect.innerHTML = '<option value="">— Select State —</option>';
                        info.available_states.forEach(s => {
                            const opt = document.createElement('option');
                            opt.value = s.code;
                            opt.textContent = s.name;
                            stateSelect.appendChild(opt);
                        });
                        if (presetState) stateSelect.value = presetState;
                    }
                } else if (info.has_provinces && info.available_provinces) {
                    if (stateContainer) stateContainer.style.display = 'block';
                    if (stateLabel) stateLabel.textContent = 'Province';
                    if (stateSelect) {
                        stateSelect.innerHTML = '<option value="">— Select Province —</option>';
                        info.available_provinces.forEach(p => {
                            const opt = document.createElement('option');
                            opt.value = p.code;
                            opt.textContent = p.name;
                            stateSelect.appendChild(opt);
                        });
                        if (presetState) stateSelect.value = presetState;
                    }
                } else {
                    if (stateContainer) stateContainer.style.display = 'none';
                }
            })
            .catch(e => console.warn('Tax rates load error:', e));
        },

        onTaxStateChange: function(stateCode) {
            // State changed — will recalculate when user clicks Calculate
        },

        saveTaxSettings: function() {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
            const country = document.getElementById('vmo-tax-country')?.value || '';
            const state = document.getElementById('vmo-tax-state')?.value || '';
            const filing = document.getElementById('vmo-filing-status')?.value || 'single';

            fetch(apiRoot + 'vmo-builder/v1/tax/settings', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ country: country, state: state, filing_status: filing })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    // Reload summary with new settings
                    loadTaxSummary();
                    alert('Tax settings saved successfully!');
                }
            })
            .catch(e => console.warn('Save tax settings error:', e));
        },

        calculateTax: function(useActual) {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
            const country = document.getElementById('vmo-tax-country')?.value;
            const state = document.getElementById('vmo-tax-state')?.value || '';
            const filing = document.getElementById('vmo-filing-status')?.value || 'single';
            const period = document.getElementById('vmo-tax-period')?.value || 'year';

            if (!country) {
                alert('Please select your country first.');
                return;
            }

            const payload = {
                country: country,
                state: state,
                filing_status: filing,
                use_actual_revenue: useActual,
                period: period,
            };

            if (!useActual) {
                payload.gross_income = parseFloat(document.getElementById('vmo-calc-income')?.value || 0);
                payload.expenses = parseFloat(document.getElementById('vmo-calc-expenses')?.value || 0);
                if (payload.gross_income <= 0) {
                    alert('Please enter your gross income.');
                    return;
                }
            }

            // Show loading
            const taxEl = document.getElementById('vmo-tax-amount');
            if (taxEl) taxEl.textContent = '...';

            fetch(apiRoot + 'vmo-builder/v1/tax/calculate', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    alert(data.message || 'Tax calculation failed');
                    return;
                }
                const te = data.data;
                const cur = te.currency || 'USD';
                window._vmoTaxCurrency = cur;
                const fmt = (v) => {
                    const sym = cur === 'GBP' ? '£' : cur === 'EUR' ? '€' : cur === 'JPY' ? '¥' : '$';
                    return sym + parseFloat(v || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                };

                // Update cards
                const grossEl = document.getElementById('vmo-tax-gross');
                const expEl = document.getElementById('vmo-tax-expenses');
                const netEl = document.getElementById('vmo-tax-net');
                const rateEl = document.getElementById('vmo-tax-rate');

                if (grossEl) grossEl.textContent = fmt(te.gross_income);
                if (expEl) expEl.textContent = fmt(te.total_expenses);
                if (netEl) netEl.textContent = fmt(te.net_profit);
                if (taxEl) taxEl.textContent = fmt(te.total_tax);
                if (rateEl) rateEl.textContent = 'Effective: ' + (te.effective_rate || 0) + '%';

                // Render breakdown
                renderTaxBreakdown(te, cur);
                renderIncomeDistribution(te, cur);

                if (te.indirect_taxes || te.sales_tax) {
                    renderIndirectTaxInfo(te.indirect_taxes, te.sales_tax);
                }
            })
            .catch(e => {
                console.warn('Tax calculation error:', e);
                if (taxEl) taxEl.textContent = '$0.00';
            });
        },

        addExpenseRow: function() {
            const container = document.getElementById('vmo-expenses-list');
            if (!container) return;

            // If it has the placeholder text, clear it
            if (container.querySelector('p') && !container.querySelector('.vmo-expense-row')) {
                container.innerHTML = '<div style="display:flex;flex-direction:column;gap:8px;"></div>';
            }

            const wrapper = container.querySelector('div') || container;
            const categories = {
                'software': '💻', 'marketing': '📢', 'hosting': '🌐', 'supplies': '📦',
                'travel': '✈️', 'office': '🏢', 'insurance': '🛡️', 'professional': '👔',
                'utilities': '⚡', 'other': '📎'
            };

            let catOptions = '';
            Object.keys(categories).forEach(cat => {
                catOptions += '<option value="' + cat + '">' + categories[cat] + ' ' + cat.charAt(0).toUpperCase() + cat.slice(1) + '</option>';
            });

            const row = document.createElement('div');
            row.className = 'vmo-expense-row';
            row.style.cssText = 'display:grid;grid-template-columns:40px 1fr 1fr auto auto;gap:8px;align-items:center;padding:8px 12px;background:rgba(255,255,255,0.03);border-radius:8px;';
            row.innerHTML = '<span style="font-size:1.3rem;">📎</span>' +
                '<input type="text" placeholder="Description" class="vmo-exp-desc" style="padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;">' +
                '<select class="vmo-exp-cat" style="padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;">' + catOptions + '</select>' +
                '<input type="number" placeholder="0.00" class="vmo-exp-amount" style="width:100px;padding:6px;border-radius:6px;background:#0f172a;color:#e2e8f0;border:1px solid rgba(255,255,255,0.1);font-size:0.9rem;text-align:right;">' +
                '<button onclick="this.closest(\'.vmo-expense-row\').remove()" style="padding:4px 8px;border-radius:6px;background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.3);cursor:pointer;font-size:0.8rem;">✕</button>';
            wrapper.appendChild(row);
        },

        saveExpenses: function() {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
            const rows = document.querySelectorAll('.vmo-expense-row');
            const expenses = [];
            rows.forEach(row => {
                const desc = row.querySelector('.vmo-exp-desc')?.value || '';
                const cat = row.querySelector('.vmo-exp-cat')?.value || 'other';
                const amount = parseFloat(row.querySelector('.vmo-exp-amount')?.value || 0);
                if (amount > 0 || desc) {
                    expenses.push({ description: desc, category: cat, amount: amount, date: new Date().toISOString().split('T')[0] });
                }
            });

            fetch(apiRoot + 'vmo-builder/v1/tax/expenses', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ expenses: expenses })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    alert('Expenses saved! (' + data.saved + ' items)');
                    loadTaxSummary();
                }
            })
            .catch(e => console.warn('Save expenses error:', e));
        },

        runAITaxAnalysis: function() {
            const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
            const country = document.getElementById('vmo-tax-country')?.value;
            const state = document.getElementById('vmo-tax-state')?.value || '';
            const income = parseFloat(document.getElementById('vmo-calc-income')?.value || 0);
            const expenses = parseFloat(document.getElementById('vmo-calc-expenses')?.value || 0);

            if (!country) {
                alert('Please select your country first.');
                return;
            }

            if (!confirm('AI Tax Analysis will use tokens. Proceed?')) return;

            const analysisBox = document.getElementById('vmo-ai-tax-analysis');
            const contentBox = document.getElementById('vmo-ai-tax-content');
            if (analysisBox) analysisBox.style.display = 'block';
            if (contentBox) contentBox.textContent = '🤖 Analyzing your tax situation with AI... Please wait...';

            fetch(apiRoot + 'vmo-builder/v1/tax/ai-analysis', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ country: country, state: state, gross_income: income, expenses: expenses })
            })
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    if (contentBox) contentBox.textContent = '❌ ' + (data.message || 'Analysis failed');
                    return;
                }
                if (contentBox) contentBox.textContent = data.data.analysis;
            })
            .catch(e => {
                if (contentBox) contentBox.textContent = '❌ Request failed. Please try again.';
            });
        },
        
        // Add more methods as needed...
        // Help Menu Logic
        toggleHelpMenu: function(e) {
            if (e) e.stopPropagation();
            const dd = document.getElementById('vmo-help-dropdown');
            if (dd) {
                const isOpen = dd.style.display === 'block';
                dd.style.display = isOpen ? 'none' : 'block';
                
                // One-time close listener
                if (!isOpen) {
                    const closeFn = function(ev) {
                        if (!dd.contains(ev.target) && ev.target !== e.target) {
                            dd.style.display = 'none';
                            document.removeEventListener('click', closeFn);
                        }
                    };
                    setTimeout(() => document.addEventListener('click', closeFn), 10);
                }
            }
        },

        handleHelpAction: function(action, e) {
            if (e) {
                e.preventDefault();
                e.stopPropagation();
            }
            // Close menu
            const dd = document.getElementById('vmo-help-dropdown');
            if (dd) dd.style.display = 'none';

            if (action === 'ticket') {
                this.showFuturisticModal('🎫 New Support Ticket', `
                    <div class="vmo-ticket-form">
                        <div style="margin-bottom:15px;">
                            <label style="display:block; color:#94a3b8; font-size:12px; margin-bottom:5px;">Subject</label>
                            <input type="text" placeholder="Brief description of issue" style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid #334155; border-radius:6px; color:white;">
                        </div>
                        <div style="margin-bottom:15px;">
                            <label style="display:block; color:#94a3b8; font-size:12px; margin-bottom:5px;">Priority</label>
                            <select style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid #334155; border-radius:6px; color:white;">
                                <option>Low</option>
                                <option>Medium</option>
                                <option>High</option>
                                <option>Critical</option>
                            </select>
                        </div>
                        <div style="margin-bottom:20px;">
                            <label style="display:block; color:#94a3b8; font-size:12px; margin-bottom:5px;">Message</label>
                            <textarea rows="5" placeholder="Describe your issue..." style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid #334155; border-radius:6px; color:white; resize:vertical;"></textarea>
                        </div>
                        <div style="text-align:right;">
                            <button class="vmo-btn-primary" onclick="this.closest('.vmo-modal').remove(); alert('Ticket #8492 Created! Agent will reply shortly.');">Submit Ticket</button>
                        </div>
                    </div>
                `);
            } else if (action === 'suggestion') {
                this.showFuturisticModal('💡 Submit Suggestion', `
                    <div class="vmo-suggestion-form">
                        <p style="color:#cbd5e1; margin-bottom:15px;">Help us improve VMO! What feature would you like to see?</p>
                        <textarea rows="4" placeholder="I wish VMO could..." style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid #334155; border-radius:6px; color:white; margin-bottom:20px;"></textarea>
                        <div style="text-align:right;">
                            <button class="vmo-btn-primary" onclick="this.closest('.vmo-modal').remove(); alert('Thank you! Your suggestion has been sent to our product team.');">Send Idea</button>
                        </div>
                    </div>
                `);
            } else if (action === 'faq') {
                this.showFuturisticModal('📚 Knowledge Base', `
                    <div class="vmo-faq-list">
                        <div class="vmo-faq-item" style="margin-bottom:10px; border:1px solid #334155; border-radius:8px; overflow:hidden;">
                            <div class="vmo-faq-q" style="padding:12px; background:rgba(255,255,255,0.05); cursor:pointer; font-weight:600;" onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none'">▶ How do I start building?</div>
                            <div class="vmo-faq-a" style="display:none; padding:12px; color:#cbd5e1; border-top:1px solid #334155;">
                                Click the "Start Consultation" button. Jarvis will ask you about your business and generate the site automatically.
                            </div>
                        </div>
                        <div class="vmo-faq-item" style="margin-bottom:10px; border:1px solid #334155; border-radius:8px; overflow:hidden;">
                            <div class="vmo-faq-q" style="padding:12px; background:rgba(255,255,255,0.05); cursor:pointer; font-weight:600;" onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none'">▶ Where is the support phone number?</div>
                            <div class="vmo-faq-a" style="display:none; padding:12px; color:#cbd5e1; border-top:1px solid #334155;">
                                As a modern AI platform, we prioritize digital support first. Our AI agents can solve 99% of configuration issues instantly. If you need human assistance for a critical billing or legal issue, a callback option will be presented in the ticket system.
                            </div>
                        </div>
                        <div class="vmo-faq-item" style="margin-bottom:10px; border:1px solid #334155; border-radius:8px; overflow:hidden;">
                            <div class="vmo-faq-q" style="padding:12px; background:rgba(255,255,255,0.05); cursor:pointer; font-weight:600;" onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none'">▶ How do I export documents?</div>
                            <div class="vmo-faq-a" style="display:none; padding:12px; color:#cbd5e1; border-top:1px solid #334155;">
                                Go to the "Documents" tab. All generated plans (Marketing, SEO, Business Plan) can be downloaded as PDF.
                            </div>
                        </div>
                    </div>
                `);
            }
        },

        showFuturisticModal: function(title, content) {
            const modalId = 'vmo-modal-' + Math.random().toString(36).substr(2, 9);
            const html = `
                <div id="${modalId}" class="vmo-modal" style="
                    display:flex; 
                    position:fixed; 
                    top:0; left:0; width:100%; height:100%; 
                    background:rgba(0,0,0,0.6); 
                    backdrop-filter:blur(5px); 
                    z-index:10000; 
                    align-items:center; 
                    justify-content:center;
                ">
                    <div class="vmo-modal-content" style="
                        background: #0f172a; 
                        border: 1px solid #334155; 
                        width:90%; max-width:600px; 
                        border-radius:16px; 
                        box-shadow:0 25px 50px -12px rgba(0,0,0,0.5); 
                        overflow:hidden;
                        animation: vmoSlideUp 0.3s ease-out;
                    ">
                        <div class="vmo-modal-header" style="
                            padding:20px; 
                            border-bottom:1px solid #334155; 
                            display:flex; justify-content:space-between; align-items:center;
                            background: rgba(255,255,255,0.02);
                        ">
                            <h3 style="margin:0; font-size:18px; color:white;">${title}</h3>
                            <button onclick="document.getElementById('${modalId}').remove()" style="background:none; border:none; color:#94a3b8; font-size:24px; cursor:pointer;">×</button>
                        </div>
                        <div class="vmo-modal-body" style="padding:20px; color:#e2e8f0;">
                            ${content}
                        </div>
                    </div>
                </div>
                <style>
                    @keyframes vmoSlideUp {
                        from { opacity:0; transform:translateY(20px); }
                        to { opacity:1; transform:translateY(0); }
                    }
                </style>
            `;
            document.body.insertAdjacentHTML('beforeend', html);
        },

        closePremiumModal: function() {
            const modal = document.getElementById('vmo-premium-modal');
            if (modal) modal.remove();
        },

        // Legacy Call Support (Preserved for Jarvis/API usage)
        callSupport: function() {
            const $ = jQuery;
            // Check if event exists (sometimes called directly)
            let btn = null;
            try {
                if (typeof event !== 'undefined' && event && event.currentTarget) {
                    btn = $(event.currentTarget);
                }
            } catch(e) {}
            
            if (btn && btn.length) {
                const originalText = btn.html();
                btn.html('<span class="vmo-spinner">⏳</span> Connecting...');
                btn.prop('disabled', true);
            }

            const ajaxUrl = (typeof vmo_ajax !== 'undefined') ? vmo_ajax.ajaxurl : '/wp-admin/admin-ajax.php';
            const nonce = (typeof vmo_ajax !== 'undefined') ? (vmo_ajax.nonce || vmo_ajax.builder_nonce) : '';

            $.post(ajaxUrl, {
                action: 'vmo_get_user_business_phone', 
                security: nonce
            }).done(function(response) {
                if (response.success && response.data.phone_number) {
                    window.location.href = 'tel:' + response.data.phone_number;
                } else {
                    alert('No business line provisioned yet. Please complete the Phone Setup in Phase 3.');
                }
            }).fail(function() {
                alert('Could not connect to service provider.');
            }).always(function() {
                if (btn && btn.length) { // restore button if it existed
                    // Recalculate original text or just reset
                     btn.prop('disabled', false);
                     if (btn.text().indexOf('Connecting') > -1) btn.html('📞 Call Support'); 
                }
            });
        },

        // Graceful no-op while payments are disabled
        upgradePlan: function(plan) {
            if (typeof window.vmo_ajax !== 'undefined' && window.vmo_ajax.payments_enabled === false) {
                alert('Payments are temporarily disabled. This will be available soon.');
                return;
            }
            // If enabled in the future, delegate to the plans module/button
            const $btn = jQuery(`.vmo-plan-btn[data-plan="${plan}"]`);
            if ($btn.length) {
                $btn.trigger('click');
            } else {
                // Fallback to AJAX if plan button not present
                if (typeof vmo_ajax !== 'undefined') {
                    jQuery.post(vmo_ajax.ajaxurl, { action:'vmo_create_checkout', security: vmo_ajax.nonce, plan }, function(res){
                        if (res && res.success && res.data && res.data.url) {
                            window.location.href = res.data.url;
                        } else {
                            console.warn('Checkout unavailable:', res?.data?.message || 'Unknown error');
                        }
                    });
                }
            }
        },

    // --- AFFILIATE FUNCTIONS (MASTER ADMIN) ---
    loadAffiliateData: function() {
        const container = document.getElementById('vmo-section-affiliates');
        
        // Master Dashboard Layout
        container.innerHTML = `
            <div class="vmo-dashboard-header">
                <div style="display:flex; justify-content:space-between; align-items:flex-end;">
                    <div>
                        <h1>Master Administration</h1>
                        <p>Affiliates & User Management</p>
                    </div>
                    <div style="display:flex; gap:10px;">
                        <button class="vmo-btn-secondary active" onclick="VMOBusinessDashboard.switchAdminTab('affiliates', this)">Affiliates</button>
                        <button class="vmo-btn-secondary" onclick="VMOBusinessDashboard.switchAdminTab('users', this)">User Management</button>
                    </div>
                </div>
            </div>

            <div id="vmo-admin-tab-affiliates" class="vmo-admin-tab active">
                 <div class="vmo-glass-panel" style="margin-bottom:20px; display:flex; justify-content:space-between; align-items:center;">
                    <div>
                        <h3>Affiliate Partners</h3>
                        <p style="opacity:0.6;">Manage partners, view commissions, and track milestones.</p>
                    </div>
                    <button class="vmo-btn-primary" onclick="VMOBusinessDashboard.openCreateAffiliateModal()">+ New Affiliate</button>
                </div>
                <div id="vmo-affiliates-table-container">
                    <span class="vmo-spinner"></span> Loading Affiliates...
                </div>
            </div>

            <div id="vmo-admin-tab-users" class="vmo-admin-tab" style="display:none;">
                 <div class="vmo-glass-panel" style="margin-bottom:20px;">
                    <h3>User Base</h3>
                    <div style="display:flex; gap:10px; margin-top:10px;">
                        <input type="text" id="vmo-user-search" placeholder="Search users, emails..." style="background:rgba(0,0,0,0.3); border:1px solid rgba(255,255,255,0.1); padding:8px; color:#fff; border-radius:4px; flex:1;">
                        <select id="vmo-user-filter-plan" style="background:rgba(0,0,0,0.3); border:1px solid rgba(255,255,255,0.1); padding:8px; color:#fff; border-radius:4px;">
                            <option value="">All Plans</option>
                            <option value="premium">Premium</option>
                            <option value="free">Unpaid Users</option>
                        </select>
                        <button class="vmo-btn-secondary" onclick="VMOBusinessDashboard.loadUsersList()">Filter</button>
                    </div>
                </div>
                <div id="vmo-users-table-container">
                    <span class="vmo-spinner"></span> Loading Users...
                </div>
            </div>
        `;

        VMOBusinessDashboard.loadAffiliatesList();
    },

    switchAdminTab: function(tab, btn) {
        document.querySelectorAll('.vmo-admin-tab').forEach(el => el.style.display = 'none');
        document.querySelectorAll('.vmo-dashboard-header .vmo-btn-secondary').forEach(el => el.classList.remove('active'));
        if(btn) btn.classList.add('active');
        document.getElementById(`vmo-admin-tab-${tab}`).style.display = 'block';
        if(tab === 'users') { VMOBusinessDashboard.loadUsersList(); } else { VMOBusinessDashboard.loadAffiliatesList(); }
    },

    loadAffiliatesList: function() {
        const container = document.getElementById('vmo-affiliates-table-container');
        jQuery.post(vmo_ajax.ajaxurl, { action: 'vmo_get_affiliates_admin', security: vmo_ajax.nonce }, function(response) {
            if(!response.success) { container.innerHTML = `<div class="vmo-alert error">${response.data.message||'Error'}</div>`; return; }
            const list = response.data.affiliates || [];
            if(list.length===0) { container.innerHTML = `<div class="vmo-glass-panel" style="padding:40px;text-align:center;">No affiliates found.</div>`; return; }
            container.innerHTML = `
                <table class="vmo-table" style="width:100%; border-collapse:collapse;">
                    <thead><tr style="text-align:left; border-bottom:1px solid rgba(255,255,255,0.1);">
                        <th style="padding:12px;">Partner</th><th style="padding:12px;">Code</th><th style="padding:12px;">Location</th>
                        <th style="padding:12px;">Ref. Count</th><th style="padding:12px;">Commissions</th><th style="padding:12px;">Awards</th><th style="padding:12px;">Status</th>
                    </tr></thead>
                    <tbody>${list.map(aff => `
                        <tr style="border-bottom:1px solid rgba(255,255,255,0.05); cursor:pointer;">
                            <td style="padding:12px;"><strong>${aff.name}</strong><br><span style="opacity:0.6;font-size:11px;">${aff.email}</span></td>
                            <td style="padding:12px;"><code style="background:rgba(255,255,255,0.1);padding:2px 6px;">${aff.referral_code}</code></td>
                            <td style="padding:12px;">${aff.location||'-'}</td>
                            <td style="padding:12px;font-weight:bold;">${aff.referral_count}</td>
                            <td style="padding:12px;color:#10b981;">$${parseFloat(aff.total_earnings||0).toFixed(2)}</td>
                            <td style="padding:12px;color:#fbbf24;">${aff.milestone_awards>0 ? '🏆 $'+aff.milestone_awards : '-'}</td>
                            <td style="padding:12px;"><span style="color:#10b981;">● Active</span></td>
                        </tr>`).join('')}</tbody></table>`;
        });
    },

    loadUsersList: function() {
        const container = document.getElementById('vmo-users-table-container');
        jQuery.post(vmo_ajax.ajaxurl, { 
            action: 'vmo_get_users_admin', security: vmo_ajax.nonce,
            filter_plan: document.getElementById('vmo-user-filter-plan')?.value
        }, function(response) {
             if(!response.success) { container.innerHTML = `<div class="vmo-alert error">${response.data.message||'Error'}</div>`; return; }
            const list = response.data.users || [];
             container.innerHTML = `
                <table class="vmo-table" style="width:100%; border-collapse:collapse;">
                    <thead><tr style="text-align:left; border-bottom:1px solid rgba(255,255,255,0.1);">
                        <th style="padding:12px;">User</th><th style="padding:12px;">Joined</th><th style="padding:12px;">Plan</th>
                        <th style="padding:12px;">Referred By</th><th style="padding:12px;">Details</th><th style="padding:12px;">Actions</th>
                    </tr></thead>
                    <tbody>${list.map(u => `
                        <tr style="border-bottom:1px solid rgba(255,255,255,0.05);">
                            <td style="padding:12px;"><strong>${u.name}</strong><br><span style="opacity:0.6;font-size:11px;">${u.email}</span></td>
                            <td style="padding:12px;">${new Date(u.joined).toLocaleDateString()}</td>
                            <td style="padding:12px;"><span class="vmo-badge">${u.plan}</span></td>
                            <td style="padding:12px;">${u.ref_code!=='-'?'<code style="color:#d8b4fe;">'+u.ref_code+'</code>':'-'}</td>
                            <td style="padding:12px;font-size:11px;">${u.domain}<br>${u.phone}</td>
                            <td style="padding:12px;"><button class="vmo-btn-secondary small-btn" onclick="VMOBusinessDashboard.openUserActions(${u.id})">Manage</button></td>
                        </tr>`).join('')}</tbody></table>`;
        });
    },
    
    openCreateAffiliateModal: function() {
        const email = prompt("Enter email of existing user to activate as affiliate:");
        if(email) {
            jQuery.post(vmo_ajax.ajaxurl, { action: 'vmo_create_affiliate_manual', security: vmo_ajax.nonce, email }, function(res){
                alert(res.success ? 'Success! Code: ' + res.data.code : 'Error: ' + res.data.message);
                if(res.success) VMOBusinessDashboard.loadAffiliatesList();
            });
        }
    },

    openUserActions: function(userId) {
        const action = prompt("Action for User ID "+userId+":\n1. Give 50% Discount\n2. Add 1000 Tokens\n3. Mark Founding Member\n4. Forgive Tokens\n\nEnter number:");
        if(action) alert('Processing action ID: '+action+' (Mock)');
    },

    // Load campaigns data
    loadCampaignsData: function() {
        const list = document.getElementById('campaigns-list');
        if (list) {
            // Gentle prompt if empty
            const hasItems = list.querySelector('.vmo-campaign-item');
            if (!hasItems) {
                const msg = document.createElement('p');
                msg.style.color = '#4a5568';
                msg.textContent = 'Use "Create New Campaign" to generate 4 AI-crafted email templates and send to your leads.';
                // Clear previous simple placeholder once
                const ps = list.querySelectorAll('p'); ps.forEach((p,i)=>{ if(i===0) p.remove(); });
                list.appendChild(msg);
            }
        }
    }
};
})();

    // --- VMO Strategic helpers (modals + export) to support dashboard pages that load this script ---
    (function(){
    // Avoid redefining if the Strategic Dashboard template already provided these
    const has = (name)=> typeof window[name] === 'function';
    const ajaxURL = (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl) ? vmo_ajax.ajaxurl : ((typeof ajaxurl !== 'undefined' && ajaxurl) ? ajaxurl : '/wp-admin/admin-ajax.php');
    const nonce = (typeof vmo_ajax !== 'undefined' && vmo_ajax.nonce) ? vmo_ajax.nonce : (window.VMO_NONCE || '');
    const qs = (obj)=> new URLSearchParams(obj);
    function ajaxPost(action, extra){
        const body = qs(Object.assign({ action, security: nonce, nonce }, extra||{}));
        return fetch(ajaxURL, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body })
            .then(r=>r.json());
    }
    function ensureBasicModal(id, title){
        let m = document.getElementById(id);
        if (m) return m;
        m = document.createElement('div');
        m.id = id;
        m.style.position='fixed'; m.style.inset='0'; m.style.display='none'; m.style.alignItems='center'; m.style.justifyContent='center'; m.style.zIndex='100000';
        m.innerHTML = '<div class="vmo-modal-overlay" style="position:absolute;inset:0;background:rgba(0,0,0,.72)"></div>'+
            '<div class="vmo-modal-panel" style="position:relative;width:min(920px,96vw);max-height:88vh;overflow:auto;background:#0b1117;border:1px solid rgba(255,255,255,.12);border-radius:16px;padding:18px 20px;box-shadow:0 10px 40px rgba(0,0,0,.6)">'+
            '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px"><h3 style="margin:0;color:#65f1ff">'+(title||'Info')+'</h3><button type="button" data-close="'+id+'" style="background:none;border:none;color:#9fb2c8;font-size:20px;cursor:pointer">&times;</button></div>'+
            '<div class="vmo-modal-body" style="color:#e6f3ff;white-space:pre-wrap;line-height:1.55"></div></div>';
        document.body.appendChild(m);
        document.addEventListener('click', function(e){
            const t = e.target; if (t && (t.getAttribute('data-close')===id || t.classList.contains('vmo-modal-overlay'))) { m.style.display='none'; }
        });
        return m;
    }

    async function showContactDetails(contactId) {
        if (!contactId) return;
        const modal = ensureBasicModal('__vmoContactDetails', '👤 Contact Details');
        const body = modal.querySelector('.vmo-modal-body');
        if (body) body.textContent = 'Loading…';
        modal.style.display = 'flex';
        try {
            const res = await ajaxPost('vmo_get_crm_contact_details', { contact_id: contactId });
            if (!res || !res.success) {
                if (body) body.textContent = (res && res.data && res.data.message) ? res.data.message : 'Failed to load contact.';
                return;
            }
            const c = res.data?.contact || {};
            const calls = Array.isArray(res.data?.calls) ? res.data.calls : [];
            const purchases = Array.isArray(res.data?.purchases) ? res.data.purchases : [];

            let txt = '';
            txt += `Name: ${c.name || '—'}\n`;
            txt += `Email: ${c.email || '—'}\n`;
            txt += `Phone: ${c.phone || '—'}\n`;
            txt += `Company: ${c.company || '—'}\n`;
            txt += `Stage: ${c.lifecycle_stage || '—'}\n`;
            txt += `Tags: ${c.tags || '—'}\n`;
            txt += `Notes: ${c.notes || '—'}\n`;
            txt += `Created: ${c.created_at || '—'}\n`;

            if (calls.length) {
                txt += `\nRecent Interactions:\n`;
                calls.slice(0, 10).forEach((it) => {
                    txt += `- ${it.interaction_type || 'interaction'}: ${(it.summary || it.subject || '').toString().slice(0, 120)} (${it.created_at || ''})\n`;
                });
            }

            if (purchases.length) {
                txt += `\nRecent Purchases:\n`;
                purchases.slice(0, 10).forEach((p) => {
                    txt += `- ${p.product_service || 'purchase'}: ${p.amount || ''} ${p.currency || ''} (${p.status || ''})\n`;
                });
            }

            if (body) body.textContent = txt || 'No details available.';
        } catch (e) {
            if (body) body.textContent = 'Failed to load contact.';
        }
    }

    async function markLeadAsCustomer(contactId) {
        if (!contactId) return;
        if (!confirm('Mark this contact as a customer?')) return;
        try {
            const res = await ajaxPost('vmo_mark_as_customer', { contact_id: contactId });
            if (!res || !res.success) {
                alert((res && res.data && res.data.message) ? res.data.message : 'Failed to update contact.');
                return;
            }
            // Refresh the leads list to reflect the stage change
            if (window.VMOBusinessDashboard && typeof window.VMOBusinessDashboard.searchLeads === 'function') {
                window.VMOBusinessDashboard.searchLeads();
            }
        } catch (e) {
            alert('Failed to update contact.');
        }
    }

    // Expose helper methods on VMOBusinessDashboard if present
    try {
        if (typeof window.VMOBusinessDashboard === 'object' && window.VMOBusinessDashboard) {
            if (typeof window.VMOBusinessDashboard.showContactDetails !== 'function') {
                window.VMOBusinessDashboard.showContactDetails = showContactDetails;
            }
            if (typeof window.VMOBusinessDashboard.markLeadAsCustomer !== 'function') {
                window.VMOBusinessDashboard.markLeadAsCustomer = markLeadAsCustomer;
            }
        }
    } catch (e) {}
    async function downloadUrl(url, filename){
        const res = await fetch(url, { credentials:'include' });
        const blob = await res.blob();
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = filename;
        document.body.appendChild(a); a.click(); a.remove();
        setTimeout(()=>URL.revokeObjectURL(a.href), 1500);
    }

        function loadScript(src){
                return new Promise((resolve, reject) => {
                        const s = document.createElement('script');
                        s.src = src;
                        s.async = true;
                        s.onload = () => resolve(true);
                        s.onerror = () => reject(new Error('Failed to load ' + src));
                        document.head.appendChild(s);
                });
        }

        async function ensureHtml2Pdf(){
                if (window.html2pdf) return true;
                try {
                        const baseUrl = (typeof vmo_ajax !== 'undefined' && vmo_ajax.plugin_url) ? vmo_ajax.plugin_url : '';
                        await loadScript(baseUrl + 'assets/vendor/html2pdf.bundle.min.js');
                        return !!window.html2pdf;
                } catch (e) {
                        return false;
                }
        }

        function createHiddenPrintContainer(html){
                const wrap = document.createElement('div');
                wrap.style.position = 'fixed';
                wrap.style.left = '-10000px';
                wrap.style.top = '0';
                wrap.style.width = '900px';
                wrap.style.background = 'white';
                wrap.innerHTML = html;
                document.body.appendChild(wrap);
                return wrap;
        }

        function fmtDate(iso){
                if (!iso) return '';
                const t = Date.parse(String(iso).replace(' ', 'T'));
                return Number.isNaN(t) ? String(iso) : new Date(t).toLocaleDateString();
        }

        function escapeHtml(s){
                return String(s || '')
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;');
        }

        function progressSummaryLine(progress){
                const pct = Math.round(progress?.progress_percentage || 0);
                const exp = Math.round(progress?.expected_percentage || 0);
                const health = (progress?.schedule_health || 'tracking').replace(/_/g, ' ');
                const days = Number.isFinite(progress?.days_ahead_behind) ? progress.days_ahead_behind : 0;
                const daysTxt = days >= 0 ? `+${days} days ahead` : `${days} days behind`;
                return `${pct}% complete (expected ${exp}%) • ${health} • ${daysTxt}`;
        }

        function buildRoadmapReportHtml({ businessName, progress, roadmapData }){
                const now = new Date().toLocaleString();
                const milestones = Array.isArray(roadmapData) ? roadmapData : (roadmapData?.milestones || []);

                const pct = Math.round(progress?.progress_percentage || 0);
                const exp = Math.round(progress?.expected_percentage || 0);
                const barW = (n)=> Math.max(0, Math.min(100, n));
                const svgBar = `
                        <svg width="100%" height="42" viewBox="0 0 600 42" role="img" aria-label="Progress vs Expected">
                            <rect x="0" y="8" width="600" height="10" fill="#e5e7eb" rx="5" />
                            <rect x="0" y="8" width="${6*barW(exp)}" height="10" fill="#93c5fd" rx="5" />
                            <rect x="0" y="24" width="600" height="10" fill="#e5e7eb" rx="5" />
                            <rect x="0" y="24" width="${6*barW(pct)}" height="10" fill="#22c55e" rx="5" />
                            <text x="0" y="7" font-size="10" fill="#374151">Expected: ${exp}%</text>
                            <text x="0" y="23" font-size="10" fill="#374151">Actual: ${pct}%</text>
                        </svg>
                `;

                const rows = milestones.map((m, idx) => {
                        const title = escapeHtml(m.title || m.milestone_title || `Milestone ${idx+1}`);
                        const week = escapeHtml(m.week_number || m.week || '');
                        const objective = escapeHtml(m.objective || '');
                        const deliverables = escapeHtml(m.deliverables || '');
                        const metrics = escapeHtml(m.success_metrics || m.kpis || '');
                        const priority = escapeHtml(m.priority || '');
                        return `<tr>
                                <td>${week}</td>
                                <td><strong>${title}</strong><br/><span class="muted">${objective}</span></td>
                                <td>${deliverables}</td>
                                <td>${metrics}</td>
                                <td>${priority}</td>
                        </tr>`;
                }).join('');

                const textIllustration = `
            Business Execution Timeline (text-based)
            ${milestones.slice(0, 8).map((m,i)=>{
              const wk = m.week_number || m.week || (i+1);
              const t = (m.title || m.milestone_title || '').toString().slice(0, 52);
              return 'Week ' + wk + ': ' + t;
            }).join('\n')}
                `.trim();

                return `
                <div class="page">
                    <h1>Business Execution Roadmap</h1>
                    <div class="meta">${escapeHtml(businessName || 'Your Business')} • Generated ${escapeHtml(now)}</div>
                    <div class="card">
                        <div class="kpi">
                            <div class="label">Schedule Status</div>
                            <div class="value">${escapeHtml(progressSummaryLine(progress))}</div>
                        </div>
                        <div style="margin-top:10px">${svgBar}</div>
                    </div>

                    <div class="card">
                        <h2>Illustration</h2>
                        <pre class="mono">${escapeHtml(textIllustration)}</pre>
                    </div>

                    <div class="card">
                        <h2>Milestones (Table)</h2>
                        <table>
                            <thead>
                                <tr>
                                    <th style="width:70px">Week</th>
                                    <th>Milestone</th>
                                    <th>Deliverables</th>
                                    <th>Success Metrics</th>
                                    <th style="width:70px">Priority</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${rows || '<tr><td colspan="5" class="muted">No milestones found.</td></tr>'}
                            </tbody>
                        </table>
                    </div>
                </div>
                <style>
                    .page{ font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif; color:#111827; }
                    h1{ margin:0 0 6px 0; font-size:22px; }
                    h2{ margin:0 0 10px 0; font-size:15px; color:#111827; }
                    .meta{ color:#6b7280; font-size:12px; margin-bottom:12px; }
                    .card{ border:1px solid #e5e7eb; border-radius:10px; padding:12px; margin-bottom:12px; }
                    .kpi .label{ font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:.04em; }
                    .kpi .value{ font-size:13px; margin-top:4px; }
                    .mono{ font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,'Liberation Mono','Courier New',monospace; font-size:11px; background:#f9fafb; border:1px solid #e5e7eb; padding:10px; border-radius:8px; white-space:pre-wrap; }
                    table{ width:100%; border-collapse:collapse; font-size:11px; }
                    th,td{ border-bottom:1px solid #e5e7eb; padding:8px; vertical-align:top; }
                    th{ text-align:left; color:#374151; background:#f9fafb; }
                    .muted{ color:#6b7280; }
                </style>
                `;
        }

        function parseTs(x){
            if (!x) return NaN;
            return Date.parse(String(x).replace(' ', 'T'));
        }

        function classifyActivity(a, roadmapCreatedAt){
                const status = (a.status || 'pending').toString();
            const type = (a.activity_type || '').toString().toLowerCase();
            const isResearchType = type.includes('research') || type.includes('market') || type.includes('benchmark') || type.includes('competitor') || type.includes('trend') || type.includes('update');

            // Tightened detection:
            // - completed always wins
            // - research-added if created_at is clearly after roadmap creation (grace window avoids tagging the initial batch)
            // - fallback to type only if timestamps are missing
            const graceMs = 30 * 60 * 1000; // 30 minutes
            const baseMs = parseTs(roadmapCreatedAt);
            const createdMs = parseTs(a.created_at);
            const timestampIndicatesResearch = Number.isFinite(baseMs) && Number.isFinite(createdMs) && (createdMs > (baseMs + graceMs));

                if (status === 'completed') return { key:'completed', label:'Completed', color:'#dcfce7', border:'#22c55e' };
            if (timestampIndicatesResearch) return { key:'research', label:'Research-added', color:'#fef9c3', border:'#eab308' };
            if (!Number.isFinite(baseMs) || !Number.isFinite(createdMs)) {
                if (isResearchType) return { key:'research', label:'Research-added', color:'#fef9c3', border:'#eab308' };
            }
                return { key:'pending', label:'Pending', color:'#e5e7eb', border:'#64748b' };
        }

        function buildDailyActivitiesReportHtml({ businessName, progress, activities, roadmapCreatedAt }){
                const now = new Date().toLocaleString();
                const list = Array.isArray(activities) ? activities : [];
                const sorted = list.slice().sort((a,b)=>{
                        const da = Date.parse((a.activity_date||'').toString().replace(' ', 'T'));
                        const db = Date.parse((b.activity_date||'').toString().replace(' ', 'T'));
                        return (Number.isNaN(da)?0:da) - (Number.isNaN(db)?0:db);
                });

                const legend = `
                    <div class="legend">
                        <span class="chip" style="background:#dcfce7;border-color:#22c55e">Completed</span>
                        <span class="chip" style="background:#fef9c3;border-color:#eab308">Research-added</span>
                        <span class="chip" style="background:#e5e7eb;border-color:#64748b">Pending</span>
                    </div>
                `;

                const rows = sorted.map((a)=>{
                    const cls = classifyActivity(a, roadmapCreatedAt);
                        const title = escapeHtml(a.activity_title || a.title || '');
                        const date = escapeHtml(fmtDate(a.activity_date || a.expected_complete_by || ''));
                        const day = escapeHtml(a.day_number || '');
                        const mins = escapeHtml(a.estimated_duration_minutes || '');
                        const notes = escapeHtml(a.completion_notes || '');
                        return `<tr style="background:${cls.color}">
                            <td>${date}</td>
                            <td>Day ${day}</td>
                            <td><strong>${title}</strong><div class="muted">${escapeHtml(a.activity_description || '')}</div></td>
                            <td>${escapeHtml(cls.label)}</td>
                            <td>${mins ? mins + ' min' : ''}</td>
                            <td>${notes}</td>
                        </tr>`;
                }).join('');

                return `
                <div class="page">
                    <h1>Daily Activities Plan</h1>
                    <div class="meta">${escapeHtml(businessName || 'Your Business')} • Generated ${escapeHtml(now)}</div>

                    <div class="card">
                        <div class="kpi">
                            <div class="label">Schedule Status</div>
                            <div class="value">${escapeHtml(progressSummaryLine(progress))}</div>
                        </div>
                        ${legend}
                    </div>

                    <div class="card">
                        <h2>Activities (Dated List)</h2>
                        <table>
                            <thead>
                                <tr>
                                    <th style="width:95px">Date</th>
                                    <th style="width:70px">Day</th>
                                    <th>Activity</th>
                                    <th style="width:120px">Status</th>
                                    <th style="width:85px">Time</th>
                                    <th style="width:150px">Notes</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${rows || '<tr><td colspan="6" class="muted">No activities found.</td></tr>'}
                            </tbody>
                        </table>
                    </div>
                </div>
                <style>
                    .page{ font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif; color:#111827; }
                    h1{ margin:0 0 6px 0; font-size:22px; }
                    h2{ margin:0 0 10px 0; font-size:15px; color:#111827; }
                    .meta{ color:#6b7280; font-size:12px; margin-bottom:12px; }
                    .card{ border:1px solid #e5e7eb; border-radius:10px; padding:12px; margin-bottom:12px; }
                    .kpi .label{ font-size:11px; color:#6b7280; text-transform:uppercase; letter-spacing:.04em; }
                    .kpi .value{ font-size:13px; margin-top:4px; }
                    .legend{ display:flex; gap:8px; flex-wrap:wrap; margin-top:10px; }
                    .chip{ display:inline-block; padding:4px 8px; border:1px solid; border-radius:999px; font-size:11px; color:#111827; }
                    table{ width:100%; border-collapse:collapse; font-size:11px; }
                    th,td{ border-bottom:1px solid #e5e7eb; padding:8px; vertical-align:top; }
                    th{ text-align:left; color:#374151; background:#f9fafb; }
                    .muted{ color:#6b7280; font-size:10px; margin-top:4px; }
                </style>
                `;
        }

        async function downloadPdfFromHtml(html, filename){
                const ok = await ensureHtml2Pdf();
                const container = createHiddenPrintContainer(html);
                try {
                        if (ok && window.html2pdf) {
                                const opt = {
                                        margin: 0.4,
                                        filename,
                                        image: { type: 'jpeg', quality: 0.98 },
                                        html2canvas: { scale: 2, useCORS: true },
                                        jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
                                };
                                await window.html2pdf().set(opt).from(container).save();
                        } else {
                                // Fallback: open as HTML for user to Print → Save as PDF
                                const w = window.open('', '_blank');
                                if (w) {
                                        w.document.open();
                                        w.document.write('<!doctype html><html><head><meta charset="utf-8"><title>'+escapeHtml(filename)+'</title></head><body>'+html+'</body></html>');
                                        w.document.close();
                                        w.focus();
                                } else {
                                        alert('PDF library unavailable and popup blocked.');
                                }
                        }
                } finally {
                        container.remove();
                }
        }

        async function downloadRoadmapPDF(){
                try {
                        const progRes = await ajaxPost('vmo_get_progress_tracking');
                        if (!progRes || !progRes.success || !progRes.data?.has_roadmap) {
                                alert('No roadmap found yet. Complete Phase 4 to generate it.');
                                return;
                        }
                        const progress = progRes.data.progress || {};
                const roadmapMetaRes = await ajaxPost('vmo_get_business_roadmap');
                const roadmapId = roadmapMetaRes?.data?.roadmap_id || '';
                const roadmapRes = await ajaxPost('vmo_download_business_roadmap', { roadmap_id: roadmapId, format: 'json' });
                        if (!roadmapRes || !roadmapRes.success) {
                                alert(roadmapRes?.data?.message || 'Failed to load roadmap data.');
                                return;
                        }

                        const businessName = (document.querySelector('#vmo-business-dashboard .vmo-dashboard-logo p')?.textContent || '').trim();
                        const html = buildRoadmapReportHtml({ businessName, progress, roadmapData: roadmapRes.data.roadmap });
                        await downloadPdfFromHtml(html, 'VMO-Business-Roadmap.pdf');
                } catch (e) {
                        alert('Roadmap export failed.');
                }
        }

        async function downloadDailyActivitiesPDF(){
                try {
                        const progRes = await ajaxPost('vmo_get_progress_tracking');
                        if (!progRes || !progRes.success || !progRes.data?.has_roadmap) {
                                alert('No roadmap found yet. Complete Phase 4 to generate it.');
                                return;
                        }
                        const progress = progRes.data.progress || {};

                        // Need roadmap_id to load activities
                        const roadmapRes = await ajaxPost('vmo_get_business_roadmap');
                        const roadmapId = roadmapRes?.data?.roadmap_id || '';
                const roadmapCreatedAt = roadmapRes?.data?.roadmap_created_at || null;
                        if (!roadmapId) {
                                alert('Could not determine active roadmap.');
                                return;
                        }

                const actsRes = await ajaxPost('vmo_download_daily_activities', { roadmap_id: roadmapId, format: 'json' });
                        if (!actsRes || !actsRes.success) {
                                alert(actsRes?.data?.message || 'Failed to load daily activities.');
                                return;
                        }

                        const businessName = (document.querySelector('#vmo-business-dashboard .vmo-dashboard-logo p')?.textContent || '').trim();
                const baseline = actsRes?.data?.roadmap_created_at || roadmapCreatedAt || null;
                const html = buildDailyActivitiesReportHtml({ businessName, progress, activities: actsRes.data.activities || [], roadmapCreatedAt: baseline });
                        await downloadPdfFromHtml(html, 'VMO-Daily-Activities.pdf');
                } catch (e) {
                        alert('Daily Activities export failed.');
                }
        }

        // Expose PDF downloads on the dashboard module
        try {
                if (typeof window.VMOBusinessDashboard === 'object' && window.VMOBusinessDashboard) {
                        if (typeof window.VMOBusinessDashboard.downloadRoadmapPDF !== 'function') {
                                window.VMOBusinessDashboard.downloadRoadmapPDF = downloadRoadmapPDF;
                        }
                        if (typeof window.VMOBusinessDashboard.downloadDailyActivitiesPDF !== 'function') {
                                window.VMOBusinessDashboard.downloadDailyActivitiesPDF = downloadDailyActivitiesPDF;
                        }
                }
        } catch (e) {}
    if (!has('showWeeklyBriefing')) {
        window.showWeeklyBriefing = function(){
            const existing = document.getElementById('weeklyModal');
            const modal = existing || ensureBasicModal('__vmoWeekly', '📊 Weekly Strategic Briefing');
            const body = (existing ? document.getElementById('vmo-brief-analysis') : modal.querySelector('.vmo-modal-body'));
            if (body) body.textContent = 'Loading…';
            ajaxPost('vmo_get_weekly_briefing').then(({success,data})=>{
                const txt = (success && data) ? ((data.analysis||data.summary||'No analysis available')) : 'No current research available.';
                if (body) body.textContent = txt;
            }).catch(()=>{ if(body) body.textContent='Failed to load.'; });
            if (window.vmoModalUtils && existing) { vmoModalUtils.open(existing); }
            else { (existing||modal).style.display='flex'; }
        };
    }
    if (!has('regenerateRoadmap')) {
        window.regenerateRoadmap = function(){
            ajaxPost('vmo_regenerate_roadmap').then(({success,message})=>{
                if (!success) { alert(message||'Failed to regenerate roadmap'); return; }
                alert('Roadmap updated');
            }).catch(e=>alert('Error: '+e.message));
        };
    }
    if (!has('exportProgress')) {
        window.exportProgress = function(){
            ajaxPost('vmo_export_progress_pdf').then(async ({success,data,message})=>{
                if (success && data && data.url) {
                    try { await downloadUrl(data.url, 'VMO-Progress-Report.pdf'); return; } catch(err) { /* fallback */ }
                }
                return ajaxPost('vmo_export_progress').then(async ({success,data,message})=>{
                    if (!success || !data || !data.url) { alert(message||'Export failed'); return; }
                    try { await downloadUrl(data.url, 'VMO-Progress-Report.html'); } catch(err){ alert('Download failed'); }
                });
            }).catch(e=>alert('Export error: '+e.message));
        };
    }

    // Optional: dedicated Full Analysis modal (distinct from Weekly Briefing)
    if (!has('showFullAnalysis')) {
        window.showFullAnalysis = function(){
            const id='__vmoFullAnalysis';
            const modal = ensureBasicModal(id, '📑 Weekly Full Analysis');
            const body = modal.querySelector('.vmo-modal-body');
            if (body) body.textContent = 'Loading…';
            ajaxPost('vmo_get_weekly_full_analysis').then(({success,data})=>{
                if (success && data) {
                    if (body) body.textContent = data.analysis || 'No analysis available yet.';
                } else {
                    if (body) body.textContent = 'No analysis available.';
                }
            }).catch(()=>{ if(body) body.textContent = 'Failed to load.'; });
            modal.style.display='flex';
        };
    }


    // Email Selected Contacts
    VMOBusinessDashboard.emailSelectedContacts = function() {
        // 1. Gather selected contacts
        const selected = [];
        document.querySelectorAll('.vmo-lead-checkbox:checked').forEach(cb => {
            const row = cb.closest('tr');
            const email = row.querySelector('td:nth-child(3)').textContent.trim(); // Assuming email is 3rd column
            const name = row.querySelector('td:nth-child(2)').textContent.trim();
            selected.push({ name, email });
        });

        if (selected.length === 0) {
            alert('Please select at least one contact to email.');
            return;
        }

        // 2. Determine mode (Bulk vs Regular)
        const threshold = 20;
        const useBulk = selected.length > threshold;
        
        if (useBulk) {
            if (confirm(`You have selected ${selected.length} contacts. This will open the Bulk Email Marketing tool. Continue?`)) {
                // Open Bulk Tool
                if (window.vmoOpenEmailTool) {
                    window.vmoOpenEmailTool();
                    // Pass contacts to the bulk tool (simulated)
                    setTimeout(() => {
                        alert(`${selected.length} contacts added to "Selected Leads" recipient group.`);
                    }, 500);
                } else {
                    alert('Bulk Email Tool not loaded.');
                }
            }
        } else {
            // Regular Compose
            if (confirm(`Email ${selected.length} contacts?`)) {
                // Open Compose Modal
                if (window.vmoOpenComposeModal) {
                    window.vmoOpenComposeModal();
                    // Pre-fill recipients
                    const emails = selected.map(c => c.email).join(', ');
                    setTimeout(() => {
                        const toInput = document.getElementById('vmo-compose-to');
                        if (toInput) toInput.value = emails;
                    }, 300);
                }
            }
        }
    };
})();

// Webmail Interface Logic
(function() {
    let __vmoLastFolder = 'inbox';
    let __vmoLastEmails = [];

    function vmoEnsureMailViewerModal() {
        let modal = document.getElementById('vmo-mail-viewer-modal');
        if (modal) return modal;
        modal = document.createElement('div');
        modal.id = 'vmo-mail-viewer-modal';
        modal.className = 'vmo-tools-overlay';
        modal.innerHTML = `
            <div class="vmo-modal-content vmo-email-modal" style="max-width: 900px;">
                <div class="vmo-modal-header">
                    <h3 id="vmo-mail-viewer-subject">Email</h3>
                    <button class="vmo-modal-close" type="button" onclick="document.getElementById('vmo-mail-viewer-modal').classList.remove('vmo-show')">×</button>
                </div>
                <div class="vmo-modal-body" style="padding: 16px 20px;">
                    <div style="display:flex; justify-content:space-between; gap:12px; align-items:flex-start; flex-wrap:wrap; margin-bottom:12px;">
                        <div style="color: var(--muted); font-size: 12px;">
                            <div><strong style="color:var(--ink)">From:</strong> <span id="vmo-mail-viewer-from">—</span></div>
                            <div><strong style="color:var(--ink)">To:</strong> <span id="vmo-mail-viewer-to">—</span></div>
                        </div>
                        <div style="color: var(--muted); font-size: 12px; text-align:right;">
                            <div><strong style="color:var(--ink)">Date:</strong> <span id="vmo-mail-viewer-date">—</span></div>
                            <div><strong style="color:var(--ink)">Folder:</strong> <span id="vmo-mail-viewer-folder">—</span></div>
                        </div>
                    </div>
                    <div id="vmo-mail-viewer-body" style="background: rgba(255,255,255,.02); border: 1px solid var(--border); border-radius: 10px; padding: 14px; max-height: 420px; overflow: auto;"></div>
                    <div style="display:flex; justify-content:flex-end; gap:8px; margin-top: 12px; flex-wrap:wrap;">
                        <button id="vmo-mail-viewer-mark-read" type="button" class="action-btn">Mark read</button>
                        <button id="vmo-mail-viewer-trash" type="button" class="action-btn">Move to trash</button>
                        <button type="button" class="action-btn primary" onclick="document.getElementById('vmo-mail-viewer-modal').classList.remove('vmo-show')">Close</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        // click outside closes
        modal.addEventListener('click', function(e) {
            if (e.target === modal) modal.classList.remove('vmo-show');
        });
        return modal;
    }

    async function vmoMailApiFetch(path, opts) {
        const apiRoot = vmoMailApiRoot();
        const url = apiRoot + 'vmo-manager/v1' + path;
        const res = await fetch(url, Object.assign({ headers: vmoMailApiHeaders() }, opts || {}));
        const data = await res.json().catch(() => null);
        if (!data || data.success !== true) {
            const msg = (data && data.message) ? data.message : 'Request failed';
            throw new Error(msg);
        }
        return data;
    }

    async function vmoOpenMailMessage(id) {
        const modal = vmoEnsureMailViewerModal();
        const subjEl = document.getElementById('vmo-mail-viewer-subject');
        const fromEl = document.getElementById('vmo-mail-viewer-from');
        const toEl = document.getElementById('vmo-mail-viewer-to');
        const dateEl = document.getElementById('vmo-mail-viewer-date');
        const folderEl = document.getElementById('vmo-mail-viewer-folder');
        const bodyEl = document.getElementById('vmo-mail-viewer-body');
        const markBtn = document.getElementById('vmo-mail-viewer-mark-read');
        const trashBtn = document.getElementById('vmo-mail-viewer-trash');

        if (subjEl) subjEl.textContent = 'Loading…';
        if (bodyEl) bodyEl.innerHTML = '<div style="color:var(--muted)">Loading…</div>';
        modal.classList.add('vmo-show');

        const data = await vmoMailApiFetch('/emails/' + encodeURIComponent(String(id)), { method: 'GET' });
        const email = data.email || {};
        const subject = (email.subject || '(No subject)').toString();
        const from = (email.from_email || '').toString();
        const to = (email.to_email || '').toString();
        const date = vmoFormatMailDate(email.created_at || '');
        const folder = (email.folder || '').toString();
        const html = (email.message || '').toString();

        if (subjEl) subjEl.textContent = subject;
        if (fromEl) fromEl.textContent = from || '—';
        if (toEl) toEl.textContent = to || '—';
        if (dateEl) dateEl.textContent = date;
        if (folderEl) folderEl.textContent = folder || '—';
        if (bodyEl) bodyEl.innerHTML = html || '<div style="color:var(--muted)">(Empty)</div>';

        if (markBtn) {
            markBtn.onclick = async function() {
                markBtn.disabled = true;
                try {
                    await vmoMailApiFetch('/emails/' + encodeURIComponent(String(id)) + '/read', { method: 'POST' });
                    await vmoSwitchMailFolder(__vmoLastFolder || 'inbox');
                } catch (_) {
                } finally {
                    markBtn.disabled = false;
                }
            };
        }
        if (trashBtn) {
            trashBtn.onclick = async function() {
                trashBtn.disabled = true;
                try {
                    await vmoMailApiFetch('/emails/' + encodeURIComponent(String(id)), { method: 'DELETE' });
                    modal.classList.remove('vmo-show');
                    await vmoSwitchMailFolder(__vmoLastFolder || 'inbox');
                } catch (_) {
                } finally {
                    trashBtn.disabled = false;
                }
            };
        }
    }

    function vmoMailApiRoot() {
        try {
            if (window.wpApiSettings && wpApiSettings.root) return wpApiSettings.root;
        } catch (_) {}
        return (window.location.origin + '/wp-json/');
    }

    function vmoMailApiHeaders() {
        const headers = { 'Content-Type': 'application/json' };
        try {
            if (window.wpApiSettings && wpApiSettings.nonce) headers['X-WP-Nonce'] = wpApiSettings.nonce;
        } catch (_) {}
        return headers;
    }

    function vmoStripHtml(html) {
        try {
            const tmp = document.createElement('div');
            tmp.innerHTML = String(html || '');
            return (tmp.textContent || tmp.innerText || '').trim();
        } catch (_) {
            return String(html || '').replace(/<[^>]*>/g, '').trim();
        }
    }

    function vmoFormatMailDate(input) {
        const raw = (input || '').toString();
        const dt = new Date(raw.replace(' ', 'T'));
        if (!isNaN(dt.getTime())) return dt.toLocaleString();
        return raw || '—';
    }

    function vmoGetSelectedMailboxAccountEmail() {
        try {
            const sel = document.querySelector('.vmo-account-selector');
            const val = sel ? String(sel.value || '').trim() : '';
            return val;
        } catch (_) {
            return '';
        }
    }

    async function vmoLoadMailboxAccounts() {
        const sel = document.querySelector('.vmo-account-selector');
        if (!sel) return;

        const apiRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
        const nonce = (window.wpApiSettings && window.wpApiSettings.nonce) ? window.wpApiSettings.nonce : '';
        const prev = String(sel.value || '');

        try {
            const resp = await fetch(apiRoot + 'vmo-manager/v1/email-accounts', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce }
            });
            const data = await resp.json();
            const accounts = (data && data.success === true && Array.isArray(data.accounts)) ? data.accounts : [];

            if (!accounts.length) {
                // keep existing fallback options
                return;
            }

            sel.innerHTML = '';
            accounts.forEach(a => {
                const email = a && a.email ? String(a.email).trim() : '';
                if (!email) return;
                const labelBits = [email];
                const cat = a && a.category ? String(a.category).trim() : '';
                const name = a && a.display_name ? String(a.display_name).trim() : '';
                if (name) labelBits.push(name);
                if (cat) labelBits.push(cat);
                const opt = document.createElement('option');
                opt.value = email;
                opt.textContent = labelBits.join(' • ');
                sel.appendChild(opt);
            });

            if (prev) {
                const found = Array.from(sel.options).some(o => o.value === prev);
                if (found) sel.value = prev;
            }
            if (!sel.value && sel.options.length) sel.selectedIndex = 0;
        } catch (_) {
            // best-effort: keep fallback options
        }

        if (!sel.__vmoBoundMailboxAccount) {
            sel.__vmoBoundMailboxAccount = true;
            sel.addEventListener('change', function() {
                try { window.vmoRefreshMail && window.vmoRefreshMail(); } catch (_) {}
            });
        }
    }

    async function vmoFetchMails(folder) {
        const apiRoot = vmoMailApiRoot();
        const account = vmoGetSelectedMailboxAccountEmail();
        const url = apiRoot + 'vmo-manager/v1/emails?folder=' + encodeURIComponent(folder || 'inbox') + '&type=all' + (account ? ('&account=' + encodeURIComponent(account)) : '');
        const resp = await fetch(url, { method: 'GET', headers: vmoMailApiHeaders() });
        const data = await resp.json();
        if (!data || data.success !== true) {
            const msg = (data && data.message) ? data.message : 'Failed to load emails';
            throw new Error(msg);
        }
        return Array.isArray(data.emails) ? data.emails : [];
    }

    async function vmoUpdateMailCounts() {
        const inboxBadge = document.getElementById('vmo-inbox-count');
        const draftsBadge = document.getElementById('vmo-drafts-count');
        try {
            if (inboxBadge) {
                const inbox = await vmoFetchMails('inbox');
                const unread = inbox.filter(e => String(e.is_read) === '0' || e.is_read === 0 || e.is_read === false).length;
                inboxBadge.textContent = unread ? String(unread) : String(inbox.length || 0);
            }
        } catch (_) {
            if (inboxBadge) inboxBadge.textContent = '0';
        }
        try {
            if (draftsBadge) {
                const drafts = await vmoFetchMails('drafts');
                draftsBadge.textContent = String(drafts.length || 0);
            }
        } catch (_) {
            if (draftsBadge) draftsBadge.textContent = '0';
        }
    }

    window.vmoSwitchMailFolder = async function(folder) {
        __vmoLastFolder = folder || 'inbox';
        const folderKey = __vmoLastFolder;

        // Update active state in sidebar
        const folderEls = Array.from(document.querySelectorAll('.vmo-folder[data-folder]'));
        folderEls.forEach(el => el.classList.remove('active'));
        const activeFolder = document.querySelector('.vmo-folder[data-folder="' + folderKey + '"]');
        if (activeFolder) activeFolder.classList.add('active');

        // Ensure visible highlight follows active selection (some templates rely on inline styles)
        folderEls.forEach(el => {
            const isActive = el.classList.contains('active');
            el.style.background = isActive ? 'rgba(255,255,255,0.05)' : 'transparent';
            el.style.color = isActive ? 'var(--ink)' : 'var(--muted)';
        });

        // Update title
        const titleEl = document.getElementById('vmo-current-folder-title');
        if (titleEl) titleEl.textContent = folderKey.charAt(0).toUpperCase() + folderKey.slice(1);

        // Show loading
        const listEl = document.getElementById('vmo-mail-list');
        if (!listEl) return;
        listEl.innerHTML = '<div style="padding:20px; text-align:center; color:var(--muted);">Loading…</div>';

        try {
            const emails = await vmoFetchMails(folderKey);
            __vmoLastEmails = emails;

            const render = (items) => {
                if (!items.length) {
                    listEl.innerHTML = `
                        <div style="display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%; color:var(--muted); padding:40px;">
                            <div style="font-size:48px; margin-bottom:16px; opacity:0.3;">📭</div>
                            <p>No messages in ${folderKey}</p>
                        </div>
                    `;
                    return;
                }
                listEl.innerHTML = items.map(email => {
                    const from = (email.from_email || email.from || '').toString();
                    const subject = (email.subject || '').toString();
                    const date = vmoFormatMailDate(email.created_at || email.date || '');
                    const preview = vmoStripHtml(email.message || email.preview || '').slice(0, 160);
                    const isUnread = (String(email.is_read) === '0' || email.is_read === 0 || email.is_read === false);
                    const eid = (email.id != null) ? String(email.id) : '';
                    return `
                        <div data-email-id="${eid}" style="padding:12px; border-bottom:1px solid var(--border); background:rgba(255,255,255,0.02); cursor:pointer;" title="Open message">
                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                <strong style="color:var(--ink); font-size:13px;">${from || '—'}</strong>
                                <span style="color:var(--muted); font-size:11px;">${date}</span>
                            </div>
                            <div style="color:var(--cyan-soft); font-size:12px; font-weight:${isUnread ? '800' : '600'}; margin-bottom:2px;">${subject || '(No subject)'}</div>
                            <div style="color:var(--muted); font-size:11px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${preview || ''}</div>
                        </div>
                    `;
                }).join('');

                // bind open handlers
                Array.prototype.forEach.call(listEl.querySelectorAll('[data-email-id]'), function(row) {
                    if (row.__vmoBound) return;
                    row.__vmoBound = true;
                    row.addEventListener('click', function() {
                        const id = row.getAttribute('data-email-id');
                        if (!id) return;
                        vmoOpenMailMessage(id).catch(() => {});
                    });
                });
            };

            render(emails);

            // Bind search (in-page filter only)
            const searchEl = document.getElementById('vmo-mail-search');
            if (searchEl && !searchEl.__vmoBound) {
                searchEl.__vmoBound = true;
                searchEl.addEventListener('input', function() {
                    const q = (searchEl.value || '').toString().trim().toLowerCase();
                    if (!q) {
                        render(__vmoLastEmails);
                        return;
                    }
                    const filtered = (__vmoLastEmails || []).filter(e => {
                        const from = (e.from_email || e.from || '').toString().toLowerCase();
                        const subj = (e.subject || '').toString().toLowerCase();
                        const msg = vmoStripHtml(e.message || e.preview || '').toLowerCase();
                        return from.includes(q) || subj.includes(q) || msg.includes(q);
                    });
                    render(filtered);
                });
            }

            // Update badges opportunistically
            vmoUpdateMailCounts();
        } catch (err) {
            listEl.innerHTML = '<div style="padding:20px; text-align:center; color:var(--muted);">Failed to load emails</div>';
        }
    };

    window.vmoOpenComposeModal = function(recipients = []) {
        // Check if modal exists
        let modal = document.getElementById('vmo-compose-modal');
        
        // If modal exists (from tools-modals.php), use it
        if (modal) {
            // Populate recipients if provided
            const toInput = document.getElementById('vmo-compose-to');
            if (toInput && Array.isArray(recipients) && recipients.length > 0) {
                toInput.value = recipients.join(', ');
            } else if (toInput && typeof recipients === 'string') {
                toInput.value = recipients;
            }

            // Sync the compose-modal "From:" selector with the sidebar account list
            try {
                const composeSel = document.getElementById('vmo-compose-from');
                const sidebarSel = document.querySelector('.vmo-account-selector');
                if (composeSel && sidebarSel && sidebarSel.options.length) {
                    const currentVal = composeSel.value;
                    composeSel.innerHTML = '';
                    Array.from(sidebarSel.options).forEach(opt => {
                        const o = document.createElement('option');
                        o.value = opt.value;
                        o.textContent = opt.textContent;
                        composeSel.appendChild(o);
                    });
                    // Preserve previous selection if it still exists
                    const found = Array.from(composeSel.options).some(o => o.value === currentVal);
                    if (found) composeSel.value = currentVal;
                    else if (sidebarSel.value) composeSel.value = sidebarSel.value;
                }
            } catch (e) { /* non-critical */ }
            
            // Show the modal using the class defined in tools-modals.php
            modal.classList.add('vmo-show');
            return;
        }

        // Fallback: Create simple modal if the rich one isn't loaded
        modal = document.createElement('div');
        modal.id = 'vmo-compose-modal';
        modal.className = 'vmo-modal'; 
        const toValue = Array.isArray(recipients) ? recipients.join(', ') : (recipients || '');
        
        modal.innerHTML = `
            <div class="modal-content" style="width:600px; max-width:95vw;">
                <div class="modal-header">
                    <h3 class="modal-title">New Message</h3>
                    <button class="modal-close" onclick="document.getElementById('vmo-compose-modal').classList.remove('show')">×</button>
                </div>
                <div class="modal-body">
                    <div style="display:flex; flex-direction:column; gap:12px;">
                        <input type="text" id="vmo-compose-to" placeholder="To" value="${toValue}" style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid var(--border); color:var(--ink); border-radius:6px;">
                        <input type="text" id="vmo-compose-subject" placeholder="Subject" style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid var(--border); color:var(--ink); border-radius:6px;">
                        <textarea id="vmo-compose-body" placeholder="Write your message..." rows="10" style="width:100%; padding:10px; background:rgba(0,0,0,0.2); border:1px solid var(--border); color:var(--ink); border-radius:6px; resize:vertical;"></textarea>
                        <div style="display:flex; justify-content:flex-end; gap:8px; margin-top:8px;">
                            <button class="action-btn" onclick="document.getElementById('vmo-compose-modal').classList.remove('show')">Discard</button>
                            <button class="action-btn primary" onclick="alert('Message sent!'); document.getElementById('vmo-compose-modal').classList.remove('show')">Send</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        setTimeout(() => modal.classList.add('show'), 10);
    };

    window.vmoRefreshMail = function() {
        const activeFolder = document.querySelector('.vmo-folder.active');
        const folder = activeFolder ? (activeFolder.getAttribute('data-folder') || __vmoLastFolder || 'inbox') : (__vmoLastFolder || 'inbox');
        vmoSwitchMailFolder(folder);
    };

    // Load mailbox accounts (best-effort) once UI is ready.
    try {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', vmoLoadMailboxAccounts);
        } else {
            vmoLoadMailboxAccounts();
        }
    } catch (_) {}
})();

    window.vmoToggleAutoReply = function(checkbox) {
        const enabled = checkbox.checked;
        const account = document.querySelector('.vmo-account-selector')?.value || 'primary';
        
        // In a real implementation, this would save to the backend
        console.log('AI Auto-Reply for ' + account + ': ' + (enabled ? 'ON' : 'OFF'));
        
        if (enabled) {
            // Show toast
            const toast = document.createElement('div');
            toast.textContent = '🤖 AI Auto-Reply Enabled for ' + account;
            toast.style.cssText = 'position:fixed; bottom:20px; right:20px; background:#0fe1ff; color:#000; padding:10px 20px; border-radius:8px; z-index:10000; font-weight:bold; box-shadow:0 5px 15px rgba(0,0,0,0.3);';
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
    };

    /**
     * VMO Open Power Dialer Interface
     * Opens the Autonomous Robo Sales Strategy Control Panel
     */
window.VMOBusinessDashboard.openPowerDialer = function() {
        console.log('Opening Autonomous Robo Sales Interface...');
        
        // Remove existing modal if any
        const existing = document.getElementById('vmo-power-dialer-modal');
        if (existing) existing.remove();

        // Get Balance
        const balance = (typeof currentUser !== 'undefined' && currentUser.balance) ? currentUser.balance : '—';
        
        // --- HELPER STATES ---
        window.vmoPDState = {
            leads: [],
            audioBlob: null,
            audioURL: null,
            scriptGenerated: false,
            speakerOn: false
        };

        // Load Campaign (Attempt to restore from localStorage)
        try {
            const saved = localStorage.getItem('vmo_pd_campaign');
            if (saved) {
                const data = JSON.parse(saved);
                if (data.goal) setTimeout(() => { if(document.getElementById('pd-goal')) document.getElementById('pd-goal').value = data.goal; }, 500);
                if (data.intent) setTimeout(() => { if(document.getElementById('pd-intent')) document.getElementById('pd-intent').value = data.intent; }, 500);
                if (data.script) setTimeout(() => { if(document.getElementById('pd-strategy-prompt')) document.getElementById('pd-strategy-prompt').value = data.script; }, 500);
                if (data.leads) window.vmoPDState.leads = data.leads;
            }
        } catch(e) { console.log('No saved campaign'); }

        // Save Campaign Helper
        window.vmoPD_SaveCampaign = function() {
            const data = {
                goal: document.getElementById('pd-goal') ? document.getElementById('pd-goal').value : '',
                intent: document.getElementById('pd-intent') ? document.getElementById('pd-intent').value : '',
                script: document.getElementById('pd-strategy-prompt') ? document.getElementById('pd-strategy-prompt').value : '',
                leads: window.vmoPDState.leads
            };
            localStorage.setItem('vmo_pd_campaign', JSON.stringify(data));
        };
        // Auto-save on specific actions like generation or switching tabs
        
        // --- HELPER FUNCTIONS (Attached to window for inline onclick access) ---

        // PHASE 1: SCRIPT GENERATION
        window.vmoPD_GenerateScript = function() {
            const intent = document.getElementById('pd-intent').value;
            const goal = document.getElementById('pd-goal').value;
            const output = document.getElementById('pd-strategy-prompt');
            const btn = document.querySelector('.vmo-pd-gen-btn');

            if (!intent || !goal) {
                alert('Please enter both User Intent and End Goal.');
                return;
            }

            // UI Loading State
            btn.innerHTML = '<span class="vmo-spinner"></span> Generating...';
            btn.disabled = true;
            output.value = "Accessing VMO Sales Matrix... Analyzing Intent... Constructing Script...";

            // Simulate AI Delay
            setTimeout(() => {
                const script = `Server: VMO-AI-Sales-Core v4.2
Context: ${intent}
Objective: ${goal}
---------------------------------------------------

[OPENING - THE HOOK]
"Hi, this is [Your Name] calling from [My Company]. I know I'm catching you out of the blue, but I saw your business online and had to reach out about ${intent}."

[THE BRIDGE]
"We've been helping businesses like yours achieve ${goal} using our new automated system. Is that something you'd be open to hearing about for 30 seconds?"

[THE PROBLEM/AGITATE]
"Most owners tell us they struggle with [Pain Point related to ${intent}]. It's costing them time and money."

[THE SOLUTION]
"We've fixed this by [Unique Selling Proposition]. It's not just a service, it's a complete system."

[THE CLOSE]
"I'm not asking for a commitment now, just a chance to show you the math. Are you available tomorrow morning for a 10-minute demo?"

[OBJECTION HANDLING]
If 'Not Interested': "That's fair. Before I go, can I just ask..."
If 'Send Email': "I certainly can, but the demo speaks louder than a PDF..."`;

                output.value = script;
                btn.innerHTML = '✨ Regenerate Script';
                btn.disabled = false;
                window.vmoPDState.scriptGenerated = true;
                window.vmoPD_SaveCampaign(); // Auto-save
            }, 2000);
        };

        // PHASE 2: RECORDER
        let mediaRecorder;
        let audioChunks = [];

        window.vmoPD_StartRecord = function(btn) {
            navigator.mediaDevices.getUserMedia({ audio: true })
                .then(stream => {
                    mediaRecorder = new MediaRecorder(stream);
                    mediaRecorder.start();
                    audioChunks = [];

                    mediaRecorder.addEventListener("dataavailable", event => {
                        audioChunks.push(event.data);
                    });

                    mediaRecorder.addEventListener("stop", () => {
                        window.vmoPDState.audioBlob = new Blob(audioChunks, { type: 'audio/mp3' });
                        window.vmoPDState.audioURL = URL.createObjectURL(window.vmoPDState.audioBlob);
                        
                        // Update UI to "Recorded" state
                        document.getElementById('pd-recorder-controls').style.display = 'none';
                        document.getElementById('pd-player-controls').style.display = 'flex';
                    });

                    // UI Updates
                    btn.classList.add('recording');
                    document.getElementById('rec-text').textContent = 'Recording... Tap to Stop';
                    btn.setAttribute('onclick', 'vmoPD_StopRecord(this)');
                })
                .catch(err => {
                    alert('Microphone access denied or not available: ' + err.message);
                });
        };

        window.vmoPD_StopRecord = function(btn) {
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
                btn.classList.remove('recording');
                // UI transition happens in 'stop' event listener
            }
        };

        window.vmoPD_PlayRecord = function(btn) {
            // Check State
            if (window.vmoPDState.isPlaying && window.vmoPDState.currentAudio) {
                // STOP ACTION
                window.vmoPDState.currentAudio.pause();
                window.vmoPDState.currentAudio.currentTime = 0;
                window.vmoPDState.isPlaying = false;
                
                // Reset Button Icon to Play Triangle
                const icon = btn.querySelector('div');
                icon.style.width = '0'; icon.style.height = '0';
                icon.style.border = 'none'; // Clear previous overrides if any
                icon.style.borderTop = '10px solid transparent';
                icon.style.borderBottom = '10px solid transparent';
                icon.style.borderLeft = '16px solid #fff';
                icon.style.backgroundColor = 'transparent';
                return;
            }

            // PLAY ACTION
            if (window.vmoPDState.audioURL) {
                const audio = new Audio(window.vmoPDState.audioURL);
                window.vmoPDState.currentAudio = audio;
                window.vmoPDState.isPlaying = true;

                // Change Button Icon to Stop Square
                const icon = btn.querySelector('div');
                icon.style.border = 'none';
                icon.style.width = '14px';
                icon.style.height = '14px';
                icon.style.backgroundColor = '#fff';
                icon.style.borderRadius = '2px';

                audio.play();
                
                audio.onended = function() {
                   window.vmoPDState.isPlaying = false;
                   // Reset Icon to Play Triangle
                   icon.style.width = '0'; icon.style.height = '0';
                   icon.style.borderTop = '10px solid transparent';
                   icon.style.borderBottom = '10px solid transparent';
                   icon.style.borderLeft = '16px solid #fff';
                   icon.style.backgroundColor = 'transparent';
                };
            }
        };

        window.vmoPD_DeleteRecord = function() {
            // Stop if playing
            if (window.vmoPDState.isPlaying && window.vmoPDState.currentAudio) {
                window.vmoPDState.currentAudio.pause();
                window.vmoPDState.isPlaying = false;
            }

            window.vmoPDState.audioBlob = null;
            window.vmoPDState.audioURL = null;
            
            // Reset UI
            document.getElementById('pd-recorder-controls').style.display = 'block';
            document.getElementById('pd-player-controls').style.display = 'none';
            const recBtn = document.querySelector('#pd-recorder-controls .vmo-rec-btn');
            recBtn.setAttribute('onclick', 'vmoPD_StartRecord(this)');
            document.getElementById('rec-text').textContent = 'Tap to Record Intro';
        };

        window.vmoPD_UploadLink = function() {
            document.getElementById('pd-audio-upload').click();
        };

        window.vmoPD_HandleAudioUpload = function(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                if (file.type.indexOf('audio') === -1 && !file.name.endsWith('.mp3')) {
                    alert('Please upload a valid audio file (MP3 preferred).');
                    return;
                }
                
                window.vmoPDState.audioBlob = file;
                window.vmoPDState.audioURL = URL.createObjectURL(file);
                
                // Update UI
                document.getElementById('pd-recorder-controls').style.display = 'none';
                document.getElementById('pd-player-controls').style.display = 'flex';
                // Show filename hint
                const hint = document.createElement('div');
                hint.style.fontSize = '10px'; hint.style.color = '#fff'; hint.style.marginTop = '5px';
                hint.textContent = 'File: ' + file.name;
                document.getElementById('pd-player-controls').appendChild(hint);
            }
        };

        // PHASE 3: LEADS
        window.vmoPD_ParseCSV = function(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const text = e.target.result;
                    const lines = text.split('\\n');
                    const leads = [];
                    lines.forEach(line => {
                        const parts = line.split(',');
                        if (parts.length >= 2) {
                            leads.push({
                                name: parts[0].trim(),
                                number: parts[1].trim(),
                                company: parts[2] ? parts[2].trim() : 'Unknown'
                            });
                        }
                    });
                    
                    window.vmoPDState.leads = leads;
                    vmoPD_UpdateLeadUI();
                };
                reader.readAsText(input.files[0]);
            }
        };

        window.vmoPD_MockCRM = function() {
            // Mock Data
            window.vmoPDState.leads = [
                { name: "Sarah Connor", number: "+1 (555) Skynet-1", company: "Cyberdyne Systems" },
                { name: "Tony Stark", number: "+1 (555) Iron-Man", company: "Stark Ind" },
                { name: "Bruce Wayne", number: "+1 (555) Bat-Cave", company: "Wayne Ent" },
                { name: "Peter Parker", number: "+1 (555) Web-Head", company: "Daily Bugle" },
                { name: "Diana Prince", number: "+1 (555) Wonder", company: "The Louvre" }
            ];
            vmoPD_UpdateLeadUI();
        };

        window.vmoPD_UpdateLeadUI = function() {
            const count = window.vmoPDState.leads.length;
            const textarea = document.getElementById('pd-leads-input');
            const summaryCount = document.getElementById('pd-summ-count');
            const summaryTime = document.getElementById('pd-summ-time');
            const summaryCost = document.getElementById('pd-summ-cost');
            const confirmLeads = document.getElementById('confirm-leads'); // For Tab 4

            // Update Textarea
            let text = "";
            window.vmoPDState.leads.forEach(l => {
                text += `${l.name}, ${l.number}, ${l.company}\\n`;
            });
            textarea.value = text;

            // Update Stats
            if(summaryCount) summaryCount.textContent = count;
            if(summaryTime) summaryTime.textContent = (count * 3) + ' mins';
            if(summaryCost) summaryCost.textContent = (count * 0.5) + ' credits';
            if(confirmLeads) confirmLeads.textContent = count;
        };

        // PHASE 4: LAUNCH & MONITOR
        window.vmoPD_TestCall = function() {
            const btn = document.querySelector('button[onclick="vmoPD_TestCall()"]');
            
            // 1. Get Components
            const audioURL = window.vmoPDState.audioURL;
            const scriptText = document.getElementById('pd-strategy-prompt') ? document.getElementById('pd-strategy-prompt').value : '';
            
            if (!scriptText && !audioURL) {
                alert('No script or audio intro recorded. Please go back to Strategy or Voice phases.');
                return;
            }

            // UI Feedback
            if(btn) btn.innerHTML = '⏳ Playing Simulation...';

            // 2. Play Audio First (if Hybrid)
            const playScript = () => {
                if ('speechSynthesis' in window) {
                   // Clean script of instructional text for TTS
                   const speakText = scriptText
                       .replace(/\[.*?\]/g, '') // Remove [Stage Directions]
                       .replace(/Server: VMO-AI-Sales-Core.*/s, '') // Remove Header
                       .trim();

                   if(speakText) {
                       const utterance = new SpeechSynthesisUtterance(speakText.substring(0, 300) + " (Simulation Truncated for brevity)"); // Limit length for test
                       utterance.rate = 1.0;
                       utterance.pitch = 1.0;
                       
                       // Try to find a good voice
                       const voices = window.speechSynthesis.getVoices();
                       const preferredVoice = voices.find(v => v.name.includes('Google US English') || v.name.includes('Samantha'));
                       if (preferredVoice) utterance.voice = preferredVoice;

                       utterance.onend = () => {
                           if(btn) btn.innerHTML = '▶ Test Audio';
                       };

                       window.speechSynthesis.speak(utterance);
                   } else {
                       if(btn) btn.innerHTML = '▶ Test Audio';
                   }
                } else {
                    alert('Text-to-Speech not supported in this browser.');
                    if(btn) btn.innerHTML = '▶ Test Audio';
                }
            };

            if (audioURL) {
                const audio = new Audio(audioURL);
                audio.play();
                audio.onend = () => {
                    // Chain the AI Script after Audio
                    setTimeout(playScript, 500); 
                };
            } else {
                playScript();
            }
        };

        window.vmoPD_LaunchDialer = function() {
            const leads = window.vmoPDState.leads;
            if (leads.length === 0) {
                alert('Please add at least one lead before launching.');
                return;
            }

            const btn = document.querySelector('.vmo-pd-launch-btn');
            if(btn) {
                btn.innerHTML = '<span class="vmo-spinner"></span> Launching...';
                btn.disabled = true;
            }

            // Gather Campaign Data
            const intent = document.getElementById('pd-intent') ? document.getElementById('pd-intent').value : '';
            const goal = document.getElementById('pd-goal') ? document.getElementById('pd-goal').value : '';
            const fullScript = document.getElementById('pd-strategy-prompt') ? document.getElementById('pd-strategy-prompt').value : '';

            // Construct Payload
            const payload = {
                name: 'Auto-Dialer Campaign ' + new Date().toLocaleTimeString(),
                type: 'power_dialer',
                callback_extension: 0,
                opening: fullScript, // sending full script as opening for now
                goal: goal,
                points: intent,
                schedule: { mode: 'now' },
                settings: {
                    amd_enabled: true, // Answering Machine Detection
                    record_calls: true
                },
                contacts: leads.map(l => ({
                    name: l.name,
                    phone: l.number || l.phone,
                    company: l.company
                }))
            };

            // Send to Backend
            console.log('Sending Campaign Payload:', payload);
            // NOTE: /wp-json/* is blocked/rewritten on some deployments. Use allowlisted admin-ajax gateway.
            const ajaxBase = (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl)
                ? vmo_ajax.ajaxurl
                : '/wp-admin/admin-ajax.php';
            const apiUrl = ajaxBase + '?action=vmo_website_chat&kind=pd_campaigns';
            
            const nonce = (typeof vmo_ajax !== 'undefined' && vmo_ajax.nonce) ? vmo_ajax.nonce : '';

            jQuery.ajax({
                url: apiUrl,
                method: 'POST',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', nonce);
                },
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(payload),
                success: function(response) {
                    console.log('Campaign Created:', response);
                    
                    // Close Setup Modal
                    const modal = document.getElementById('vmo-power-dialer-modal');
                    if(modal) modal.remove();

                    // Open Live Monitor
                    vmoPD_OpenLiveMonitor();
                    
                    // Pass Campaign ID to Monitor if needed (future)
                    if(response.campaign_id && window.vmoActiveMonitor) {
                        window.vmoActiveMonitor.setAttribute('data-campaign-id', response.campaign_id);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Campaign Launch Failed:', error);
                    console.log(xhr.responseText);
                    
                    alert('Failed to launch campaign. Server responded: ' + error);
                    
                    if(btn) {
                        btn.innerHTML = '🚀 Launch Autonomous Sales Campaign';
                        btn.disabled = false;
                    }
                }
            });
        };

        window.vmoPD_OpenLiveMonitor = function() {
            const monitor = document.createElement('div');
            monitor.className = 'vmo-fs-modal vmo-modal-visible';
            monitor.style.cssText = 'display:flex; justify-content:center; align-items:center; background:rgba(0,0,0,0.8); z-index:10001;';
            
            // Phone UI
            monitor.innerHTML = `
                <div class="vmo-smartphone" style="width:360px; height:700px; background:#000; border-radius:40px; border:4px solid #333; box-shadow:0 0 50px rgba(15,225,255,0.2); position:relative; overflow:hidden; display:flex; flex-direction:column; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                    
                    <!-- Notch/Top Bar -->
                    <div style="height:30px; display:flex; justify-content:space-between; padding:10px 20px; color:#fff; font-size:12px; z-index:2;">
                        <span>VMO 5G</span>
                        <span>100% 🔋</span>
                    </div>

                    <!-- Screen Content -->
                    <div style="flex:1; display:flex; flex-direction:column; position:relative; z-index:1;">
                        
                        <!-- Header -->
                        <div style="padding:20px; text-align:center;">
                            <div style="font-size:10px; text-transform:uppercase; letter-spacing:2px; color:var(--cyan);">Auto-Dialer Active</div>
                            <h2 style="color:#fff; margin:5px 0; font-weight:300;">Mission In Progress</h2>
                        </div>

                        <!-- Visualizer -->
                        <div style="height:150px; display:flex; align-items:center; justify-content:center; gap:4px;">
                            ${Array(10).fill(0).map(() => `<div class="vmo-wave-bar" style="width:6px; height:20px; background:var(--cyan); border-radius:3px; animation: wave 1s infinite;"></div>`).join('')}
                        </div>

                        <!-- Active Call Info -->
                        <div id="vmo-phone-status" style="text-align:center; padding:20px;">
                            <h1 id="vmo-phone-name" style="color:#fff; font-weight:200; margin:0;">Initializing...</h1>
                            <p id="vmo-phone-number" style="color:#888; margin:5px 0;">...</p>
                            <div id="vmo-phone-timer" style="color:var(--cyan); font-family:monospace; margin-top:10px;">00:00</div>
                        </div>

                        <!-- Queue List (Mini) -->
                        <div style="flex:1; background:rgba(255,255,255,0.05); margin:20px; border-radius:20px; padding:15px; overflow:hidden;">
                            <h4 style="color:#888; font-size:10px; text-transform:uppercase; margin:0 0 10px;">Up Next</h4>
                            <div id="vmo-phone-queue" style="display:flex; flex-direction:column; gap:10px;">
                                <!-- Queue Items Generated Here -->
                            </div>
                        </div>

                        <!-- Controls -->
                        <div style="padding:20px; display:flex; justify-content:space-around; align-items:center;">
                             <div onclick="alert('Muted')" style="width:50px; height:50px; background:rgba(255,255,255,0.1); border-radius:50%; display:flex; align-items:center; justify-content:center; color:#fff; cursor:pointer;">🎤</div>
                             <div onclick="vmoPD_EndSimulation()" style="width:70px; height:70px; background:#ef4444; border-radius:50%; display:flex; align-items:center; justify-content:center; color:#fff; cursor:pointer; font-size:24px; box-shadow:0 10px 20px rgba(239,68,68,0.4);">📞</div>
                             <div onclick="window.vmoPDState.speakerOn = !window.vmoPDState.speakerOn; this.style.opacity = window.vmoPDState.speakerOn ? '1' : '0.5'; alert('Speaker ' + (window.vmoPDState.speakerOn ? 'On' : 'Off'))" style="width:50px; height:50px; background:rgba(255,255,255,0.1); border-radius:50%; display:flex; align-items:center; justify-content:center; color:#fff; cursor:pointer;">🔊</div>
                        </div>
                    </div>
                    
                    <!-- Styles for Visualizer -->
                    <style>
                        @keyframes wave { 0% { height:10px; opacity:0.5; } 50% { height:40px; opacity:1; } 100% { height:10px; opacity:0.5; } }
                        .vmo-wave-bar:nth-child(odd) { animation-duration: 0.8s; }
                        .vmo-wave-bar:nth-child(even) { animation-duration: 1.1s; }
                    </style>
                </div>
            `;
            
            document.body.appendChild(monitor);
            window.vmoActiveMonitor = monitor;
            
            // Start Simulation Logic
            vmoRunDialerMonitor();
        };

        window.vmoRunDialerMonitor = function() {
           const statusText = document.getElementById('vmo-phone-status').querySelector('h1');
           const numberText = document.getElementById('vmo-phone-number');
           const timerText = document.getElementById('vmo-phone-timer');

           statusText.textContent = "Connecting to Satellite...";
           numberText.textContent = "Establishing Uplink";
           
           // Poll Backend for Live Stats
           const monitorInterval = setInterval(() => {
                // Use allowlisted admin-ajax gateway (REST endpoints are often blocked).
                const ajaxBase = (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl)
                    ? vmo_ajax.ajaxurl
                    : '/wp-admin/admin-ajax.php';
                const apiUrl = ajaxBase + '?action=vmo_website_chat&kind=pd_live_calls';
                const nonce = (typeof vmo_ajax !== 'undefined' && vmo_ajax.nonce) ? vmo_ajax.nonce : '';

                jQuery.ajax({
                    url: apiUrl,
                    method: 'GET',
                    beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
                    dataType: 'json',
                    success: function(response) {
                         if(response && response.calls && response.calls.length > 0) {
                             const call = response.calls[0]; // Get first active call
                             statusText.textContent = call.contact_name || call.to_number || 'Deep Research Lead';
                             statusText.style.opacity = '1';
                             numberText.textContent = (call.status || 'dialing').toUpperCase();
                             
                             // Calculate duration
                             if(call.created_at) { 
                                try {
                                    // Parse time (assuming UTC or server time handling matches)
                                    // Simplification: just show "In Progress" or formatted duration from server if available
                                    timerText.textContent = "LIVE CALL";
                                } catch(e) { timerText.textContent = "00:00"; }
                             } else {
                                timerText.textContent = call.duration || "00:00";
                             }

                         } else {
                             // No active calls
                             statusText.textContent = "Campaign Active";
                             statusText.style.opacity = '0.7';
                             numberText.textContent = "Processing Queue...";
                             timerText.textContent = "--:--";
                         }
                    },
                    error: function() {
                         statusText.textContent = "Connection Lost";
                         numberText.textContent = "Retrying...";
                    }
                });
           }, 2000); // Poll every 2 seconds

           // Store interval to clear later
           window.vmoMonitorInterval = monitorInterval;
        };

        window.vmoPD_EndSimulation = function(completed = false) {
             if (window.vmoActiveMonitor) window.vmoActiveMonitor.remove();
             if (window.vmoMonitorInterval) clearInterval(window.vmoMonitorInterval);
             
             if (completed) {
                 alert('✅ Mission Complete! All leads processed.\\n\\nReport generated in Analytics tab.');
             }
        };


        // --- MAIN RENDER LOGIC ---

        // Add specific styles for this modal if not present
        if (!document.getElementById('vmo-pd-styles')) {
            const style = document.createElement('style');
            style.id = 'vmo-pd-styles';
            style.innerHTML = `
                .vmo-pd-tabs { display:flex; border-bottom:1px solid rgba(255,255,255,0.1); margin-bottom:20px; }
                .vmo-pd-tab { padding:14px 20px; color:var(--muted); cursor:pointer; border-bottom:2px solid transparent; flex:1; text-align:center; font-size:13px; font-weight:600; transition:all 0.2s; display:flex; align-items:center; justify-content:center; gap:8px; }
                .vmo-pd-tab:hover { color:#fff; background:rgba(255,255,255,0.02); }
                .vmo-pd-tab.active { color:var(--cyan); border-bottom-color:var(--cyan); background:linear-gradient(180deg, rgba(15,225,255,0.08), transparent); }
                .vmo-pd-content { display:none; animation:fadeIn 0.3s ease; min-height:400px; }
                .vmo-pd-content.active { display:block; }
                .vmo-pd-option { display:block; padding:15px; border:1px solid var(--border); border-radius:8px; background:rgba(255,255,255,0.02); cursor:pointer; transition:all 0.2s; position:relative; }
                .vmo-pd-option:hover { border-color:var(--cyan-soft); background:rgba(15,225,255,0.05); }
                .vmo-pd-option.selected { border-color:var(--cyan); background:rgba(15,225,255,0.1); box-shadow:0 0 15px rgba(15,225,255,0.1); }
                .vmo-pd-option input { position:absolute; top:15px; right:15px; accent-color:var(--cyan); }
                
                .vmo-rec-btn { width:60px; height:60px; border-radius:50%; background:#ef4444; border:4px solid rgba(255,255,255,0.2); cursor:pointer; display:flex; align-items:center; justify-content:center; margin:0 auto; box-shadow:0 10px 30px rgba(239,68,68,0.4); transition:all 0.3s; }
                .vmo-rec-btn:hover { transform:scale(1.05); box-shadow:0 15px 40px rgba(239,68,68,0.6); }
                .vmo-rec-btn.recording { animation: pulseRed 1.5s infinite; }
                @keyframes pulseRed { 0% { box-shadow: 0 0 0 0 rgba(239,68,68, 0.7); } 70% { box-shadow: 0 0 0 20px rgba(239,68,68, 0); } 100% { box-shadow: 0 0 0 0 rgba(239,68,68, 0); } }

                .vmo-play-btn { width:60px; height:60px; border-radius:50%; background:#10b981; border:4px solid rgba(255,255,255,0.2); cursor:pointer; display:flex; align-items:center; justify-content:center; box-shadow:0 10px 30px rgba(16,185,129,0.4); transition:all 0.3s; }
                .vmo-play-btn:hover { transform:scale(1.05); }

                /* Spinner */
                .vmo-spinner { display:inline-block; width:12px; height:12px; border:2px solid rgba(255,255,255,0.3); border-radius:50%; border-top-color:#fff; animation:spin 1s ease-in-out infinite; margin-right:8px; }
                @keyframes spin { to { transform: rotate(360deg); } }
            `;
            document.head.appendChild(style);
        }

        const modal = document.createElement('div');
        modal.id = 'vmo-power-dialer-modal';
        modal.className = 'vmo-fs-modal vmo-modal-visible';
        modal.style.display = 'flex';
        
        modal.innerHTML = `
            <div class="vmo-modal-overlay" onclick="document.getElementById('vmo-power-dialer-modal').remove()"></div>
            <div class="vmo-modal-panel" style="width: min(950px, 95vw); max-height: 92vh; display:flex; flex-direction:column;">
                
                <!-- HEADER -->
                <div class="modal-header" style="flex-shrink:0;">
                    <div style="display:flex; align-items:center; gap:16px;">
                        <h3 class="modal-title" style="display:flex; align-items:center; gap:12px;">
                            <span style="font-size:24px; background:linear-gradient(135deg, #0fe1ff, #7c5cff); -webkit-background-clip:text; -webkit-text-fill-color:transparent;">🤖</span> 
                            <div>
                                VMO Autonomous Robo Sales
                                <div style="font-size:11px; color:var(--muted); font-weight:400; margin-top:2px;">AI Power Dialer • Elite Sales DNA Loaded</div>
                            </div>
                        </h3>
                        <div style="padding:4px 12px; background:rgba(15,225,255,0.1); border:1px solid rgba(15,225,255,0.3); border-radius:20px; font-size:11px; color:var(--cyan-soft);">
                            Credits: <strong>${balance}</strong>
                        </div>
                    </div>
                    <button class="modal-close" onclick="document.getElementById('vmo-power-dialer-modal').remove()">×</button>
                </div>
                
                <!-- TABS -->
                <div class="vmo-pd-tabs">
                    <div class="vmo-pd-tab active" onclick="vmoSwitchPDTab('strategy', this)">1. Strategy & Context</div>
                    <div class="vmo-pd-tab" onclick="vmoSwitchPDTab('audio', this)">2. Voice & Intro (Hybrid)</div>
                    <div class="vmo-pd-tab" onclick="vmoSwitchPDTab('leads', this)">3. Leads & Numbers</div>
                    <div class="vmo-pd-tab" onclick="vmoSwitchPDTab('launch', this)">4. Review & Launch</div>
                </div>

                <!-- CONTENT AREA -->
                <div style="overflow-y:auto; flex:1; padding-right:4px;">
                    
                    <!-- TAB 1: STRATEGY (PHASE 1 UPDATED) -->
                    <div id="pd-tab-strategy" class="vmo-pd-content active">
                        <div style="display:grid; grid-template-columns: 2fr 1fr; gap:20px;">
                            <div class="vmo-fs-glass-card" style="padding:20px; display:flex; flex-direction:column; gap:15px;">
                                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px;">
                                    <div>
                                        <label style="display:block; color:var(--cyan-soft); font-size:12px; margin-bottom:6px;">Goal / Objective</label>
                                        <input id="pd-goal" type="text" placeholder="e.g. Book a 15-min demo" style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--border); background:rgba(0,0,0,0.2); color:#fff; font-size:13px;">
                                    </div>
                                    <div>
                                        <label style="display:block; color:var(--cyan-soft); font-size:12px; margin-bottom:6px;">Target Audience / Intent</label>
                                        <input id="pd-intent" type="text" placeholder="e.g. Local Restaurants needing more orders" style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--border); background:rgba(0,0,0,0.2); color:#fff; font-size:13px;">
                                    </div>
                                </div>
                                <button class="vmo-pd-gen-btn vmo-btn-secondary" onclick="vmoPD_GenerateScript()" style="align-self:flex-start;">✨ Generate Sales Script</button>
                                
                                <div style="position:relative;">
                                    <label style="display:block; color:var(--muted); font-size:11px; margin-bottom:6px;">Generated Script (Editable)</label>
                                    <textarea id="pd-strategy-prompt" rows="12" placeholder="Script will appear here after generation..." style="width:100%; border:1px solid var(--border); background:rgba(0,0,0,0.3); color:#e2e8f0; padding:15px; resize:vertical; line-height:1.6; font-family:'Courier New', monospace; outline:none; height:280px; border-radius:8px;"></textarea>
                                </div>
                                <div style="text-align:right;">
                                    <button class="action-btn" onclick="vmoSwitchPDTab('audio', document.querySelector('.vmo-pd-tab:nth-child(2)'))">Next: Voice Setup ➡️</button>
                                </div>
                            </div>

                            <!-- Settings Side Panel (Unchanged mostly) -->
                            <div style="display:flex; flex-direction:column; gap:16px;">
                                <div>
                                    <label style="display:block; color:var(--cyan-soft); font-size:12px; margin-bottom:6px;">Campaign Name</label>
                                    <input type="text" placeholder="e.g., Feb Cold Outreach" style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--border); background:rgba(255,255,255,0.05); color:var(--ink);">
                                </div>
                                <div>
                                    <label style="display:block; color:var(--cyan-soft); font-size:12px; margin-bottom:6px;">Sales Persona</label>
                                    <select style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--border); background:rgba(255,255,255,0.05); color:var(--ink);">
                                        <option value="elite">Elite Closer (Aggressive)</option>
                                        <option value="consultative">Consultative Expert (Helpful)</option>
                                        <option value="setter">Appointment Setter (Polite)</option>
                                        <option value="survey">Market Researcher (Neutral)</option>
                                    </select>
                                </div>
                                <div class="vmo-card">
                                    <h4 style="font-size:12px; margin:0 0 10px;">Success Criteria</h4>
                                    <label style="display:flex; align-items:center; gap:8px; font-size:11px; margin-bottom:8px; color:var(--muted); cursor:pointer;">
                                        <input type="checkbox" checked> Booked Meeting
                                    </label>
                                    <label style="display:flex; align-items:center; gap:8px; font-size:11px; color:var(--muted); cursor:pointer;">
                                        <input type="checkbox"> Sale Closed
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 2: AUDIO (PHASE 2 UPDATED) -->
                    <div id="pd-tab-audio" class="vmo-pd-content">
                        <div style="text-align:center; max-width:600px; margin:0 auto; padding-top:20px;">
                            <h3 style="color:#fff; font-size:18px;">Hybrid Call Mode</h3>
                            <p style="color:var(--muted); font-size:13px; margin-bottom:30px;">Choose how the call starts. You can use a pre-recorded human intro to increase trust, then switch to AI for the conversation.</p>
                            
                            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px; text-align:left;">
                                <div class="vmo-pd-option" onclick="document.querySelectorAll('.vmo-pd-option').forEach(el=>el.classList.remove('selected')); this.classList.add('selected'); document.getElementById('pd-intro-mode').value='ai'; document.getElementById('pd-recorder-wrapper').style.opacity='0.3'; document.getElementById('pd-recorder-wrapper').style.pointerEvents='none';">
                                    <input type="radio" name="intro_mode" checked>
                                    <h4 style="margin:0 0 5px; color:#fff;">Full AI Mode</h4>
                                    <p style="font-size:11px; color:var(--muted); margin:0;">AI speaks from the very first second.</p>
                                </div>
                                <div class="vmo-pd-option selected" onclick="document.querySelectorAll('.vmo-pd-option').forEach(el=>el.classList.remove('selected')); this.classList.add('selected'); document.getElementById('pd-intro-mode').value='hybrid'; document.getElementById('pd-recorder-wrapper').style.opacity='1'; document.getElementById('pd-recorder-wrapper').style.pointerEvents='all';">
                                    <input type="radio" name="intro_mode">
                                    <h4 style="margin:0 0 5px; color:#fff;">Hybrid Intro (Recommended)</h4>
                                    <p style="font-size:11px; color:var(--muted); margin:0;">Human Intro -> AI Helper.</p>
                                </div>
                            </div>
                            <input type="hidden" id="pd-intro-mode" value="hybrid">

                            <div id="pd-recorder-wrapper" style="margin-top:40px; padding:30px; border:1px dashed rgba(255,255,255,0.2); border-radius:12px; background:rgba(0,0,0,0.2); transition:opacity 0.3s;">
                                
                                <!-- Recording State -->
                                <div id="pd-recorder-controls">
                                    <div class="vmo-rec-btn" onclick="vmoPD_StartRecord(this)">
                                        <div style="width:20px; height:20px; background:#fff; border-radius:4px;"></div>
                                    </div>
                                    <p id="rec-text" style="color:var(--ink); margin-top:15px; font-weight:600;">Tap to Record Intro</p>
                                    <div style="margin-top:10px;">
                                        <input type="file" id="pd-audio-upload" accept=".mp3,audio/*" style="display:none" onchange="vmoPD_HandleAudioUpload(this)">
                                        <p style="font-size:11px; color:var(--muted);">Or <a href="#" onclick="vmoPD_UploadLink(); return false;" style="color:var(--cyan);">Upload .MP3</a></p>
                                    </div>
                                </div>

                                <!-- Playback/Delete State -->
                                <div id="pd-player-controls" style="display:none; flex-direction:column; align-items:center; gap:15px;">
                                    <div style="display:flex; align-items:center; gap:20px;">
                                        <div class="vmo-play-btn" onclick="vmoPD_PlayRecord(this)">
                                            <div style="width:0; height:0; border-top:10px solid transparent; border-bottom:10px solid transparent; border-left:16px solid #fff; margin-left:5px;"></div>
                                        </div>
                                        <div onclick="vmoPD_DeleteRecord()" style="width:40px; height:40px; border-radius:50%; background:rgba(255,255,255,0.1); display:flex; align-items:center; justify-content:center; cursor:pointer; color:#ef4444; transition:background 0.2s;">
                                            🗑️
                                        </div>
                                    </div>
                                    <p style="color:#10b981; font-weight:600; margin:0;">Audio Ready!</p>
                                </div> 
                                <div style="margin-top:20px;text-align:right;">
                                    <button class="action-btn" onclick="vmoSwitchPDTab('leads', document.querySelector('.vmo-pd-tab:nth-child(3)'))">Next: Add Leads ➡️</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 3: LEADS (PHASE 3 UPDATED) -->
                    <div id="pd-tab-leads" class="vmo-pd-content">
                        <div style="display:grid; grid-template-columns: 1fr 300px; gap:20px;">
                            <div>
                                <label style="display:block; color:var(--cyan-soft); font-size:12px; margin-bottom:8px;">Import Numbers (CSV Format)</label>
                                <textarea id="pd-leads-input" placeholder="Name, Number, Company" style="width:100%; height:300px; padding:15px; border-radius:8px; border:1px solid var(--border); background:rgba(0,0,0,0.3); color:var(--ink); font-family:monospace; font-size:12px; resize:vertical;"></textarea>
                                <div style="display:flex; justify-content:space-between; margin-top:10px;">
                                    <div style="font-size:11px; color:var(--muted);">Format: Name, Number, Company</div>
                                </div>
                            </div>
                            <div style="display:flex; flex-direction:column; gap:12px;">
                                <input type="file" id="pd-csv-upload" accept=".csv" style="display:none;" onchange="vmoPD_ParseCSV(this)">
                                <button class="action-btn primary" onclick="document.getElementById('pd-csv-upload').click()" style="padding:15px; text-align:center;">
                                    <span style="display:block; font-size:18px; margin-bottom:4px;">📂 Upload CSV</span>
                                    <span style="font-size:11px; opacity:0.8;">Drag & drop file here</span>
                                </button>
                                <button class="action-btn" onclick="vmoPD_MockCRM()" style="padding:15px; text-align:center; background:rgba(255,255,255,0.05);">
                                    <span style="display:block; font-size:18px; margin-bottom:4px;">👥 Select from CRM</span>
                                    <span style="font-size:11px; opacity:0.8;">Load Mock Leads</span>
                                </button>
                                <div class="vmo-card" style="margin-top:auto;">
                                    <h4 style="margin:0 0 10px;">Summary</h4>
                                    <div class="vmo-kv"><span>Leads detected</span> <strong id="pd-summ-count">0</strong></div>
                                    <div class="vmo-kv"><span>Est. Duration</span> <strong id="pd-summ-time">0 mins</strong></div>
                                    <div class="vmo-kv"><span>Est. Cost</span> <strong id="pd-summ-cost">0 Credits</strong></div>
                                </div>
                                <div style="margin-top:10px;text-align:right;">
                                    <button class="action-btn" onclick="vmoSwitchPDTab('launch', document.querySelector('.vmo-pd-tab:nth-child(4)'))">Next: Review ➡️</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 4: LAUNCH (PHASE 4 UPDATED) -->
                    <div id="pd-tab-launch" class="vmo-pd-content">
                        <div style="max-width:700px; margin:0 auto; padding-top:20px;">
                            <div class="vmo-card" style="border:1px solid var(--cyan); background:linear-gradient(180deg, rgba(15,225,255,0.05), rgba(0,0,0,0.4));">
                                <h3 style="text-align:center; color:var(--cyan-soft); margin-bottom:30px;">Ready to Launch Campaign?</h3>
                                
                                <div style="display:grid; grid-template-columns:1fr 1fr; gap:20px; margin-bottom:30px;">
                                    <div class="vmo-pd-stat">
                                        <label>Strategy</label>
                                        <val>Defined</val>
                                    </div>
                                    <div class="vmo-pd-stat">
                                        <label>Sales Agent</label>
                                        <val id="confirm-persona">Elite Closer</val>
                                    </div>
                                    <div class="vmo-pd-stat">
                                        <label>Leads</label>
                                        <val id="confirm-leads">0</val>
                                    </div>
                                    <div class="vmo-pd-stat">
                                        <label>Simulate Call</label>
                                        <button onclick="vmoPD_TestCall()" style="background:var(--cyan-soft); border:none; color:#000; padding:4px 8px; border-radius:4px; font-size:11px; font-weight:bold; cursor:pointer;">▶ Test Audio</button>
                                    </div>
                                </div>

                                <div class="vmo-card" style="background:rgba(0,0,0,0.3); margin-bottom:30px;">
                                    <h4 style="margin:0 0 10px; font-size:13px; color:#fff;">Pre-Flight Checklist</h4>
                                    <div style="display:flex; flex-direction:column; gap:8px;">
                                        <div style="display:flex; align-items:center; gap:10px; font-size:12px; color:var(--muted);">
                                            <span style="color:#10b981;">✓</span> System Prompt Injected to AI Brain
                                        </div>
                                        <div style="display:flex; align-items:center; gap:10px; font-size:12px; color:var(--muted);">
                                            <span style="color:#10b981;">✓</span> Voice Synthesis Ready (Hybrid Mode)
                                        </div>
                                        <div style="display:flex; align-items:center; gap:10px; font-size:12px; color:var(--muted);">
                                            <span style="color:#10b981;">✓</span> Reporting & Analytics Modules Active
                                        </div>
                                    </div>
                                </div>

                                <button class="action-btn primary" onclick="vmoPD_LaunchDialer()" style="width:100%; padding:16px; font-size:16px; font-weight:700; text-transform:uppercase; letter-spacing:1px; box-shadow:0 0 20px rgba(15,225,255,0.4);">
                                    📞 Begin Bulk Calls
                                </button>
                                <div style="display:flex; justify-content:center; gap:15px; margin-top:10px;">
                                    <label style="display:flex; align-items:center; gap:8px; font-size:11px; color:var(--muted); cursor:pointer;">
                                        <input type="checkbox" checked onchange="window.vmoPDState.speakerOn = this.checked"> 🔊 Speaker Phone (Listen In)
                                    </label>
                                </div>
                                <p style="text-align:center; margin-top:15px; font-size:11px; color:var(--muted);">
                                    By launching, you confirm you have consent to contact these numbers.
                                </p>
                            </div>
                        </div>
                    </div>

                </div>

                <!-- FOOTER LINK -->
                <div style="margin-top:20px; padding:20px; border-top:1px solid rgba(255,255,255,0.1); background:rgba(0,0,0,0.2);">
                    <h4 style="text-align:center; color:var(--cyan); margin-bottom:15px; font-size:14px;">⚡ Needs more fuel? Get Power Packs</h4>
                    <div style="display:grid; grid-template-columns: repeat(4, 1fr); gap:10px;">
                        
                        <!-- Pack M -->
                        <div onclick="if(typeof VMOBusinessDashboard.buyPack === 'function') VMOBusinessDashboard.buyPack('phone_m')" 
                             style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.1); border-radius:8px; padding:10px; text-align:center; cursor:pointer; transition:all 0.2s;" onmouseover="this.style.background='rgba(16,185,129,0.1)';this.style.borderColor='#10b981'" onmouseout="this.style.background='rgba(255,255,255,0.05)';this.style.borderColor='rgba(255,255,255,0.1)'">
                            <div style="font-weight:700; color:#fff; font-size:12px;">Phone Pack M</div>
                            <div style="color:#10b981; font-size:14px; margin:4px 0;">$99.99</div>
                            <div style="font-size:10px; color:#aaa;">(~63 4-min Calls)</div>
                        </div>

                        <!-- Pack L -->
                        <div onclick="if(typeof VMOBusinessDashboard.buyPack === 'function') VMOBusinessDashboard.buyPack('phone_l')" 
                             style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.1); border-radius:8px; padding:10px; text-align:center; cursor:pointer; transition:all 0.2s;" onmouseover="this.style.background='rgba(16,185,129,0.1)';this.style.borderColor='#10b981'" onmouseout="this.style.background='rgba(255,255,255,0.05)';this.style.borderColor='rgba(255,255,255,0.1)'">
                            <div style="font-weight:700; color:#fff; font-size:12px;">Phone Pack L</div>
                            <div style="color:#10b981; font-size:14px; margin:4px 0;">$249.99</div>
                            <div style="font-size:10px; color:#aaa;">(~157 4-min Calls)</div>
                        </div>

                        <!-- Power Dialer -->
                        <div onclick="if(typeof VMOBusinessDashboard.buyPack === 'function') VMOBusinessDashboard.buyPack('power_dialer')" 
                             style="background:rgba(245,158,11,0.1); border:1px solid rgba(245,158,11,0.3); border-radius:8px; padding:10px; text-align:center; cursor:pointer; transition:all 0.2s;" onmouseover="this.style.transform='translateY(-2px)';" onmouseout="this.style.transform='translateY(0)';">
                            <div style="font-weight:700; color:#f59e0b; font-size:12px;">Power Dialer</div>
                            <div style="color:#f59e0b; font-size:14px; margin:4px 0;">$499.99</div>
                            <div style="font-size:10px; color:#aaa;">(~354 4-min Calls)</div>
                        </div>

                        <!-- Pro Call Center -->
                        <div onclick="if(typeof VMOBusinessDashboard.buyPack === 'function') VMOBusinessDashboard.buyPack('phone_xl')" 
                             style="background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.3); border-radius:8px; padding:10px; text-align:center; cursor:pointer; transition:all 0.2s;" onmouseover="this.style.transform='translateY(-2px)';" onmouseout="this.style.transform='translateY(0)';">
                            <div style="font-weight:700; color:#ef4444; font-size:12px;">Pro Center</div>
                            <div style="color:#ef4444; font-size:14px; margin:4px 0;">$699.99</div>
                            <div style="font-size:10px; color:#aaa;">(~500 4-min Calls)</div>
                        </div>
                    </div>
                </div>

            </div>
        `;
        
        document.body.appendChild(modal);





        window.vmoSwitchPDTab = function(tabName, el) {
            document.querySelectorAll('.vmo-pd-tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.vmo-pd-content').forEach(c => c.classList.remove('active'));
            
            el.classList.add('active');
            document.getElementById('pd-tab-' + tabName).classList.add('active');
        };
    };

    // Polyfill buyPack ONLY if the IIFE hasn't defined it yet (avoids overwriting the real AJAX handler)
    if (!window.VMOBusinessDashboard.buyPack) {
        window.VMOBusinessDashboard.buyPack = function(packId) {
            if(confirm('Redirect to purchase ' + packId + '?')) {
                window.open('https://virtualmediaoffice.com/pricing/?plan=' + packId, '_blank');
            }
        };
    }
