<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<!-- Tools Selection Modal -->
<div id="vmo-tools-selection-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-tools-modal">
        <div class="vmo-modal-header">
            <h3>🔧 Business Tools</h3>
            <button class="vmo-modal-close" id="vmo-close-tools-btn">×</button>
        </div>
        <div class="vmo-tools-grid">
            <!-- Bulk Email Tool Card -->
            <div class="vmo-tool-card" id="vmo-open-email-tool-btn">
                <div class="vmo-tool-icon">📧</div>
                <div class="vmo-tool-info">
                    <h4>Bulk Email Marketing</h4>
                    <p>Send marketing campaigns (rate-limited for deliverability).</p>
                </div>
            </div>
            <!-- Power Dialer Tool Card (NEW) -->
            <div class="vmo-tool-card" onclick="vmoCloseToolsModal(); setTimeout(() => { if(typeof VMOBusinessDashboard !== 'undefined' && VMOBusinessDashboard.openPowerDialer) { VMOBusinessDashboard.openPowerDialer(); } else if(window.vmoOpenPowerDialer) { window.vmoOpenPowerDialer(); } else { alert('Feature not ready'); } }, 100);">
                <div class="vmo-tool-icon">🤖</div>
                <div class="vmo-tool-info">
                    <h4>Autonomous Robo Sales</h4>
                    <p>Configure AI Sales Strategy & Auto-Dialing.</p>
                </div>
            </div>
            <!-- Executive Report Tool Card (NEW) -->
            <div class="vmo-tool-card" onclick="vmoOpenExecutiveReportModal(); vmoCloseToolsModal();">
                <div class="vmo-tool-icon">📊</div>
                <div class="vmo-tool-info">
                    <h4>Business Status Report</h4>
                    <p>Generate detailed executive assessment in PDF.</p>
                </div>
            </div>
            <!-- HTML to PDF Tool Card -->
            <div class="vmo-tool-card" onclick="window.location.href = '<?php echo admin_url('admin.php?page=vmo-html-to-pdf'); ?>';">
                <div class="vmo-tool-icon">📄</div>
                <div class="vmo-tool-info">
                    <h4>HTML to PDF Publisher</h4>
                    <p>Launch Professional PDF Editor.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Email Marketing Tool Modal -->
<div id="vmo-email-tool-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal">
        <div class="vmo-modal-header">
            <h3>📧 Bulk Email Marketing</h3>
            <button class="vmo-modal-close" id="vmo-close-email-btn">×</button>
        </div>
        <div class="vmo-modal-body">
            <!-- Tabs Navigation -->
            <div class="vmo-tabs-nav">
                <button class="vmo-tab-btn active" onclick="vmoSwitchEmailTab('suggestions')">✨ AI Suggestions</button>
                <button class="vmo-tab-btn" onclick="vmoSwitchEmailTab('dashboard')">📊 Dashboard & Campaigns</button>
                <button class="vmo-tab-btn" onclick="vmoSwitchEmailTab('mailbox')">📬 Mailbox</button>
            </div>

            <!-- Tab 1: AI Suggestions -->
            <div id="vmo-email-tab-suggestions" class="vmo-tab-content active">
                <div class="vmo-ai-suggestions-header">
                    <h4>Recommended for your Business</h4>
                    <p>AI has analyzed your business profile and suggests these campaigns.</p>
                </div>
                <div class="vmo-suggestions-grid">
                    <!-- Suggestion 1 -->
                    <div class="vmo-suggestion-card" onclick="vmoLoadTemplate('welcome_series')">
                        <div class="vmo-suggestion-badge">High Conversion</div>
                        <h5>Welcome Series</h5>
                        <p>Engage new leads with a 3-part introduction sequence.</p>
                        <button class="vmo-btn-small">Use Template</button>
                    </div>
                    <!-- Suggestion 2 -->
                    <div class="vmo-suggestion-card" onclick="vmoLoadTemplate('monthly_newsletter')">
                        <h5>Monthly Newsletter</h5>
                        <p>Keep your audience updated with company news and offers.</p>
                        <button class="vmo-btn-small">Use Template</button>
                    </div>
                    <!-- Suggestion 3 -->
                    <div class="vmo-suggestion-card" onclick="vmoLoadTemplate('flash_sale')">
                        <div class="vmo-suggestion-badge">Urgent</div>
                        <h5>Flash Sale Announcement</h5>
                        <p>Drive immediate sales with a time-sensitive offer.</p>
                        <button class="vmo-btn-small">Use Template</button>
                    </div>
                </div>
            </div>

            <!-- Tab 2: Dashboard -->
            <div id="vmo-email-tab-dashboard" class="vmo-tab-content">
                <!-- Stats Row -->
                <div class="vmo-email-stats-row">
                    <div class="vmo-stat-box">
                        <span class="label">Active Campaigns</span>
                        <span class="value" id="vmo-email-stat-active-campaigns">0</span>
                    </div>
                    <div class="vmo-stat-box">
                        <span class="label">Total Sent</span>
                        <span class="value" id="vmo-email-stat-total-sent">0</span>
                    </div>
                    <div class="vmo-stat-box">
                        <span class="label">Open Rate</span>
                        <span class="value" id="vmo-email-stat-open-rate">0%</span>
                    </div>
                    <div class="vmo-stat-box">
                        <span class="label">Click Rate</span>
                        <span class="value" id="vmo-email-stat-click-rate">0%</span>
                    </div>
                </div>

                <!-- Actions -->
                <div class="vmo-email-actions-bar">
                    <button class="vmo-btn vmo-btn-primary" onclick="vmoCreateCampaign()">➕ New Campaign</button>
                    <button class="vmo-btn" onclick="vmoViewReports()">📈 Detailed Reports</button>
                    <button class="vmo-btn vmo-btn-secondary" onclick="vmoOpenSignatureModal()">✒️ Signature Maker</button>
                </div>

                <!-- Campaign List Placeholder -->
                <div class="vmo-campaign-list-container">
                    <div class="vmo-empty-state">
                        <div style="font-size: 32px; margin-bottom: 10px;">📭</div>
                        <p>No active campaigns. Start one from the AI Suggestions tab!</p>
                    </div>
                </div>
            </div>

            <!-- Tab 3: Mailbox -->
            <div id="vmo-email-tab-mailbox" class="vmo-tab-content">
                <div class="vmo-webmail-container" style="display:grid; grid-template-columns:200px 1fr; gap:16px; height:100%;">
                    <!-- Sidebar -->
                    <div class="vmo-webmail-sidebar" style="background:rgba(0,0,0,0.2); border-radius:12px; padding:16px; border:1px solid var(--border);">
                        <button class="vmo-btn vmo-btn-primary" style="width:100%; margin-bottom:16px; font-weight:bold;" onclick="vmoOpenComposeModal()">✏️ Compose</button>
                        <div class="vmo-folder-list" style="display:flex; flex-direction:column; gap:8px;">
                            <div class="vmo-folder active" onclick="vmoSwitchBulkFolder('inbox')" style="padding:8px; cursor:pointer; border-radius:6px; background:rgba(255,255,255,0.05);">📥 Inbox</div>
                            <div class="vmo-folder" onclick="vmoSwitchBulkFolder('sent')" style="padding:8px; cursor:pointer; border-radius:6px;">📤 Sent</div>
                            <div class="vmo-folder" onclick="vmoSwitchBulkFolder('drafts')" style="padding:8px; cursor:pointer; border-radius:6px;">📝 Drafts</div>
                        </div>

                        <!-- Signature Maker Button -->
                        <button class="vmo-btn vmo-btn-secondary" style="width:100%; margin-top:16px; font-size:12px;" onclick="vmoOpenSignatureModal()">✒️ Signature Maker</button>

                        <!-- AI Auto-Reply Switch -->
                        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(15,225,255,0.28);">
                            <label style="display:flex; align-items:center; justify-content:space-between; cursor:pointer; font-size:13px; color:#e6f3ff;">
                                <span>🤖 AI Auto-Reply</span>
                                <div class="vmo-toggle-switch" id="vmo-ai-reply-toggle" onclick="vmoToggleAiReply(this)">
                                    <div class="vmo-toggle-slider"></div>
                                </div>
                            </label>
                            <div style="font-size:11px; color:#9fb2c8; margin-top:5px; line-height:1.3;">
                                Automatically reply to incoming emails using AI.
                            </div>
                        </div>
                    </div>
                    <!-- Content -->
                    <div class="vmo-webmail-content" id="vmo-bulk-mail-list" style="background:rgba(0,0,0,0.2); border-radius:12px; border:1px solid var(--border); padding:20px; text-align:center; color:var(--muted);">
                        <div style="font-size: 32px; margin-bottom: 10px; opacity:0.5;">📭</div>
                        <p>Select a folder to view messages.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Signature Maker Modal -->
<div id="vmo-signature-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content" style="max-width: 500px;">
        <div class="vmo-modal-header">
            <h3>✒️ Signature Maker</h3>
            <button class="vmo-modal-close" onclick="vmoCloseSignatureModal()">×</button>
        </div>
        <div class="vmo-modal-body" style="padding: 20px;">
            <div class="vmo-form-group">
                <label>Select Email Account</label>
                <select id="vmo-sig-account" class="vmo-input">
                    <option value="">Loading…</option>
                </select>
            </div>
            <div class="vmo-form-group">
                <label>Full Name</label>
                <input type="text" id="vmo-sig-name" class="vmo-input" placeholder="e.g. John Doe">
            </div>
            <div class="vmo-form-group">
                <label>Designation / Title</label>
                <input type="text" id="vmo-sig-role" class="vmo-input" placeholder="e.g. CEO">
            </div>
            <div class="vmo-form-group">
                <label>Company Logo</label>
                <input type="hidden" id="vmo-sig-logo" value="">
                <div style="display:flex; gap:8px; align-items:center;">
                    <button type="button" class="vmo-btn vmo-btn-secondary" onclick="vmoPickSignatureLogo()" style="flex:0 0 auto;">Choose from Media Library</button>
                    <div id="vmo-sig-logo-filename" style="flex:1; color:#888; font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">No logo selected</div>
                </div>
                <div id="vmo-sig-logo-preview-wrap" style="margin-top:10px; display:none; background:rgba(255,255,255,.02); border:1px solid var(--border); border-radius:10px; padding:10px;">
                    <div style="font-size:11px; color:var(--muted); margin-bottom:6px;">Preview (auto-sized to fit signature)</div>
                    <img id="vmo-sig-logo-preview" alt="Company logo preview" src="" style="max-height:40px; max-width:140px; width:auto; height:auto; object-fit:contain; display:block;" />
                </div>
            </div>
            <div class="vmo-form-group">
                <label>Website URL (Footer Link)</label>
                <input type="text" id="vmo-sig-website" class="vmo-input" placeholder="https://yourbusiness.com">
            </div>
            <div class="vmo-form-group">
                <label>Theme Color</label>
                <input type="color" id="vmo-sig-color" value="#0fe1ff" style="width: 100%; height: 40px; border:none; background:none;">
            </div>
            
            <div id="vmo-sig-socials-container">
                <label>Social Media Links</label>
                <!-- Dynamic inputs will be added here -->
            </div>
            <button class="vmo-btn vmo-btn-secondary" onclick="vmoAddSocialInput()" style="width:100%; margin-top:10px;">+ Add Social Link</button>
            
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border);">
                <button class="vmo-btn vmo-btn-primary" onclick="vmoSaveSignature()" style="width:100%;">Save Signature</button>
            </div>
        </div>
    </div>
</div>

<!-- Compose Email Modal -->
<div id="vmo-compose-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal" style="max-width: 900px;">
        <div class="vmo-modal-header">
            <h3>✉️ Compose Email</h3>
            <button class="vmo-modal-close" onclick="vmoCloseComposeModal()">×</button>
        </div>
        
        <!-- Tabs -->
        <div class="vmo-tabs-nav" style="padding: 0 20px; margin-top: 10px;">
            <button class="vmo-tab-btn active" onclick="vmoSwitchComposeTab('write')">✍️ Write</button>
            <button class="vmo-tab-btn" onclick="vmoSwitchComposeTab('preview')">👁️ Preview</button>
            <button class="vmo-tab-btn" onclick="vmoSwitchComposeTab('templates')">📋 Templates</button>
        </div>

        <div class="vmo-modal-body" style="display:flex; flex-direction:column; gap:16px; height: 700px; overflow-y: auto;">
            
            <!-- WRITE TAB -->
            <div id="vmo-compose-tab-write" class="vmo-compose-tab active">
                <!-- Header Fields -->
                <div style="display:flex; flex-direction:column; gap:12px;">
                    <div style="display:flex; gap:12px; flex-wrap:wrap;">
                        <div style="flex:1; min-width:200px;">
                            <label style="display:block; margin-bottom:4px; font-weight:600; font-size:13px; color:var(--muted);">From:</label>
                            <select id="vmo-compose-from" class="vmo-input" style="width:100%; padding:10px;">
                                <option value="">Loading accounts…</option>
                            </select>
                        </div>
                        <div style="flex:1; min-width:200px;">
                            <label style="display:block; margin-bottom:4px; font-weight:600; font-size:13px; color:var(--muted);">To:</label>
                            <input type="text" id="vmo-compose-to" class="vmo-input" placeholder="recipient@example.com" style="width:100%; padding:10px;">
                        </div>
                    </div>
                    <div style="width: 100%;">
                        <label style="display:block; margin-bottom:4px; font-weight:600; font-size:13px; color:var(--muted);">Subject:</label>
                        <input type="text" id="vmo-compose-subject" class="vmo-input" placeholder="Email Subject" style="width:100%; padding:10px;">
                    </div>
                </div>

                <!-- AI Generation Section -->
                <div style="background:rgba(15,225,255,0.05); padding:20px; border-radius:12px; border:1px solid var(--border); margin-top: 15px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; flex-wrap:wrap; gap:10px;">
                        <h4 style="margin:0; color:var(--cyan);">AI Writer & Tools</h4>
                        <div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
                            <button class="vmo-btn-small" onclick="vmoOpenProductPicker()">Products</button>
                            <button class="vmo-btn-small" onclick="vmoInsertCheckoutLink()">Checkout</button>
                        </div>
                    </div>

                    <!-- Theme and Template Selection -->
                    <div style="display:flex; gap:10px; margin-bottom:12px; flex-wrap:wrap;">
                        <div style="flex:1; min-width:180px;">
                            <label style="display:block; margin-bottom:4px; font-size:12px; font-weight:600; color:#cfe3ff;">Design Theme:</label>
                            <select id="vmo-compose-theme" class="vmo-input" style="width:100%; padding:8px 10px;">
                                <optgroup label="Design Styles">
                                    <option value="none">No Theme</option>
                                    <option value="modern">Modern</option>
                                    <option value="minimal">Minimal</option>
                                    <option value="corporate">Corporate</option>
                                    <option value="luxury">Luxury</option>
                                    <option value="bold">Bold</option>
                                    <option value="elegant">Elegant</option>
                                    <option value="tech">Tech</option>
                                    <option value="warm">Warm & Friendly</option>
                                    <option value="dark_mode">Dark Mode</option>
                                    <option value="glassmorphism">Glassmorphism</option>
                                    <option value="gradient">Gradient Flow</option>
                                    <option value="parallax">Parallax Hero</option>
                                </optgroup>
                                <optgroup label="Seasonal / Holiday">
                                    <option value="christmas">Christmas</option>
                                    <option value="new_year">New Year</option>
                                    <option value="valentines">Valentines</option>
                                    <option value="easter">Easter</option>
                                    <option value="summer">Summer</option>
                                    <option value="back_to_school">Back to School</option>
                                    <option value="halloween">Halloween</option>
                                    <option value="black_friday">Black Friday</option>
                                    <option value="cyber_monday">Cyber Monday</option>
                                    <option value="thanksgiving">Thanksgiving</option>
                                </optgroup>
                                <optgroup label="Industry">
                                    <option value="restaurant">Restaurant</option>
                                    <option value="fitness">Fitness</option>
                                    <option value="real_estate">Real Estate</option>
                                    <option value="beauty">Beauty & Spa</option>
                                    <option value="fashion">Fashion</option>
                                    <option value="automotive">Automotive</option>
                                    <option value="healthcare">Healthcare</option>
                                    <option value="education">Education</option>
                                </optgroup>
                            </select>
                        </div>
                        <div style="flex:1; min-width:180px;">
                            <label style="display:block; margin-bottom:4px; font-size:12px; font-weight:600; color:#cfe3ff;">Email Template:</label>
                            <select id="vmo-compose-template" class="vmo-input" style="width:100%; padding:8px 10px;">
                                <optgroup label="General">
                                    <option value="freeform">Freeform (custom)</option>
                                    <option value="newsletter">Newsletter</option>
                                    <option value="announcement">Announcement</option>
                                    <option value="thank_you">Thank You</option>
                                    <option value="follow_up">Follow-Up</option>
                                </optgroup>
                                <optgroup label="E-Commerce">
                                    <option value="product_launch">Product Launch</option>
                                    <option value="flash_sale">Flash Sale</option>
                                    <option value="abandoned_cart">Abandoned Cart Recovery</option>
                                    <option value="order_followup">Post-Purchase Follow-Up</option>
                                    <option value="review_request">Review Request</option>
                                    <option value="restock_alert">Restock Alert</option>
                                    <option value="loyalty_reward">Loyalty Reward</option>
                                </optgroup>
                                <optgroup label="Business">
                                    <option value="welcome_series">Welcome Series</option>
                                    <option value="event_invite">Event Invitation</option>
                                    <option value="case_study">Case Study / Testimonial</option>
                                    <option value="survey">Survey / Feedback</option>
                                    <option value="milestone">Milestone Celebration</option>
                                    <option value="referral">Referral Program</option>
                                </optgroup>
                            </select>
                        </div>
                    </div>

                    <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-bottom:10px; color:var(--muted); font-size:12px;">
                        <span style="font-weight:600; color:#cfe3ff;">Draft format:</span>
                        <label style="display:flex; gap:6px; align-items:center; cursor:pointer;">
                            <input type="radio" name="vmo-compose-format" value="plain" />
                            <span>Plain text</span>
                        </label>
                        <label style="display:flex; gap:6px; align-items:center; cursor:pointer;">
                            <input type="radio" name="vmo-compose-format" value="html" checked />
                            <span>AI HTML</span>
                        </label>
                        <span style="opacity:0.9;">(Switch anytime)</span>
                    </div>

                    <textarea id="vmo-compose-intent" class="vmo-input" rows="5" placeholder="Describe what you want to say in detail...&#10;&#10;Examples:&#10;- Write a product launch email for our new wireless headphones&#10;- Create an abandoned cart recovery email with 15% discount&#10;- Send a holiday newsletter with year-in-review stats" style="width:100%; resize:vertical; min-height:100px;"></textarea>
                    <div style="display:flex; gap:10px; margin-top:10px;">
                        <button class="vmo-btn vmo-btn-secondary" onclick="vmoGenerateEmailContent()" style="flex:1;">Generate Draft</button>
                    </div>
                    <div style="margin-top:12px;">
                        <textarea id="vmo-compose-refine" class="vmo-input" rows="3" placeholder="Refine or regenerate... e.g., Make it shorter, Add urgency, Switch to luxury theme" style="width:100%; resize:vertical; min-height:60px;"></textarea>
                        <button class="vmo-btn" onclick="vmoRegenerateEmailVariant()" style="width:100%; margin-top:8px;">Regenerate Variant</button>
                    </div>
                </div>

                <!-- Editor -->
                <div style="width: 100%; margin-top: 15px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
                        <label id="vmo-compose-body-label" style="font-weight:600; font-size:14px;">Message Body:</label>
                        <div style="display:flex; gap:6px;">
                            <button class="vmo-btn-small" onclick="document.getElementById('vmo-compose-body').style.height='300px'" title="Compact">S</button>
                            <button class="vmo-btn-small" onclick="document.getElementById('vmo-compose-body').style.height='500px'" title="Medium">M</button>
                            <button class="vmo-btn-small" onclick="document.getElementById('vmo-compose-body').style.height='700px'" title="Large">L</button>
                        </div>
                    </div>
                    <textarea id="vmo-compose-body" class="vmo-input" rows="18" placeholder="Write your email here or use AI Generate above...&#10;&#10;Supports full HTML for rich email designs with images, buttons, product cards, etc." style="width:100%; font-family:monospace; font-size:13px; line-height:1.5; resize:vertical; min-height:250px;"></textarea>
                </div>
            </div>

            <!-- PREVIEW TAB -->
            <div id="vmo-compose-tab-preview" class="vmo-compose-tab" style="display:none; height: 100%;">
                <div style="display:flex; gap:10px; margin-bottom:10px; align-items:center;">
                    <span style="font-size:13px; color:var(--muted);">Preview as:</span>
                    <button class="vmo-btn-small active" onclick="vmoPreviewDevice('desktop', this)">Desktop</button>
                    <button class="vmo-btn-small" onclick="vmoPreviewDevice('mobile', this)">Mobile</button>
                </div>
                <div id="vmo-email-preview-frame" style="width:100%; height:calc(100% - 40px); background:white; color:black; border-radius:8px; padding:20px; overflow:auto; transition:max-width 0.3s; margin:0 auto;">
                    <!-- Preview content goes here -->
                </div>
            </div>

            <!-- TEMPLATES TAB -->
            <div id="vmo-compose-tab-templates" class="vmo-compose-tab" style="display:none;">
                <div style="margin-bottom:15px;">
                    <input type="text" id="vmo-template-search" class="vmo-input" placeholder="Search templates..." style="width:100%; padding:10px;">
                </div>
                <div id="vmo-template-gallery" style="display:grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:12px;">
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('product_launch')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F680;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Product Launch</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Hero image, features grid, CTA button</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('flash_sale')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x26A1;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Flash Sale</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Countdown timer, discount badge, urgency</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('newsletter')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F4F0;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Newsletter</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Multi-section layout, articles, sidebar</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('abandoned_cart')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F6D2;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Cart Recovery</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Item reminder, discount, return link</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('welcome_series')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F44B;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Welcome Email</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Onboarding, brand intro, first purchase CTA</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('event_invite')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F39F;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Event Invitation</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Date, location, RSVP button, agenda</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('review_request')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x2B50;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Review Request</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Star rating CTA, testimonial prompt</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('referral')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F91D;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Referral Program</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Share link, rewards tiers, social icons</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('survey')" style="background:rgba(255,255,255,0.03); border:1px solid var(--border); border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.borderColor='var(--cyan)'; this.style.transform='translateY(-2px)'" onmouseout="this.style.borderColor='var(--border)'; this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">&#x1F4CA;</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Feedback Survey</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">NPS scale, feedback form, incentive offer</p>
                    </div>
                </div>
            </div>

            <!-- Footer Actions -->
            <div style="display:flex; justify-content:space-between; align-items:center; margin-top:auto; flex-wrap:wrap; gap:10px; padding-top: 15px; border-top: 1px solid var(--border);">
                <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                    <button class="vmo-btn vmo-btn-secondary" onclick="vmoOpenSignatureModal()">Signature</button>
                    <div style="display:flex; align-items:center; gap:5px; background:rgba(0,0,0,0.2); padding:5px 10px; border-radius:8px; border:1px solid var(--border);">
                        <span style="font-size:12px;">Schedule:</span>
                        <input type="datetime-local" id="vmo-compose-schedule" class="vmo-input" style="width:180px; padding:4px; font-size:12px;">
                    </div>
                    <div style="display:flex; align-items:center; gap:5px; background:rgba(0,0,0,0.2); padding:5px 10px; border-radius:8px; border:1px solid var(--border);">
                        <label style="cursor:pointer; font-size:12px; color:var(--cyan);">Attach File<input type="file" id="vmo-compose-attachment" style="display:none;" multiple></label>
                        <span id="vmo-attachment-count" style="font-size:11px; color:var(--muted);"></span>
                    </div>
                </div>
                <div style="display:flex; gap:10px;">
                    <button class="vmo-btn" onclick="vmoSaveDraft()" title="Save as draft">Draft</button>
                    <button class="vmo-btn" onclick="vmoCloseComposeModal()">Cancel</button>
                    <button class="vmo-btn vmo-btn-primary" onclick="vmoSendEmail()">Send / Schedule</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Email Compose Helper Scripts -->
<script>
function vmoSelectTemplate(templateType) {
    var dropdown = document.getElementById('vmo-compose-template');
    if (dropdown) { dropdown.value = templateType; }
    var intents = {
        'product_launch': 'Write a product launch email with hero image, key features grid, pricing, and a strong call-to-action button',
        'flash_sale': 'Create a flash sale email with countdown urgency, discount percentage badge, featured products, and a shop now button',
        'newsletter': 'Write a professional newsletter with a header article, 2-3 news items, a featured story, and social media links',
        'abandoned_cart': 'Create an abandoned cart recovery email reminding the customer about items left in their cart, with product images and a return-to-cart button',
        'welcome_series': 'Write a warm welcome email for new subscribers introducing our brand, what to expect, and a special first-purchase discount',
        'event_invite': 'Create an event invitation email with date, time, location details, agenda highlights, a hero image, and an RSVP button',
        'review_request': 'Write a post-purchase review request email with star rating buttons, a brief testimonial prompt, and a small incentive offer',
        'referral': 'Create a referral program email explaining rewards, how to share, unique referral link placeholder, and social sharing buttons',
        'survey': 'Write a customer feedback survey email with an NPS scale visual, a brief survey link button, and a thank-you incentive'
    };
    var intentField = document.getElementById('vmo-compose-intent');
    if (intentField && intents[templateType]) { intentField.value = intents[templateType]; }
    vmoSwitchComposeTab('write');
}
function vmoPreviewDevice(device, btn) {
    var frame = document.getElementById('vmo-email-preview-frame');
    if (!frame) return;
    frame.style.maxWidth = (device === 'mobile') ? '375px' : '100%';
    var btns = btn.parentElement.querySelectorAll('.vmo-btn-small');
    btns.forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');
}
function vmoSaveDraft() {
    var body = document.getElementById('vmo-compose-body');
    var subject = document.getElementById('vmo-compose-subject');
    if (body && subject) {
        var drafts = JSON.parse(localStorage.getItem('vmo_email_drafts') || '[]');
        drafts.unshift({ subject: subject.value, body: body.value, timestamp: new Date().toISOString() });
        if (drafts.length > 20) drafts = drafts.slice(0, 20);
        localStorage.setItem('vmo_email_drafts', JSON.stringify(drafts));
        if (typeof vmoToast === 'function') { vmoToast('Draft saved', 'success'); }
    }
}
</script>

<!-- Product Picker Modal (Compose) -->
<div id="vmo-product-picker-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal" style="max-width: 900px;">
        <div class="vmo-modal-header">
            <h3>🛒 Add Product(s)</h3>
            <button class="vmo-modal-close" onclick="vmoCloseProductPicker()">×</button>
        </div>
        <div class="vmo-modal-body" style="display:flex; flex-direction:column; gap:12px; height: 520px; overflow:auto;">
            <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                <input id="vmo-product-search" class="vmo-input" type="text" placeholder="Search products..." style="flex:1; min-width: 240px;">
                <button class="vmo-btn vmo-btn-secondary" onclick="vmoLoadProducts()">Search</button>
            </div>
            <div id="vmo-product-picker-status" style="color:var(--muted); font-size:12px;">Loading…</div>
            <div id="vmo-product-picker-list" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap:12px;"></div>
        </div>
        <div class="vmo-modal-footer" style="padding: 20px; border-top: 1px solid var(--border); display:flex; justify-content:space-between; align-items:center; gap:10px; flex-wrap:wrap;">
            <div style="color:var(--muted); font-size:12px;">Select one or more products to insert into the email.</div>
            <div style="display:flex; gap:10px;">
                <button class="vmo-btn" onclick="vmoCloseProductPicker()">Cancel</button>
                <button class="vmo-btn vmo-btn-primary" onclick="vmoInsertSelectedProducts()">Insert Selected</button>
            </div>
        </div>
    </div>
</div>

<!-- HTML to PDF Modal -->
<div id="vmo-pdf-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal" style="max-width: 900px;">
        <div class="vmo-modal-header">
            <h3>📄 HTML to PDF Converter</h3>
            <button class="vmo-modal-close" onclick="vmoClosePdfModal()">×</button>
        </div>
        <div class="vmo-modal-body" style="display:flex; flex-direction:row; gap:20px; height: 600px;">
            <!-- Input Area -->
            <div style="flex:1; display:flex; flex-direction:column; min-width: 0;">
                <h4 style="margin-top:0;">Input HTML Code</h4>
                <textarea id="vmo-pdf-source" class="vmo-input" style="flex:1; font-family:monospace; padding:10px; resize:none;" placeholder="Paste your HTML code here..."></textarea>
            </div>
            
            <!-- Preview Area -->
            <div style="flex:1; display:flex; flex-direction:column; min-width: 0;">
                <h4 style="margin-top:0;">Live Preview</h4>
                <div id="vmo-pdf-preview-container" style="flex:1; background:#f0f0f1; border:1px solid var(--border); border-radius:8px; overflow:auto; padding:20px; display:flex; justify-content:center; align-items:flex-start;">
                    <div id="vmo-pdf-preview" style="background:white; color:black; width:100%; min-height:100%; box-shadow:0 2px 10px rgba(0,0,0,0.1); padding:20px; transition: all 0.3s ease;">
                        <!-- Content will be rendered here -->
                    </div>
                </div>
            </div>
        </div>
        <div class="vmo-modal-footer" style="padding: 20px; border-top: 1px solid var(--border); display:flex; justify-content:space-between; align-items:center;">
            <div style="display:flex; gap:10px; align-items:center;">
                <label style="display:flex; align-items:center; gap:5px; cursor:pointer;">
                    <input type="checkbox" id="vmo-pdf-landscape" onchange="vmoToggleOrientation()"> Landscape Mode
                </label>
            </div>
            <div style="display:flex; gap:10px;">
                <button class="vmo-btn" onclick="vmoUpdatePdfPreview()">🔄 Update Preview</button>
                <button class="vmo-btn vmo-btn-primary" onclick="vmoGeneratePDF()">⬇️ Download PDF</button>
            </div>
        </div>
    </div>
</div>

<!-- Executive Report Modal -->
<div id="vmo-executive-report-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal" style="max-width: 900px;">
        <div class="vmo-modal-header">
            <h3>📊 Executive Business Status Report</h3>
            <button class="vmo-modal-close" onclick="vmoCloseExecutiveReportModal()">×</button>
        </div>
        <div class="vmo-modal-body" style="height: 100%; overflow-y: auto; padding: 0;">
            <!-- Report Preview Container -->
            <div id="vmo-report-preview-container" style="background: white; color: #333; padding: 40px; min-height: 100%;">
                <div style="text-align: center; margin-bottom: 40px; border-bottom: 2px solid #eee; padding-bottom: 20px;">
                    <h1 style="margin: 0; color: #2c3e50; font-size: 28px;">Executive Business Status</h1>
                    <p style="color: #7f8c8d; margin: 10px 0 0;" id="vmo-report-date">Loading...</p>
                    <p style="color: #bdc3c7; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">Prepared for <span id="vmo-report-business-name">...</span></p>
                </div>

                <!-- KPIs -->
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 40px;">
                    <div class="vmo-kpi-box" style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="margin: 0; font-size: 32px; color: #2c3e50;" id="vmo-kpi-revenue">...</h3>
                        <p style="margin: 5px 0 0; color: #7f8c8d; font-size: 12px; text-transform: uppercase;">Total Revenue</p>
                    </div>
                    <div class="vmo-kpi-box" style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="margin: 0; font-size: 32px; color: #2c3e50;" id="vmo-kpi-visits">...</h3>
                        <p style="margin: 5px 0 0; color: #7f8c8d; font-size: 12px; text-transform: uppercase;">Visits</p>
                    </div>
                    <div class="vmo-kpi-box" style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="margin: 0; font-size: 32px; color: #2c3e50;" id="vmo-kpi-leads">...</h3>
                        <p style="margin: 5px 0 0; color: #7f8c8d; font-size: 12px; text-transform: uppercase;">Total Leads</p>
                    </div>
                    <div class="vmo-kpi-box" style="background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="margin: 0; font-size: 32px; color: #2c3e50;" id="vmo-kpi-conversion">...</h3>
                        <p style="margin: 5px 0 0; color: #7f8c8d; font-size: 12px; text-transform: uppercase;">Conversion Rate</p>
                    </div>
                </div>

                <!-- Charts -->
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px;">
                    <div>
                        <h4 style="color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 10px;">Traffic Trend (Visits)</h4>
                        <div id="vmo-chart-traffic" style="height: 200px; display: flex; align-items: flex-end; gap: 4px; padding-top: 20px;">
                            <!-- Bars injected by JS -->
                        </div>
                    </div>
                    <div>
                        <h4 style="color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 10px;">Sales Trend (Revenue)</h4>
                        <div id="vmo-chart-revenue" style="height: 200px; display: flex; align-items: flex-end; gap: 8px; padding-top: 20px;">
                            <!-- Bars injected by JS -->
                        </div>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px;">
                    <div>
                        <h4 style="color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 10px;">Conversion Trend (%)</h4>
                        <div id="vmo-chart-conversion" style="height: 200px; display: flex; align-items: flex-end; gap: 4px; padding-top: 20px;">
                            <!-- Bars injected by JS -->
                        </div>
                    </div>
                    <div>
                        <h4 style="color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 10px;">SEO Visibility (Proxy)</h4>
                        <div id="vmo-chart-seo" style="height: 200px; display: flex; align-items: flex-end; gap: 8px; padding-top: 20px;">
                            <!-- Bars injected by JS -->
                        </div>
                    </div>
                </div>

                <!-- Footer -->
                <div style="text-align: center; color: #bdc3c7; font-size: 12px; border-top: 1px solid #eee; padding-top: 20px;">
                    Generated by VMO Business Suite • Confidential Executive Summary
                </div>
            </div>
        </div>
        <div class="vmo-modal-footer" style="padding: 20px; border-top: 1px solid var(--border); display:flex; justify-content:space-between;">
             <div>
                 <span style="font-size: 12px; color: var(--muted); margin-right: 10px;">Period: <span id="vmo-period-label">All Time</span></span>
             </div>
             <button class="vmo-btn vmo-btn-primary" onclick="vmoDownloadExecutiveReport(this)">⬇️ Download Report as PDF</button>
        </div>
    </div>
</div>

<!-- Date Range Selection Modal for Report -->
<div id="vmo-report-date-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content" style="max-width: 400px; text-align: center;">
        <div class="vmo-modal-header" style="justify-content: center;">
            <h3>📅 Select Report Period</h3>
            <button class="vmo-modal-close" onclick="vmoCloseDateRangeModal()">×</button>
        </div>
        <div class="vmo-modal-body" style="padding: 24px;">
            <p style="color: var(--muted); margin-bottom: 20px;">Choose a date range for your business progress report.</p>
            
            <div style="margin-bottom: 15px; text-align: left;">
                <label style="display: block; color: var(--ink); margin-bottom: 5px;">From Date</label>
                <input type="date" id="vmo-report-start-date" class="vmo-input" style="width: 100%;">
            </div>
            
            <div style="margin-bottom: 25px; text-align: left;">
                <label style="display: block; color: var(--ink); margin-bottom: 5px;">To Date</label>
                <input type="date" id="vmo-report-end-date" class="vmo-input" style="width: 100%;">
            </div>

            <div style="display: flex; gap: 10px; justify-content: center;">
                 <button class="vmo-btn" onclick="vmoSetReportRange('last_30')">Last 30 Days</button>
                 <button class="vmo-btn" onclick="vmoSetReportRange('this_year')">This Year</button>
            </div>
        </div>
        <div class="vmo-modal-footer" style="padding: 20px; border-top: 1px solid var(--border);">
            <button class="vmo-btn vmo-btn-primary" style="width: 100%;" onclick="vmoGenerateReportFromRange()">Generate & Download Report</button>
        </div>
    </div>
</div>

<script>
    var vmo_report_nonce = "<?php echo wp_create_nonce('vmo_backend_nonce'); ?>";
    
    // Step 1: Open Date Picker
    window.vmoOpenDateRangeForReport = function() {
        const modal = document.getElementById('vmo-report-date-modal');
        if(modal) {
            modal.classList.add('vmo-show');
            // Default to Year
            vmoSetReportRange('this_year');
        } else {
            console.error('Date range modal not found');
        }
    };
    
    window.vmoCloseDateRangeModal = function() {
        const modal = document.getElementById('vmo-report-date-modal');
        if(modal) modal.classList.remove('vmo-show');
    };
    
    window.vmoSetReportRange = function(range) {
        const today = new Date();
        const startEl = document.getElementById('vmo-report-start-date');
        const endEl = document.getElementById('vmo-report-end-date');
        
        let start = new Date();
        let end = new Date();
        
        if (range === 'last_30') {
            start.setDate(today.getDate() - 30);
        } else if (range === 'this_year') {
            start = new Date(today.getFullYear(), 0, 1);
        }
        
        startEl.value = start.toISOString().split('T')[0];
        endEl.value = end.toISOString().split('T')[0];
    };
    
    // Step 2: Generate Report and Show Preview
    window.vmoGenerateReportFromRange = function() {
        const start = document.getElementById('vmo-report-start-date').value;
        const end = document.getElementById('vmo-report-end-date').value;
        
        if (!start || !end) {
            alert('Please select both From and To dates.');
            return;
        }
        
        // Close Date Modal
        vmoCloseDateRangeModal();
        
        // Open Report Modal logic (reused)
        vmoOpenExecutiveReportModal(start, end);
    };

    window.vmoOpenExecutiveReportModal = function(start = null, end = null) {
        const modal = document.getElementById('vmo-executive-report-modal');
        if(modal) modal.classList.add('vmo-show');
        
        // Use default range if none provided (last 30 days)
        if (!start) {
            const d = new Date();
            d.setDate(d.getDate() - 30);
            start = d.toISOString().split('T')[0];
        }
        if (!end) {
            end = new Date().toISOString().split('T')[0];
        }
        
        // Update Label
        document.getElementById('vmo-period-label').innerText = start + ' to ' + end;
        
        // Use Global jQuery if available, otherwise fetch
        if (typeof jQuery !== 'undefined') {
            jQuery.post(ajaxurl, {
                action: 'vmo_get_executive_report',
                nonce: vmo_report_nonce,
                start_date: start,
                end_date: end
            }, function(res) {
                if(res.success) {
                    vmoRenderExecutiveReport(res.data);
                } else {
                    alert('Failed to load report data: ' + (res.data ? res.data.message : 'Unknown error'));
                }
            });
        }
    };
    
    // Helper to render bars
    function renderBarChart(containerId, dataValues, labels, color = '#3498db') {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        container.innerHTML = '';
        const maxVal = Math.max(...dataValues, 10); // avoid div/0
        
        dataValues.forEach((val, index) => {
            const heightPct = (val / maxVal) * 100;
            const label = labels[index] || '';
            const barHtml = `
                <div style="flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%;">
                    <div style="width: 70%; background: ${color}; height: ${heightPct}%; border-radius: 2px 2px 0 0; min-height: 2px;"></div>
                    <div style="font-size: 9px; color: #7f8c8d; margin-top: 4px; transform: rotate(-45deg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; text-align:center;">${label}</div>
                </div>`;
            container.insertAdjacentHTML('beforeend', barHtml);
        });
    }

    window.vmoCloseExecutiveReportModal = function() {
        const modal = document.getElementById('vmo-executive-report-modal');
        if(modal) modal.classList.remove('vmo-show');
    };

    window.vmoRenderExecutiveReport = function(data) {
        document.getElementById('vmo-report-business-name').innerText = data.business_name;
        document.getElementById('vmo-report-date').innerText = data.date;
        
        // KPIs
        document.getElementById('vmo-kpi-revenue').innerText = '$' + (data.financials.total_revenue / 100).toFixed(2);
        document.getElementById('vmo-kpi-visits').innerText = data.traffic.visits_total;
        document.getElementById('vmo-kpi-leads').innerText = data.leads.total_leads;
        document.getElementById('vmo-kpi-conversion').innerText = data.traffic.conversion_rate + '%';
        
        // Render Charts with dynamic data
        renderBarChart('vmo-chart-traffic', data.traffic.traffic_trend, data.traffic.traffic_labels, '#3498db');
        renderBarChart('vmo-chart-revenue', data.financials.revenue_trend, data.financials.revenue_labels, '#27ae60');
        renderBarChart('vmo-chart-conversion', data.traffic.conversion_trend, data.traffic.conversion_labels, '#9b59b6'); // Purple
        renderBarChart('vmo-chart-seo', data.traffic.seo_trend, data.traffic.seo_labels, '#e67e22'); // Orange
    };


    window.vmoDownloadExecutiveReport = function(btn) {
        const element = document.getElementById('vmo-report-preview-container');
        const originalText = btn.innerHTML;
        btn.innerHTML = '⏳ Generating PDF...';
        btn.disabled = true;

        const opt = {
            margin:       0.2,
            filename:     'Executive_Report_' + new Date().toISOString().slice(0,10) + '.pdf',
            image:        { type: 'jpeg', quality: 0.98 },
            html2canvas:  { scale: 2 },
            jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
        };

        if (typeof html2pdf !== 'undefined') {
            html2pdf().set(opt).from(element).save().then(() => {
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        } else {
            alert('PDF Generator library not loaded. Please try again later.');
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    };
</script>

<?php wp_enqueue_script('html2pdf', VMO_AI_BUILDER_URL . 'assets/vendor/html2pdf.bundle.min.js', array(), '0.10.1', true); ?>

<style>
/* Modal Styles - Renamed to avoid conflicts */
.vmo-tools-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 100001; /* Higher than WP Admin Bar (99999) */
    display: none !important; /* Force hidden by default */
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(5px);
}

/* Class to show modal */
.vmo-tools-overlay.vmo-show {
    display: flex !important;
}

.vmo-modal-content {
    /* Glassmorphism & Theme Colors */
    background: linear-gradient(135deg, rgba(14, 29, 41, 0.95), rgba(18, 46, 63, 0.95));
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    color: #e6f3ff; /* --ink */
    border-radius: 22px; /* --radius */
    box-shadow: 0 24px 60px rgba(0,0,0,0.55), 0 0 0 1px rgba(15,225,255,0.15) inset; /* --shadow + subtle inner rim */
    width: 90%;
    max-width: 600px;
    border: 1px solid rgba(15,225,255,0.28); /* --border */
    animation: vmoModalSlideIn 0.3s ease-out;
    display: flex;
    flex-direction: column;
    position: relative;
    max-height: 90vh; /* Prevent overflow on small screens */
}

.vmo-email-modal {
    max-width: 1000px; /* Wider for the email tool */
    height: 85vh;
}

.vmo-modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid rgba(15,225,255,0.15);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: transparent;
    border-radius: 22px 22px 0 0;
}

.vmo-modal-header h3 {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 600;
    color: #0fe1ff; /* --cyan */
    letter-spacing: 0.5px;
    text-shadow: 0 0 10px rgba(15, 225, 255, 0.3);
}

.vmo-modal-close {
    background: none;
    border: none;
    color: #7ad8e2;
    font-size: 2rem;
    cursor: pointer;
    padding: 0;
    line-height: 0.5;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s;
}

.vmo-modal-close:hover {
    color: #fff;
    background: rgba(15, 225, 255, 0.15);
    box-shadow: 0 0 10px rgba(15, 225, 255, 0.2);
}

.vmo-modal-body {
    padding: 0; /* Reset padding for tabs */
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

/* Tabs */
.vmo-tabs-nav {
    display: flex;
    border-bottom: 1px solid rgba(15,225,255,0.15);
    background: rgba(0,0,0,0.2);
}

.vmo-tab-btn {
    flex: 1;
    padding: 16px;
    background: none;
    border: none;
    color: #9fb2c8;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    border-bottom: 2px solid transparent;
}

.vmo-tab-btn:hover {
    color: #e6f3ff;
    background: rgba(255,255,255,0.02);
}

.vmo-tab-btn.active {
    color: #0fe1ff;
    border-bottom-color: #0fe1ff;
    background: rgba(15,225,255,0.05);
}

.vmo-tab-content {
    display: none;
    padding: 24px;
    flex: 1;
    overflow-y: auto;
}

.vmo-tab-content.active {
    display: block;
}

/* Signature Modal */
#vmo-signature-modal {
    z-index: 100002; /* Above email modal */
}

/* AI Suggestions Tab */
.vmo-ai-suggestions-header {
    margin-bottom: 24px;
    text-align: center;
}

.vmo-ai-suggestions-header h4 {
    margin: 0 0 8px 0;
    color: #e6f3ff;
    font-size: 1.2rem;
}

.vmo-ai-suggestions-header p {
    margin: 0;
    color: #9fb2c8;
}

.vmo-suggestions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
}

.vmo-suggestion-card {
    background: linear-gradient(180deg, rgba(255,255,255,0.05), rgba(0,0,0,0.2));
    border: 1px solid rgba(15,225,255,0.2);
    border-radius: 16px;
    padding: 20px;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
    overflow: hidden;
}

.vmo-suggestion-card:hover {
    transform: translateY(-3px);
    border-color: #0fe1ff;
    box-shadow: 0 0 20px rgba(15, 225, 255, 0.15);
}

.vmo-suggestion-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    background: rgba(15,225,255,0.15);
    color: #0fe1ff;
    font-size: 0.7rem;
    padding: 2px 8px;
    border-radius: 10px;
    border: 1px solid rgba(15,225,255,0.3);
    font-weight: 700;
}

.vmo-suggestion-card h5 {
    margin: 0 0 8px 0;
    font-size: 1.1rem;
    color: #fff;
}

.vmo-suggestion-card p {
    margin: 0 0 16px 0;
    font-size: 0.9rem;
    color: #9fb2c8;
    line-height: 1.4;
}

.vmo-btn-small {
    background: transparent;
    border: 1px solid rgba(15,225,255,0.3);
    color: #0fe1ff;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 0.8rem;
    cursor: pointer;
    transition: all 0.2s;
}

.vmo-suggestion-card:hover .vmo-btn-small {
    background: #0fe1ff;
    color: #000;
}

/* Dashboard Tab */
.vmo-email-stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin-bottom: 24px;
}

.vmo-stat-box {
    background: rgba(0,0,0,0.3);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 12px;
    padding: 15px;
    text-align: center;
}

.vmo-stat-box .label {
    display: block;
    font-size: 0.8rem;
    color: #9fb2c8;
    margin-bottom: 5px;
}

.vmo-stat-box .value {
    display: block;
    font-size: 1.5rem;
    font-weight: 700;
    color: #e6f3ff;
}

.vmo-empty-state {
    text-align: center;
    padding: 40px;
    border: 2px dashed rgba(255,255,255,0.1);
    border-radius: 12px;
    color: #9fb2c8;
}

/* Tools Grid */
.vmo-tools-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    padding: 24px;
}

.vmo-tool-card {
    background: linear-gradient(180deg, rgba(255,255,255,0.05), rgba(0,0,0,0.2));
    border: 1px solid rgba(15,225,255,0.2);
    border-radius: 16px; /* --panel-radius */
    padding: 20px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.05);
}

.vmo-tool-card:hover {
    transform: translateY(-2px);
    border-color: #0fe1ff; /* --cyan */
    box-shadow: 0 0 15px rgba(15, 225, 255, 0.15), inset 0 0 0 1px rgba(15, 225, 255, 0.1);
    background: linear-gradient(180deg, rgba(255,255,255,0.08), rgba(0,0,0,0.3));
}

.vmo-tool-icon {
    font-size: 2rem;
    filter: drop-shadow(0 0 5px rgba(15, 225, 255, 0.4));
}

.vmo-tool-info h4 {
    margin: 0 0 5px 0;
    font-size: 1rem;
    color: #e6f3ff;
    font-weight: 600;
}

.vmo-tool-info p {
    margin: 0;
    font-size: 0.875rem;
    color: #9fb2c8; /* --muted */
}

.vmo-tool-coming-soon {
    opacity: 0.7;
    cursor: default;
    border-style: dashed;
    border-color: rgba(15,225,255,0.15);
}

.vmo-tool-coming-soon:hover {
    transform: none;
    border-color: rgba(15,225,255,0.25);
    background: rgba(0,0,0,0.2);
    box-shadow: none;
}

/* Buttons */
.vmo-btn {
    padding: 10px 20px;
    border-radius: 12px;
    border: 1px solid rgba(15,225,255,0.28);
    cursor: pointer;
    font-weight: 600;
    transition: all 0.2s;
    background: linear-gradient(180deg, rgba(255,255,255,0.08), rgba(0,0,0,0.45));
    color: #e6f3ff;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.08), 0 4px 12px rgba(0,0,0,0.2);
}

.vmo-btn:hover {
    background: linear-gradient(180deg, rgba(255,255,255,0.12), rgba(0,0,0,0.5));
    border-color: #0fe1ff;
    color: #fff;
    box-shadow: 0 0 15px rgba(15, 225, 255, 0.2);
}

.vmo-btn-primary {
    background: linear-gradient(180deg, rgba(15, 225, 255, 0.15), rgba(15, 225, 255, 0.05));
    border-color: #0fe1ff;
    color: #0fe1ff;
}

.vmo-btn-primary:hover {
    background: linear-gradient(180deg, rgba(15, 225, 255, 0.25), rgba(15, 225, 255, 0.1));
    box-shadow: 0 0 20px rgba(15, 225, 255, 0.3);
    text-shadow: 0 0 8px rgba(15, 225, 255, 0.5);
}

.vmo-email-actions-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
}

@keyframes vmoModalSlideIn {
    from {
        opacity: 0;
        transform: translateY(20px) scale(0.98);
    }
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}
/* AI Toggle Switch */
.vmo-toggle-switch {
    width: 36px;
    height: 20px;
    background: rgba(0,0,0,0.3);
    border-radius: 20px;
    position: relative;
    transition: background 0.3s;
    border: 1px solid rgba(15,225,255,0.28);
}
.vmo-toggle-switch.active {
    background: rgba(15,225,255,0.2);
    border-color: #0fe1ff;
}
.vmo-toggle-slider {
    width: 16px;
    height: 16px;
    background: #9fb2c8;
    border-radius: 50%;
    position: absolute;
    top: 1px;
    left: 1px;
    transition: transform 0.3s, background 0.3s;
}
.vmo-toggle-switch.active .vmo-toggle-slider {
    transform: translateX(16px);
    background: #0fe1ff;
}
</style>

<script>
    // AI Auto-Reply Toggle
    window.vmoToggleAiReply = function(el) {
        el.classList.toggle('active');
        const isActive = el.classList.contains('active');
        
        const formData = new FormData();
        formData.append('action', 'vmo_update_ai_reply_settings');
        formData.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '')); 
        formData.append('enabled', isActive ? 1 : 0);

        vmoFetchJson(ajaxurl, {
            method: 'POST',
            body: formData
        }).then(data => {
            if (!data || !data.success) {
                console.error('Failed to update AI reply settings:', data);
                el.classList.toggle('active');
                alert('Failed to update setting: ' + (data && data.data && data.data.message ? data.data.message : 'Unknown error'));
            }
        }).catch(err => {
            console.error('Network error:', err);
            el.classList.toggle('active');
        });
    };

(function() {
    // Define functions globally
    window.vmoOpenToolsModal = function() {
        const modal = document.getElementById('vmo-tools-selection-modal');
        if (modal) modal.classList.add('vmo-show');
    };

    window.vmoCloseToolsModal = function() {
        const modal = document.getElementById('vmo-tools-selection-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoOpenEmailTool = function(mode, recipients) {
        vmoCloseToolsModal(); // Close selection modal
        const modal = document.getElementById('vmo-email-tool-modal');
        if (modal) {
            modal.classList.add('vmo-show');
            
            if (mode === 'bulk') {
                // Switch to Campaigns/Dashboard tab
                vmoSwitchEmailTab('dashboard');
                
                // If recipients are provided, show a notification
                if (recipients && recipients.length > 0) {
                    // Store recipients for the campaign wizard
                    window.vmoBulkRecipients = recipients;
                    alert(`Starting bulk campaign for ${recipients.length} contacts. Please create a new campaign.`);
                }
            }
        }
    };

    window.vmoCloseEmailTool = function() {
        const modal = document.getElementById('vmo-email-tool-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoSwitchEmailTab = function(tabName) {
        // Hide all tabs
        document.querySelectorAll('.vmo-tab-content').forEach(el => el.classList.remove('active'));
        document.querySelectorAll('.vmo-tab-btn').forEach(el => el.classList.remove('active'));
        
        // Show selected
        document.getElementById('vmo-email-tab-' + tabName).classList.add('active');
        // Find button (simple approximation)
        const btns = document.querySelectorAll('.vmo-tab-btn');
        if (tabName === 'suggestions') btns[0].classList.add('active');
        if (tabName === 'dashboard') {
            btns[1].classList.add('active');
            if (typeof window.vmoRefreshEmailDashboard === 'function') {
                window.vmoRefreshEmailDashboard();
            }
        }
        if (tabName === 'mailbox') {
            btns[2].classList.add('active');
            // Fetch AI reply status
            (function(){
                const fd = new FormData();
                fd.append('action', 'vmo_get_ai_reply_status');
                fd.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : ''));
                vmoFetchJson(ajaxurl, { method: 'POST', body: fd })
                    .then(data => {
                        const toggle = document.getElementById('vmo-ai-reply-toggle');
                        if (!toggle) return;
                        const enabled = !!(data && data.success && data.data && data.data.enabled);
                        if (enabled) toggle.classList.add('active');
                        else toggle.classList.remove('active');
                    })
                    .catch(err => console.error('Failed to fetch AI reply status', err));
            })();

            // Load current mailbox folder (real data)
            const folder = (window.vmoCurrentMailboxFolder ? String(window.vmoCurrentMailboxFolder) : 'inbox') || 'inbox';
            if (typeof window.vmoSwitchBulkFolder === 'function') {
                window.vmoSwitchBulkFolder(folder);
            }
        }
    };

    window.vmoOpenSignatureModal = function() {
        const modal = document.getElementById('vmo-signature-modal');
        if (modal) modal.classList.add('vmo-show');
        vmoPopulateSignatureAccounts();
    };

    window.vmoCloseSignatureModal = function() {
        const modal = document.getElementById('vmo-signature-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoPickSignatureLogo = function() {
        try {
            if (!(window.wp && wp.media)) {
                alert('Media Library is not available on this screen.');
                return;
            }
            const frame = wp.media({
                title: 'Select Company Logo',
                button: { text: 'Use this logo' },
                library: { type: 'image' },
                multiple: false
            });
            frame.on('select', function() {
                const attachment = frame.state().get('selection').first();
                if (!attachment) return;
                const data = attachment.toJSON();
                const url = data && data.url ? data.url : '';
                const filename = (data && data.filename) ? data.filename : (url ? url.split('/').pop() : 'Selected image');
                const input = document.getElementById('vmo-sig-logo');
                if (input) input.value = url;
                const nameEl = document.getElementById('vmo-sig-logo-filename');
                if (nameEl) nameEl.textContent = filename || 'Selected image';
                const wrap = document.getElementById('vmo-sig-logo-preview-wrap');
                const img = document.getElementById('vmo-sig-logo-preview');
                if (img) img.src = url;
                if (wrap) wrap.style.display = url ? 'block' : 'none';
            });
            frame.open();
        } catch (e) {
            alert('Could not open Media Library.');
        }
    };

    window.vmoAddSocialInput = function() {
        const container = document.getElementById('vmo-sig-socials-container');
        const div = document.createElement('div');
        div.style.display = 'flex';
        div.style.gap = '8px';
        div.style.marginBottom = '8px';
        div.innerHTML = `
            <select class="vmo-input vmo-social-select" style="width:120px;">
                <option value="linkedin">LinkedIn</option>
                <option value="twitter">Twitter/X</option>
                <option value="facebook">Facebook</option>
                <option value="instagram">Instagram</option>
                <option value="youtube">YouTube</option>
                <option value="website">Website</option>
                <option value="github">GitHub</option>
            </select>
            <input type="text" class="vmo-input vmo-social-url" placeholder="Paste URL here..." style="flex:1;" oninput="vmoAutoDetectSocial(this)">
            <button class="vmo-btn" onclick="this.parentElement.remove()" style="padding:0 8px;">×</button>
        `;
        container.appendChild(div);
    };

    window.vmoAutoDetectSocial = function(input) {
        const url = input.value.toLowerCase();
        const select = input.parentElement.querySelector('select');
        
        if (url.includes('linkedin.com')) select.value = 'linkedin';
        else if (url.includes('twitter.com') || url.includes('x.com')) select.value = 'twitter';
        else if (url.includes('facebook.com')) select.value = 'facebook';
        else if (url.includes('instagram.com')) select.value = 'instagram';
        else if (url.includes('youtube.com')) select.value = 'youtube';
        else if (url.includes('github.com')) select.value = 'github';
    };

    window.vmoSaveSignature = function() {
        const account = document.getElementById('vmo-sig-account').value;
        const name = document.getElementById('vmo-sig-name').value;
        const designation = document.getElementById('vmo-sig-role').value;
        const color = document.getElementById('vmo-sig-color').value;
        const logo = document.getElementById('vmo-sig-logo').value;
        const website = document.getElementById('vmo-sig-website').value;
        
        const socials = [];
        document.querySelectorAll('#vmo-sig-socials-container > div').forEach(div => {
            const platform = div.querySelector('select').value;
            const url = div.querySelector('input').value;
            if (url) socials.push({ platform, url });
        });

        const formData = new FormData();
        formData.append('action', 'vmo_save_email_signature');
        formData.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : ''));
        formData.append('account', account);
        formData.append('name', name);
        formData.append('designation', designation);
        formData.append('theme_color', color);
        formData.append('social_links', JSON.stringify(socials));
        formData.append('logo_url', logo);
        formData.append('website_url', website);

        // Prefer plugin nonce; fall back to WP REST nonce.
        const security = (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '') || vmoGetWpNonce();
        if (security) {
            formData.set('security', security);
        }

        const btn = event && event.target ? event.target : null;
        if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }

        vmoFetchJson(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(data => {
            if (data && data.success) {
                alert('Signature saved!');
                vmoCloseSignatureModal();
            } else {
                const msg = (data && data.data && data.data.message) ? data.data.message : 'Unable to save signature.';
                alert('Error: ' + msg);
            }
        })
        .catch(err => {
            console.error('Save signature failed:', err);
            alert('Error saving signature: ' + (err && err.message ? err.message : 'Unknown error'));
        })
        .finally(() => {
            if (btn) { btn.disabled = false; btn.textContent = 'Save Signature'; }
        });
    };

    function vmoSetSigLoading(state) {
        const sel = document.getElementById('vmo-sig-account');
        if (!sel) return;
        sel.disabled = !!state;
    }

    function vmoClearSignatureForm() {
        document.getElementById('vmo-sig-name').value = '';
        document.getElementById('vmo-sig-role').value = '';
        document.getElementById('vmo-sig-logo').value = '';
        document.getElementById('vmo-sig-website').value = '';
        // keep color as-is
        const nameEl = document.getElementById('vmo-sig-logo-filename');
        if (nameEl) nameEl.textContent = 'No logo selected';
        const wrap = document.getElementById('vmo-sig-logo-preview-wrap');
        if (wrap) wrap.style.display = 'none';
        const img = document.getElementById('vmo-sig-logo-preview');
        if (img) img.src = '';

        // Remove all social input rows (preserve the container label)
        document.querySelectorAll('#vmo-sig-socials-container > div').forEach(div => div.remove());
    }

    function vmoLoadSignatureForAccount(accountEmail) {
        vmoSetSigLoading(true);
        const formData = new FormData();
        formData.append('action', 'vmo_get_email_signature');
        formData.append('account', accountEmail || 'default');
        formData.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '') || vmoGetWpNonce());

        vmoFetchJson(ajaxurl, { method: 'POST', body: formData })
            .then(data => {
                const sig = data && data.success && data.data ? data.data.signature : null;
                vmoClearSignatureForm();
                if (!sig) return;

                document.getElementById('vmo-sig-name').value = sig.name || '';
                document.getElementById('vmo-sig-role').value = sig.designation || '';
                document.getElementById('vmo-sig-website').value = sig.website_url || '';
                if (sig.theme_color) {
                    document.getElementById('vmo-sig-color').value = sig.theme_color;
                }
                if (sig.logo_url) {
                    document.getElementById('vmo-sig-logo').value = sig.logo_url;
                    const nameEl = document.getElementById('vmo-sig-logo-filename');
                    if (nameEl) nameEl.textContent = sig.logo_url.split('/').pop();
                    const wrap = document.getElementById('vmo-sig-logo-preview-wrap');
                    const img = document.getElementById('vmo-sig-logo-preview');
                    if (img) img.src = sig.logo_url;
                    if (wrap) wrap.style.display = 'block';
                }

                const socials = Array.isArray(sig.social_links) ? sig.social_links : [];
                socials.forEach(s => {
                    vmoAddSocialInput();
                    const last = document.querySelector('#vmo-sig-socials-container > div:last-child');
                    if (!last) return;
                    const select = last.querySelector('select');
                    const input = last.querySelector('input');
                    if (select && s.platform) select.value = String(s.platform);
                    if (input && s.url) input.value = String(s.url);
                });
            })
            .catch(err => {
                console.error('Failed to load signature:', err);
            })
            .finally(() => vmoSetSigLoading(false));
    }

    function vmoPopulateSignatureAccounts() {
        const select = document.getElementById('vmo-sig-account');
        if (!select) return;

        vmoSetSigLoading(true);
        const prev = select.value;
        select.innerHTML = '<option value="">Loading…</option>';

        const formData = new FormData();
        formData.append('action', 'vmo_list_email_accounts');
        formData.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '') || vmoGetWpNonce());

        vmoFetchJson(ajaxurl, { method: 'POST', body: formData })
            .then(data => {
                const accounts = data && data.success && data.data && Array.isArray(data.data.accounts) ? data.data.accounts : [];
                select.innerHTML = '';

                if (!accounts.length) {
                    select.innerHTML = '<option value="default">default</option>';
                    select.value = 'default';
                    vmoLoadSignatureForAccount('default');
                    return;
                }

                accounts.forEach(a => {
                    const email = a && a.email ? String(a.email) : '';
                    if (!email) return;
                    const opt = document.createElement('option');
                    opt.value = email;
                    opt.textContent = email;
                    select.appendChild(opt);
                });

                // Restore selection if possible
                if (prev) {
                    const found = Array.from(select.options).some(o => o.value === prev);
                    if (found) select.value = prev;
                }
                if (!select.value) {
                    select.selectedIndex = 0;
                }

                vmoLoadSignatureForAccount(select.value);
            })
            .catch(err => {
                console.error('Failed to load email accounts:', err);
                select.innerHTML = '<option value="default">default</option>';
                select.value = 'default';
                vmoLoadSignatureForAccount('default');
            })
            .finally(() => {
                vmoSetSigLoading(false);
            });

        // Attach change handler once
        if (!select.__vmoBound) {
            select.addEventListener('change', function() {
                vmoLoadSignatureForAccount(select.value);
            });
            select.__vmoBound = true;
        }
    }

    window.vmoSwitchBulkFolder = function(folder) {
        try { window.vmoCurrentMailboxFolder = String(folder || 'inbox'); } catch (_) { window.vmoCurrentMailboxFolder = 'inbox'; }
        // Update active state
        document.querySelectorAll('#vmo-email-tab-mailbox .vmo-folder').forEach(el => {
            el.classList.remove('active');
            el.style.background = 'transparent';
        });
        const activeEl = document.querySelector(`#vmo-email-tab-mailbox .vmo-folder[onclick*="${folder}"]`);
        if (activeEl) {
            activeEl.classList.add('active');
            activeEl.style.background = 'rgba(255,255,255,0.05)';
        }
        
        // Update content
        const listEl = document.getElementById('vmo-bulk-mail-list');
        if (!listEl) return;
        listEl.innerHTML = '<div style="padding:20px;">Loading ' + vmoEscapeHtml(folder) + '…</div>';

        const apiRoot = vmoGetApiRoot();
        const nonce = vmoGetWpNonce();

        const url = new URL(apiRoot + 'vmo-manager/v1/emails');
        url.searchParams.set('folder', String(folder || 'inbox'));
        url.searchParams.set('type', 'transactional');

        fetch(url.toString(), {
            method: 'GET',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(async (r) => {
            const ct = (r.headers && r.headers.get) ? (r.headers.get('content-type') || '') : '';
            const text = await r.text();
            if (!r.ok) {
                throw new Error('HTTP ' + r.status + ' ' + (text ? text.slice(0, 180) : ''));
            }
            if (ct && ct.toLowerCase().includes('application/json')) {
                return text ? JSON.parse(text) : {};
            }
            try {
                return text ? JSON.parse(text) : {};
            } catch (e) {
                throw new Error('Non-JSON response: ' + (text ? text.slice(0, 180) : '(empty)'));
            }
        })
        .then(data => {
            if (!data || !data.success) {
                listEl.innerHTML = `
                    <div style="font-size: 32px; margin-bottom: 10px; opacity:0.5;">📭</div>
                    <p>Unable to load messages.</p>
                `;
                return;
            }

            const emails = Array.isArray(data.emails) ? data.emails : [];
            if (!emails.length) {
                listEl.innerHTML = `
                    <div style="font-size: 32px; margin-bottom: 10px; opacity:0.5;">📭</div>
                    <p>No messages in ${vmoEscapeHtml(folder)}</p>
                `;
                return;
            }

            listEl.innerHTML = `
                <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px;">
                    <div style="font-weight:700; color:#e6f3ff;">${vmoEscapeHtml(folder).toUpperCase()}</div>
                    <div style="color:var(--muted); font-size:12px;">${emails.length} message(s)</div>
                </div>
                <div style="overflow:auto;">
                    <table style="width:100%; text-align:left; border-collapse:collapse; color:#e6f3ff;">
                        <thead>
                            <tr style="border-bottom:1px solid rgba(255,255,255,0.1);">
                                <th style="padding:8px;">From</th>
                                <th style="padding:8px;">Subject</th>
                                <th style="padding:8px;">Date</th>
                                <th style="padding:8px; width:90px;">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${emails.map(e => {
                                const id = Number(e.id || e.email_id || 0);
                                const from = vmoEscapeHtml(e.from_email || e.from || e.sender || '');
                                const subj = vmoEscapeHtml(e.subject || '(no subject)');
                                const dt = vmoEscapeHtml(e.created_at || e.received_at || e.date || '');
                                return `
                                    <tr style="border-bottom:1px solid rgba(255,255,255,0.05);">
                                        <td style="padding:8px; color:#cfe3ff;">${from || '—'}</td>
                                        <td style="padding:8px;">${subj}</td>
                                        <td style="padding:8px; color:var(--muted); font-size:12px;">${dt || '—'}</td>
                                        <td style="padding:8px;"><button class="vmo-btn-small" onclick="vmoOpenBulkEmail(${id}, '${vmoEscapeHtml(folder)}')">Open</button></td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        })
        .catch(err => {
            console.error('Mailbox load error:', err);
            listEl.innerHTML = `
                <div style="font-size: 32px; margin-bottom: 10px; opacity:0.5;">📭</div>
                <p>Network error loading messages.</p>
            `;
        });
    };

    window.vmoOpenBulkEmail = function(id, folder) {
        const listEl = document.getElementById('vmo-bulk-mail-list');
        if (!listEl) return;

        const emailId = Number(id || 0);
        if (!emailId) {
            alert('Invalid message.');
            return;
        }

        const apiRoot = vmoGetApiRoot();
        const nonce = vmoGetWpNonce();
        const safeFolder = String(folder || (window.vmoCurrentMailboxFolder || 'inbox'));

        listEl.innerHTML = '<div style="padding:20px;">Loading message…</div>';

        fetch(apiRoot + 'vmo-manager/v1/emails/' + emailId, {
            method: 'GET',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(async (r) => {
            const ct = (r.headers && r.headers.get) ? (r.headers.get('content-type') || '') : '';
            const text = await r.text();
            if (!r.ok) {
                throw new Error('HTTP ' + r.status + ' ' + (text ? text.slice(0, 180) : ''));
            }
            if (ct && ct.toLowerCase().includes('application/json')) {
                return text ? JSON.parse(text) : {};
            }
            try {
                return text ? JSON.parse(text) : {};
            } catch (e) {
                throw new Error('Non-JSON response: ' + (text ? text.slice(0, 180) : '(empty)'));
            }
        })
        .then(data => {
            if (!data || !data.success || !data.email) {
                listEl.innerHTML = `
                    <div style="padding:20px;">
                        <button class="vmo-btn" onclick="vmoSwitchBulkFolder('${vmoEscapeHtml(safeFolder)}')">← Back</button>
                        <div style="margin-top:12px; color:var(--muted);">Unable to load message.</div>
                    </div>
                `;
                return;
            }
            const e = data.email;
            const subj = vmoEscapeHtml(e.subject || '(no subject)');
            const from = vmoEscapeHtml(e.from_email || e.from || e.sender || '');
            const to = vmoEscapeHtml(e.to_email || e.to || '');
            const dt = vmoEscapeHtml(e.created_at || e.received_at || e.date || '');
            const bodyHtml = (e.body_html || e.html || '');
            const bodyText = (e.body_text || e.text || e.body || '');
            const hasHtml = !!String(bodyHtml || '').trim();

            listEl.innerHTML = `
                <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px;">
                    <button class="vmo-btn" onclick="vmoSwitchBulkFolder('${vmoEscapeHtml(safeFolder)}')">← Back</button>
                    <button class="vmo-btn vmo-btn-secondary" onclick="vmoDeleteBulkEmail(${emailId}, '${vmoEscapeHtml(safeFolder)}')">🗑️ Delete</button>
                </div>
                <div style="background:rgba(0,0,0,0.2); border:1px solid var(--border); border-radius:12px; padding:16px;">
                    <div style="font-weight:800; font-size:16px; margin-bottom:10px;">${subj}</div>
                    <div style="display:flex; flex-direction:column; gap:6px; color:var(--muted); font-size:12px;">
                        <div><span style="color:#cfe3ff;">From:</span> ${from || '—'}</div>
                        <div><span style="color:#cfe3ff;">To:</span> ${to || '—'}</div>
                        <div><span style="color:#cfe3ff;">Date:</span> ${dt || '—'}</div>
                    </div>
                    <div style="margin-top:14px; background:#fff; color:#111; border-radius:10px; padding:14px; overflow:auto; max-height:45vh;">
                        ${hasHtml ? bodyHtml : ('<pre style="white-space:pre-wrap; word-wrap:break-word; font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace; font-size:13px; line-height:1.5;">' + vmoEscapeHtml(bodyText || '') + '</pre>')}
                    </div>
                </div>
            `;

            // Mark read (best effort)
            fetch(apiRoot + 'vmo-manager/v1/emails/' + emailId + '/read', {
                method: 'POST',
                headers: { 'X-WP-Nonce': nonce }
            }).catch(() => {});
        })
        .catch(err => {
            console.error('Email view error:', err);
            listEl.innerHTML = `
                <div style="padding:20px;">
                    <button class="vmo-btn" onclick="vmoSwitchBulkFolder('${vmoEscapeHtml(safeFolder)}')">← Back</button>
                    <div style="margin-top:12px; color:var(--muted);">Network error loading message.</div>
                </div>
            `;
        });
    };

    window.vmoDeleteBulkEmail = function(id, folder) {
        const emailId = Number(id || 0);
        if (!emailId) return;
        if (!confirm('Delete this email?')) return;
        const apiRoot = vmoGetApiRoot();
        const nonce = vmoGetWpNonce();
        const safeFolder = String(folder || (window.vmoCurrentMailboxFolder || 'inbox'));
        vmoFetchJson(apiRoot + 'vmo-manager/v1/emails/' + emailId, {
            method: 'DELETE',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(() => {
            window.vmoSwitchBulkFolder(safeFolder);
        })
        .catch(err => {
            console.error('Email delete error:', err);
            alert('Network error deleting email.');
        });
    };

    window.vmoLoadTemplate = function(templateId) {
        let subject = "";
        let body = "";

        if (templateId === 'welcome_series') {
            subject = "Welcome to the family! Here's what to expect.";
            body = "<h1>Welcome!</h1><p>We are thrilled to have you with us.</p>";
        } else if (templateId === 'monthly_newsletter') {
            subject = "Your Monthly Update: exciting news inside";
            body = "<h1>Monthly Newsletter</h1><p>Here is what happened this month...</p>";
        } else if (templateId === 'flash_sale') {
            subject = "⚡ Flash Sale! 24 Hours Only";
            body = "<h1>Flash Sale!</h1><p>Get 50% off everything for the next 24 hours.</p>";
        }

        // Open Compose Modal
        vmoOpenComposeModal();
        
        // Populate fields
        document.getElementById('vmo-compose-subject').value = subject;
        document.getElementById('vmo-compose-body').value = body;
        
        // Switch to preview to show it off
        vmoSwitchComposeTab('preview');
    };

    window.vmoCreateCampaign = function() {
        // Open compose modal as the "Campaign Wizard"
        vmoOpenComposeModal();
    };

    window.vmoViewReports = function() {
        const container = document.querySelector('.vmo-campaign-list-container');
        if (!container) return;
        container.innerHTML = '<div style="padding:15px; color:var(--muted);">Loading reports…</div>';

        const formData = new FormData();
        formData.append('action', 'vmo_get_email_overview');
        formData.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : ''));

        vmoFetchJson(ajaxurl, { method: 'POST', body: formData })
            .then(resp => {
                const payload = resp && resp.success ? resp.data : null;
                const campaigns = payload && Array.isArray(payload.campaigns) ? payload.campaigns : [];

                if (!campaigns.length) {
                    container.innerHTML = `
                        <div class="vmo-empty-state">
                            <div style="font-size: 32px; margin-bottom: 10px;">📭</div>
                            <p>No campaigns yet.</p>
                        </div>
                    `;
                    return;
                }

                const rows = campaigns.map(c => {
                    const name = vmoEscapeHtml(c.title || c.campaign_name || 'Campaign');
                    const sent = Number(c.sent || c.sent_count || 0);
                    const opened = Number(c.open || c.opened_count || 0);
                    const clicked = Number(c.click || c.clicked_count || 0);
                    const openRate = sent > 0 ? Math.round((opened / sent) * 1000) / 10 : 0;
                    const clickRate = opened > 0 ? Math.round((clicked / opened) * 1000) / 10 : 0;
                    return `
                        <tr style="border-bottom:1px solid rgba(255,255,255,0.05);">
                            <td style="padding:8px;">${name}</td>
                            <td style="padding:8px;">${sent}</td>
                            <td style="padding:8px;">${openRate}%</td>
                            <td style="padding:8px;">${clickRate}%</td>
                        </tr>
                    `;
                }).join('');

                container.innerHTML = `
                    <div style="background:rgba(0,0,0,0.2); border-radius:8px; padding:15px;">
                        <h4 style="margin-top:0;">📈 Campaign Performance</h4>
                        <table style="width:100%; text-align:left; border-collapse:collapse; color:#e6f3ff;">
                            <tr style="border-bottom:1px solid rgba(255,255,255,0.1);">
                                <th style="padding:8px;">Campaign</th>
                                <th style="padding:8px;">Sent</th>
                                <th style="padding:8px;">Open Rate</th>
                                <th style="padding:8px;">Click Rate</th>
                            </tr>
                            ${rows}
                        </table>
                        <button class="vmo-btn-small" style="margin-top:15px;" onclick="window.vmoRefreshEmailDashboard && window.vmoRefreshEmailDashboard()">Close Reports</button>
                    </div>
                `;
            })
            .catch(err => {
                console.error('Reports load error:', err);
                container.innerHTML = '<div style="padding:15px; color:var(--muted);">Network error loading reports.</div>';
            });
    };

    window.vmoRefreshEmailDashboard = function() {
        const activeEl = document.getElementById('vmo-email-stat-active-campaigns');
        const sentEl = document.getElementById('vmo-email-stat-total-sent');
        const openEl = document.getElementById('vmo-email-stat-open-rate');
        const clickEl = document.getElementById('vmo-email-stat-click-rate');
        const container = document.querySelector('.vmo-campaign-list-container');

        if (container) {
            container.innerHTML = '<div style="padding:15px; color:var(--muted);">Loading campaigns…</div>';
        }

        // Metrics
        (function() {
            const fd = new FormData();
            fd.append('action', 'vmo_get_email_overview');
            fd.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : ''));
            return vmoFetchJson(ajaxurl, { method: 'POST', body: fd })
                .then(resp => {
                    const d = resp && resp.success ? resp.data : null;
                    if (!d) return;

                    const sent30 = Number(d.sent_30 || 0);
                    const opened30 = Number(d.opened_30 || 0);
                    const clicked30 = Number(d.clicked_30 || 0);
                    const openRate = sent30 > 0 ? Math.round((opened30 / sent30) * 1000) / 10 : 0;
                    const clickRate = opened30 > 0 ? Math.round((clicked30 / opened30) * 1000) / 10 : 0;

                    if (sentEl) sentEl.textContent = String(sent30);
                    if (openEl) openEl.textContent = String(openRate) + '%';
                    if (clickEl) clickEl.textContent = String(clickRate) + '%';
                })
                .catch(err => {
                    console.error('Metrics load error:', err);
                });
        })();

        // Campaign list
        const fd = new FormData();
        fd.append('action', 'vmo_get_email_overview');
        fd.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : ''));

        vmoFetchJson(ajaxurl, { method: 'POST', body: fd })
            .then(resp => {
                const payload = resp && resp.success ? resp.data : null;
                const campaigns = payload && Array.isArray(payload.campaigns) ? payload.campaigns : [];

                const activeCount = campaigns.filter(c => {
                    const status = String(c.status || '').toLowerCase();
                    return status && status !== 'draft';
                }).length;
                if (activeEl) activeEl.textContent = String(activeCount);

                if (!container) return;
                if (!campaigns.length) {
                    container.innerHTML = `
                        <div class="vmo-empty-state">
                            <div style="font-size: 32px; margin-bottom: 10px;">📭</div>
                            <p>No active campaigns. Start one from the AI Suggestions tab!</p>
                        </div>
                    `;
                    return;
                }

                const items = campaigns.map(c => {
                    const name = vmoEscapeHtml(c.title || c.campaign_name || 'Campaign');
                    const subject = vmoEscapeHtml(c.subject || '');
                    const status = vmoEscapeHtml(c.status || 'draft');
                    const sent = Number(c.sent || c.sent_count || 0);
                    const created = vmoEscapeHtml(c.created_at || '');
                    return `
                        <div style="background:rgba(0,0,0,0.18); border:1px solid var(--border); border-radius:12px; padding:14px; display:flex; flex-direction:column; gap:6px;">
                            <div style="display:flex; align-items:center; justify-content:space-between; gap:10px;">
                                <div style="font-weight:800;">${name}</div>
                                <div style="font-size:12px; color:var(--muted); text-transform:uppercase;">${status}</div>
                            </div>
                            ${subject ? `<div style="color:#cfe3ff; font-size:12px;">Subject: ${subject}</div>` : ''}
                            <div style="display:flex; gap:14px; flex-wrap:wrap; color:var(--muted); font-size:12px;">
                                <div>Sent: <span style="color:#e6f3ff;">${sent}</span></div>
                                ${created ? `<div>Created: <span style="color:#e6f3ff;">${created}</span></div>` : ''}
                            </div>
                        </div>
                    `;
                }).join('');

                container.innerHTML = `
                    <div style="display:flex; flex-direction:column; gap:12px;">
                        ${items}
                    </div>
                `;
            })
            .catch(err => {
                console.error('Campaign list load error:', err);
                if (container) {
                    container.innerHTML = '<div style="padding:15px; color:var(--muted);">Network error loading campaigns.</div>';
                }
            });
    };

    window.vmoOpenComposeModal = function() {
        const modal = document.getElementById('vmo-compose-modal');
        if (modal) modal.classList.add('vmo-show');
    };

    window.vmoCloseComposeModal = function() {
        const modal = document.getElementById('vmo-compose-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoSwitchComposeTab = function(tabName) {
        // Update buttons
        document.querySelectorAll('.vmo-tabs-nav .vmo-tab-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.getAttribute('onclick').includes(tabName)) {
                btn.classList.add('active');
            }
        });

        // Update content visibility
        document.querySelectorAll('.vmo-compose-tab').forEach(tab => {
            tab.style.display = 'none';
        });
        
        const activeTab = document.getElementById('vmo-compose-tab-' + tabName);
        if (activeTab) {
            activeTab.style.display = 'block';
            
            // If switching to preview, render the HTML
            if (tabName === 'preview') {
                const rawHtml = document.getElementById('vmo-compose-body').value;
                const previewFrame = document.getElementById('vmo-email-preview-frame');
                const format = vmoGetComposeFormat();
                if (format === 'plain') {
                    const escaped = vmoEscapeHtml(rawHtml || '');
                    previewFrame.innerHTML = escaped
                        ? '<pre style="white-space:pre-wrap; word-wrap:break-word; font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace; font-size:13px; line-height:1.5;">' + escaped + '</pre>'
                        : '<p style="color:#ccc; text-align:center; margin-top:50px;">No content to preview.</p>';
                } else {
                    // Basic sanitization could go here, but for admin tools we trust the user
                    previewFrame.innerHTML = rawHtml || '<p style="color:#ccc; text-align:center; margin-top:50px;">No content to preview.</p>';
                }
            }
        }
    };

    function vmoGetComposeFormat() {
        const el = document.querySelector('input[name="vmo-compose-format"]:checked');
        const val = el ? String(el.value || '') : 'html';
        return (val === 'plain') ? 'plain' : 'html';
    }

    function vmoSyncComposeBodyLabel() {
        const label = document.getElementById('vmo-compose-body-label');
        if (!label) return;
        const format = vmoGetComposeFormat();
        label.textContent = (format === 'plain') ? 'Message Body (Plain Text):' : 'Message Body (HTML Supported):';
    }

    // Ensure REST settings exist even if wpApiSettings is not localized on this page.
    // Missing/incorrect REST root/nonce can cause REST calls to return HTML (login/redirect pages) instead of JSON.
    (function vmoEnsureWpApiSettings() {
        try {
            if (!window.wpApiSettings) window.wpApiSettings = {};
            if (!window.wpApiSettings.root) window.wpApiSettings.root = <?php echo wp_json_encode( esc_url_raw( rest_url() ) ); ?>;
            if (!window.wpApiSettings.altRoot) window.wpApiSettings.altRoot = <?php echo wp_json_encode( esc_url_raw( home_url( '/?rest_route=/' ) ) ); ?>;
            if (!window.wpApiSettings.nonce) window.wpApiSettings.nonce = <?php echo wp_json_encode( wp_create_nonce( 'wp_rest' ) ); ?>;
        } catch (_) {
            // best-effort only
        }
    })();

    function vmoGetApiRoot() {
        return (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root : (window.location.origin + '/wp-json/');
    }

    function vmoGetWpNonce() {
        return (window.wpApiSettings && window.wpApiSettings.nonce) ? window.wpApiSettings.nonce : '';
    }

    function vmoGetInstallationId() {
        try {
            return (window.location && window.location.hostname) ? window.location.hostname : '';
        } catch (_) {
            return '';
        }
    }

    async function vmoFetchJson(url, options) {
        const opts = options || {};
        const headers = Object.assign({}, (opts.headers || {}));

        const nonce = vmoGetWpNonce();
        if (nonce && !headers['X-WP-Nonce']) {
            headers['X-WP-Nonce'] = nonce;
        }

        const res = await fetch(url, Object.assign({}, opts, {
            headers,
            credentials: 'same-origin'
        }));

        const text = await res.text();
        let data;
        try {
            data = text ? JSON.parse(text) : {};
        } catch (e) {
            // Some environments rewrite /wp-json/* to a normal HTML page (e.g., marketing/landing),
            // so retry once using the query-style REST route which bypasses rewrite rules.
            const alreadyRetried = !!opts._vmoRetried;
            const altRoot = (window.wpApiSettings && window.wpApiSettings.altRoot) ? String(window.wpApiSettings.altRoot) : '';
            if (!alreadyRetried && altRoot && String(url).includes('/wp-json/')) {
                const altUrl = String(url).replace(/\/wp-json\//, '/?rest_route=/');
                return vmoFetchJson(altUrl, Object.assign({}, opts, { _vmoRetried: true }));
            }
            const snippet = text ? String(text).slice(0, 220) : '(empty)';
            throw new Error('Non-JSON response (often login/redirect). Snippet: ' + snippet);
        }

        if (!res.ok) {
            const msg = (data && (data.message || (data.data && data.data.message)))
                ? (data.message || data.data.message)
                : ('HTTP ' + res.status);
            throw new Error(msg);
        }

        return data;
    }

    function vmoEscapeHtml(str) {
        return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#039;');
    }

    window.vmoOpenProductPicker = function() {
        const modal = document.getElementById('vmo-product-picker-modal');
        if (modal) modal.classList.add('vmo-show');
        vmoLoadProducts();
    };

    window.vmoCloseProductPicker = function() {
        const modal = document.getElementById('vmo-product-picker-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoLoadProducts = function() {
        const listEl = document.getElementById('vmo-product-picker-list');
        const statusEl = document.getElementById('vmo-product-picker-status');
        const searchEl = document.getElementById('vmo-product-search');
        if (!listEl || !statusEl) return;

        const apiRoot = vmoGetApiRoot();
        const nonce = vmoGetWpNonce();
        const search = searchEl ? (searchEl.value || '').trim() : '';

        statusEl.textContent = 'Loading products…';
        listEl.innerHTML = '';

        const url = new URL(apiRoot + 'vmo-manager/v1/store/products');
        if (search) url.searchParams.set('search', search);
        url.searchParams.set('per_page', '24');

        vmoFetchJson(url.toString(), {
            method: 'GET',
            headers: {
                'X-WP-Nonce': nonce
            }
        })
        .then(data => {
            if (!data || !data.success) {
                statusEl.textContent = (data && data.message) ? data.message : 'No products available.';
                return;
            }
            const products = Array.isArray(data.products) ? data.products : [];
            try {
                window.__vmoStoreProducts = products;
            } catch (_) {}
            if (!products.length) {
                statusEl.textContent = (data && data.message) ? data.message : 'No products found.';
                return;
            }
            statusEl.textContent = 'Select products to insert:';
            listEl.innerHTML = products.map(p => {
                const id = Number(p.id);
                const name = vmoEscapeHtml(p.name);
                const img = p.image_url ? `<img src="${vmoEscapeHtml(p.image_url)}" alt="${name}" style="width:100%; height:160px; object-fit:cover; border-radius:10px;" />` : '';
                const price = p.price_display ? vmoEscapeHtml(p.price_display) : '';
                const desc = p.description ? vmoEscapeHtml(p.description).slice(0, 140) : '';
                return `
                    <div class="vmo-card" style="background:rgba(255,255,255,.02)">
                        <label style="display:flex; gap:10px; cursor:pointer; align-items:flex-start;">
                            <input type="checkbox" class="vmo-product-pick" value="${id}" style="margin-top:6px;">
                            <div style="flex:1; min-width:0;">
                                ${img}
                                <div style="margin-top:10px; font-weight:700;">${name}</div>
                                <div style="margin-top:4px; color:var(--cyan-soft);">${price}</div>
                                ${desc ? `<div style="margin-top:6px; color:var(--muted); font-size:12px;">${desc}</div>` : ''}
                            </div>
                        </label>
                        <div style="margin-top:10px; display:flex; gap:8px; flex-wrap:wrap;">
                            ${p.buy_url ? `<a class="action-btn primary" href="${vmoEscapeHtml(p.buy_url)}" target="_blank" rel="noopener">Buy link</a>` : ''}
                            ${p.store_url ? `<a class="action-btn" href="${vmoEscapeHtml(p.store_url)}" target="_blank" rel="noopener">View store</a>` : ''}
                        </div>
                    </div>
                `;
            }).join('');
        })
        .catch(err => {
            console.error('Product load error:', err);
            statusEl.textContent = 'Network error loading products.';
        });
    };

    window.vmoInsertSelectedProducts = function() {
        const checks = Array.from(document.querySelectorAll('.vmo-product-pick:checked'));
        if (!checks.length) {
            alert('Please select at least one product.');
            return;
        }

        const ids = checks.map(c => Number(c.value)).filter(Boolean);
        const cached = (function(){ try { return Array.isArray(window.__vmoStoreProducts) ? window.__vmoStoreProducts : []; } catch(_) { return []; } })();
        const selected = cached.filter(p => ids.includes(Number(p.id)));

        if (!selected.length) {
            alert('Selected products are no longer loaded. Please search again and re-select.');
            return;
        }

        try {
            if (!selected.length) {
                alert('Could not load selected product details.');
                return;
            }

            const cards = selected.map(p => {
                const name = vmoEscapeHtml(p.name);
                const img = p.image_url ? `<img src="${vmoEscapeHtml(p.image_url)}" alt="${name}" style="width:100%; max-width:560px; height:auto; border-radius:10px; display:block; margin:0 auto;" />` : '';
                const price = p.price_display ? vmoEscapeHtml(p.price_display) : '';
                const desc = p.description ? vmoEscapeHtml(p.description) : '';
                const href = p.buy_url || p.store_url || '#';
                const btnLabel = p.buy_url ? 'Buy now' : 'View store';

                return `
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin: 20px 0; background: #f9f9f9; border-radius: 12px; overflow: hidden;">
  <tr>
    <td style="padding: 18px; text-align: center; font-family: Arial, sans-serif; color:#333;">
      ${img}
      <h3 style="margin: 14px 0 6px;">${name}</h3>
      ${price ? `<div style="margin: 6px 0 12px; font-size: 18px; font-weight: bold; color:#2271b1;">${price}</div>` : ''}
      ${desc ? `<p style="margin: 0 0 14px; color:#666;">${desc}</p>` : ''}
            <a href="${vmoEscapeHtml(href)}" style="background-color: #2271b1; color: white; padding: 12px 22px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;">${btnLabel}</a>
    </td>
  </tr>
</table>`;
            }).join('\n');

            const bodyField = document.getElementById('vmo-compose-body');
            bodyField.value += '\n' + cards + '\n';
            vmoCloseProductPicker();
            vmoSwitchComposeTab('preview');
        } catch (err) {
            console.error('Insert products error:', err);
            alert('Error while inserting products.');
        }
    };

    window.vmoInsertCheckoutLink = function() {
        const apiRoot = vmoGetApiRoot();
        const nonce = vmoGetWpNonce();
        vmoFetchJson(apiRoot + 'vmo-manager/v1/store/checkout', {
            method: 'GET',
            headers: { 'X-WP-Nonce': nonce }
        })
        .then(data => {
            const url = (data && data.success && data.store_url) ? data.store_url : (window.location.origin + '/store');
            const html = `
<div style="text-align:center; margin: 24px 0;">
  <a href="${vmoEscapeHtml(url)}" style="background:#0fe1ff; color:#001018; padding: 14px 26px; border-radius: 10px; text-decoration:none; font-weight:800; display:inline-block;">Checkout</a>
</div>`;
            const bodyField = document.getElementById('vmo-compose-body');
            bodyField.value += '\n' + html + '\n';
            vmoSwitchComposeTab('preview');
        })
        .catch(err => {
            console.error('Checkout link error:', err);
            alert('Network error while inserting checkout link.');
        });
    };

    window.vmoGenerateEmailContent = function() {
        const intent = document.getElementById('vmo-compose-intent').value;
        const theme = document.getElementById('vmo-compose-theme').value;
        const format = vmoGetComposeFormat();
        const btn = event && event.target ? event.target : null;
        
        if (!intent) {
            alert('Please describe what you want the AI to write.');
            return;
        }

        if (btn) { btn.innerHTML = 'Generating...'; btn.disabled = true; }

        const apiRoot = vmoGetApiRoot();
        const installationId = vmoGetInstallationId();
        const nonce = vmoGetWpNonce();
        const themeLabel = (document.querySelector('#vmo-compose-theme option:checked') || {}).textContent || theme;

        const system = (format === 'plain')
            ? {
                role: 'system',
                content: 'You write marketing emails. Return ONLY valid JSON with keys: subject (string), text (string). The text must be plain text (no HTML).'
            }
            : {
                role: 'system',
                content: 'You write marketing emails. Return ONLY valid JSON with keys: subject (string), html (string). The html must be email-client-safe (table-based layout, inline styles, no external CSS/JS), max width 600px. Include: (1) preheader (hidden), (2) header/brand, (3) hero section with an <img> tag whose src is exactly {{HERO_IMAGE_URL}}, (4) body copy, (5) a primary CTA button, (6) optional product section placeholder exactly {{PRODUCT_BLOCKS}} (put it where product cards should appear), (7) footer with a simple unsubscribe placeholder link href="{{UNSUBSCRIBE_URL}}". For motion/parallax: do NOT use JS; if you want motion, design it so it still looks good without animation (e.g., animated hero image/GIF fallback or subtle gradient styling).'
            };
        const user = (format === 'plain')
            ? {
                role: 'user',
                content: `Create an email draft. Theme: ${themeLabel}. Intent: ${intent}. Include a clear CTA. Return JSON only.`
            }
            : {
                role: 'user',
                content: `Create an email draft. Theme: ${themeLabel}. Intent: ${intent}. Include a clear CTA. Use email-safe HTML with inline styles only. Return JSON only.`
            };

        const payload = {
            chat: [system, user],
            is_refinement: false
        };

        const heroPrompt = `Email hero image for theme ${themeLabel}. Based on: ${intent}. Clean, high-quality, no text overlay.`;

        const headers = {
            'Content-Type': 'application/json',
            'X-VMO-Installation-ID': installationId,
            'X-WP-Nonce': nonce
        };

        const genPromise = vmoFetchJson(apiRoot + 'vmo-manager/v1/generate', { method: 'POST', headers, body: JSON.stringify(payload) });
        const imgPromise = (format === 'plain')
            ? Promise.resolve(null)
            : vmoFetchJson(apiRoot + 'vmo-manager/v1/image', { method: 'POST', headers, body: JSON.stringify({ description: heroPrompt }) });

        Promise.all([genPromise, imgPromise])
        .then(([gen, img]) => {
            if (!gen || !gen.success || !gen.html) {
                throw new Error((gen && gen.message) ? gen.message : 'AI generation failed');
            }
            let parsed;
            try {
                parsed = JSON.parse(gen.html);
            } catch (_) {
                // Some models may return raw text/html; accept it as body
                parsed = (format === 'plain')
                    ? { subject: 'Draft Email', text: String(gen.html) }
                    : { subject: 'Draft Email', html: String(gen.html) };
            }
            const subject = parsed.subject || 'Draft Email';
            if (format === 'plain') {
                const text = parsed.text || '';
                document.getElementById('vmo-compose-subject').value = subject;
                document.getElementById('vmo-compose-body').value = text;
            } else {
                let html = parsed.html || '';
                const heroUrl = (img && (img.image_url || img.url)) ? (img.image_url || img.url) : (img && img.success && img.image_url ? img.image_url : '');
                if (heroUrl) {
                    if (/\{\{HERO_IMAGE_URL\}\}/.test(html)) {
                        html = html.replace(/\{\{HERO_IMAGE_URL\}\}/g, heroUrl);
                    } else {
                        const heroTag = `<div style="text-align:center; padding: 0 0 16px;"><img src="${vmoEscapeHtml(heroUrl)}" alt="" style="max-width:100%; height:auto; border-radius: 12px; display:block; margin:0 auto;" /></div>`;
                        html = heroTag + html;
                    }
                } else {
                    html = html.replace(/\{\{HERO_IMAGE_URL\}\}/g, '');
                }

                document.getElementById('vmo-compose-subject').value = subject;
                document.getElementById('vmo-compose-body').value = html;
            }
            vmoSwitchComposeTab('preview');
        })
        .catch(err => {
            console.error('Compose generate error:', err);
            alert('Error generating draft: ' + (err && err.message ? err.message : 'Unknown error'));
        })
        .finally(() => {
            if (btn) { btn.innerHTML = 'Generate Draft'; btn.disabled = false; }
        });
    };

    window.vmoRegenerateEmailVariant = function() {
        const refine = (document.getElementById('vmo-compose-refine').value || '').trim();
        const theme = document.getElementById('vmo-compose-theme').value;
        const themeLabel = (document.querySelector('#vmo-compose-theme option:checked') || {}).textContent || theme;
        const currentSubject = document.getElementById('vmo-compose-subject').value || '';
        const currentHtml = document.getElementById('vmo-compose-body').value || '';
        const intent = document.getElementById('vmo-compose-intent').value || '';
        const format = vmoGetComposeFormat();
        const btn = event && event.target ? event.target : null;

        if (!refine) {
            alert('Please enter a refinement prompt.');
            return;
        }
        if (!currentHtml) {
            alert('Generate a draft first, then refine.');
            return;
        }

        if (btn) { btn.innerHTML = 'Regenerating...'; btn.disabled = true; }

        const apiRoot = vmoGetApiRoot();
        const installationId = vmoGetInstallationId();
        const nonce = vmoGetWpNonce();

        const system = (format === 'plain')
            ? {
                role: 'system',
                content: 'You refine marketing emails. Return ONLY valid JSON with keys: subject (string), text (string). The text must be plain text (no HTML).'
            }
            : {
                role: 'system',
                content: 'You refine marketing emails. Return ONLY valid JSON with keys: subject (string), html (string). Keep email-safe HTML (inline styles, max 600px). Keep or replace the hero image placeholder string exactly: {{HERO_IMAGE_URL}} in an <img> tag.'
            };
        const user = (format === 'plain')
            ? {
                role: 'user',
                content: `Refine this email variant. Theme: ${themeLabel}. Original intent: ${intent}. Current subject: ${currentSubject}. Instructions: ${refine}. Current text follows:\n\n${currentHtml}\n\nReturn JSON only.`
            }
            : {
                role: 'user',
                content: `Refine this email variant. Theme: ${themeLabel}. Original intent: ${intent}. Current subject: ${currentSubject}. Instructions: ${refine}. Current HTML follows:\n\n${currentHtml}\n\nReturn JSON only.`
            };

        const payload = {
            chat: [system, user],
            is_refinement: true
        };

        const heroPrompt = `Email hero image variant for theme ${themeLabel}. Based on: ${intent}. Refinement: ${refine}. No text overlay.`;

        const headers = {
            'Content-Type': 'application/json',
            'X-VMO-Installation-ID': installationId,
            'X-WP-Nonce': nonce
        };

        const genPromise = vmoFetchJson(apiRoot + 'vmo-manager/v1/generate', { method: 'POST', headers, body: JSON.stringify(payload) });
        const imgPromise = (format === 'plain')
            ? Promise.resolve(null)
            : vmoFetchJson(apiRoot + 'vmo-manager/v1/image', { method: 'POST', headers, body: JSON.stringify({ description: heroPrompt }) });

        Promise.all([genPromise, imgPromise])
        .then(([gen, img]) => {
            if (!gen || !gen.success || !gen.html) {
                throw new Error((gen && gen.message) ? gen.message : 'AI refinement failed');
            }
            let parsed;
            try {
                parsed = JSON.parse(gen.html);
            } catch (_) {
                parsed = (format === 'plain')
                    ? { subject: currentSubject || 'Draft Email', text: String(gen.html) }
                    : { subject: currentSubject || 'Draft Email', html: String(gen.html) };
            }
            const subject = parsed.subject || (currentSubject || 'Draft Email');
            if (format === 'plain') {
                const text = parsed.text || '';
                document.getElementById('vmo-compose-subject').value = subject;
                document.getElementById('vmo-compose-body').value = text;
            } else {
                let html = parsed.html || '';
                const heroUrl = (img && (img.image_url || img.url)) ? (img.image_url || img.url) : (img && img.success && img.image_url ? img.image_url : '');
                if (heroUrl) {
                    if (/\{\{HERO_IMAGE_URL\}\}/.test(html)) {
                        html = html.replace(/\{\{HERO_IMAGE_URL\}\}/g, heroUrl);
                    } else {
                        const heroTag = `<div style="text-align:center; padding: 0 0 16px;"><img src="${vmoEscapeHtml(heroUrl)}" alt="" style="max-width:100%; height:auto; border-radius: 12px; display:block; margin:0 auto;" /></div>`;
                        html = heroTag + html;
                    }
                } else {
                    html = html.replace(/\{\{HERO_IMAGE_URL\}\}/g, '');
                }

                document.getElementById('vmo-compose-subject').value = subject;
                document.getElementById('vmo-compose-body').value = html;
            }
            vmoSwitchComposeTab('preview');
        })
        .catch(err => {
            console.error('Compose refine error:', err);
            alert('Error regenerating variant: ' + (err && err.message ? err.message : 'Unknown error'));
        })
        .finally(() => {
            if (btn) { btn.innerHTML = 'Regenerate Variant'; btn.disabled = false; }
        });
    };

    window.vmoSendEmail = function() {
        const to = document.getElementById('vmo-compose-to').value;
        const subject = document.getElementById('vmo-compose-subject').value;
        const body = document.getElementById('vmo-compose-body').value;
        const schedule = document.getElementById('vmo-compose-schedule').value;
        const btn = event.target;

        // Prefer the compose-modal's own From selector, then fall back to sidebar account selector.
        let fromEmail = '';
        try {
            const composeSel = document.getElementById('vmo-compose-from');
            if (composeSel && composeSel.value) fromEmail = String(composeSel.value).trim();
        } catch (e) { fromEmail = ''; }
        if (!fromEmail) {
            try {
                const sel = document.querySelector('.vmo-account-selector');
                if (sel && sel.value) fromEmail = String(sel.value).trim();
            } catch (e) { fromEmail = ''; }
        }

        // Allow testing/generation without consultation, but require a configured sending identity to actually send.
        if (!fromEmail) {
            alert('No sending email account is selected/configured yet. You can generate and preview templates now, but to send you must complete email setup (consultation) and select a sending account.');
            return;
        }
        
        if (!to || !subject || !body) {
            alert('Please fill in all required fields.');
            return;
        }

        const originalText = btn.innerHTML;
        btn.innerHTML = 'Sending...';
        btn.disabled = true;

        const payload = {
            to: to,
            subject: subject,
            message: body,
            type: 'transactional'
        };

        if (fromEmail) {
            payload.from_email = fromEmail;
        }

        if (schedule) {
            payload.schedule = schedule;
        }

        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 : '';

        vmoFetchJson(apiRoot + 'vmo-manager/v1/emails/send', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': nonce
            },
            body: JSON.stringify(payload)
        })
        .then(data => {
            if (data.success || data.sent) {
                alert(schedule ? 'Email scheduled successfully!' : 'Email sent successfully!');
                vmoCloseComposeModal();
                // Clear fields
                document.getElementById('vmo-compose-to').value = '';
                document.getElementById('vmo-compose-subject').value = '';
                document.getElementById('vmo-compose-body').value = '';
                document.getElementById('vmo-compose-schedule').value = '';
            } else {
                alert('Error sending email: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(err => {
            console.error('Email send error:', err);
            alert('Network error occurred while sending email.');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    };

    // Initialize event listeners when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        // Keep composer label in sync with draft format
        document.querySelectorAll('input[name="vmo-compose-format"]').forEach(r => {
            r.addEventListener('change', vmoSyncComposeBodyLabel);
        });
        vmoSyncComposeBodyLabel();

        // 1. Tools Pill Click
        const toolsPill = document.querySelector('.vmo-pill[data-view="tools"]');
        if (toolsPill) {
            toolsPill.addEventListener('click', function(e) {
                e.preventDefault();
                vmoOpenToolsModal();
            });
            toolsPill.style.cursor = 'pointer';
        }

        // 2. Close Buttons
        const closeToolsBtn = document.getElementById('vmo-close-tools-btn');
        if (closeToolsBtn) {
            closeToolsBtn.addEventListener('click', vmoCloseToolsModal);
        }

        const closeEmailBtn = document.getElementById('vmo-close-email-btn');
        if (closeEmailBtn) {
            closeEmailBtn.addEventListener('click', vmoCloseEmailTool);
        }

        // 3. Open Email Tool Button
        const openEmailBtn = document.getElementById('vmo-open-email-tool-btn');
        if (openEmailBtn) {
            openEmailBtn.addEventListener('click', vmoOpenEmailTool);
        }

        // 4. Close on click outside
        window.addEventListener('click', function(event) {
            if (event.target.classList.contains('vmo-tools-overlay')) {
                event.target.classList.remove('vmo-show');
            }
        });
    });
})();
</script>

<script>
(function() {
    window.vmoOpenPowerDialer = function() {
        // Open the Power Dialer interface (if integrated directly in modal)
        // OR redirect to the dedicated Power Dialer page/view.
        // Assuming user asked for it to be integrated into the tools modal flow.
        const pdModal = document.getElementById('vmo-power-dialer-modal');
        if (pdModal) {
             pdModal.classList.add('vmo-show');
        } else {
             // Fallback: If no modal exists, emulate redirect to CRM/Dialer tab
             // Find CRM nav button and click it, then switch to Dialer sub-tab
             const crmBtn = document.querySelector('[data-view="crm"]');
             if(crmBtn) crmBtn.click();
             setTimeout(() => {
                 // Logic to switch to 'Dialer' tab inside CRM if it exists
                 // For now, notify user
                 if(typeof notify === 'function') notify('Opening Sales Dialer...', 'success');
             }, 500);
        }
    };

    window.vmoOpenPdfModal = function() {
        const modal = document.getElementById('vmo-pdf-modal');
        if (modal) modal.classList.add('vmo-show');
    };

    window.vmoClosePdfModal = function() {
        const modal = document.getElementById('vmo-pdf-modal');
        if (modal) modal.classList.remove('vmo-show');
    };

    window.vmoUpdatePdfPreview = function() {
        const source = document.getElementById('vmo-pdf-source').value;
        const preview = document.getElementById('vmo-pdf-preview');
        preview.innerHTML = source;
    };

    window.vmoToggleOrientation = function() {
        const isLandscape = document.getElementById('vmo-pdf-landscape').checked;
        const preview = document.getElementById('vmo-pdf-preview');
        
        if (isLandscape) {
            // Landscape: Wider aspect ratio (approx A4 landscape)
            preview.style.width = '800px'; 
            preview.style.minHeight = '565px'; // Aspect ratio ~1.414
        } else {
            // Portrait: Taller aspect ratio (approx A4 portrait)
            preview.style.width = '100%'; // Fit to container width
            preview.style.minHeight = '100%';
        }
    };

    window.vmoGeneratePDF = function() {
        const element = document.getElementById('vmo-pdf-preview');
        const isLandscape = document.getElementById('vmo-pdf-landscape').checked;
        
        const opt = {
            margin:       0.5,
            filename:     'vmo-document.pdf',
            image:        { type: 'jpeg', quality: 0.98 },
            html2canvas:  { scale: 2, useCORS: true, logging: true },
            jsPDF:        { unit: 'in', format: 'letter', orientation: isLandscape ? 'landscape' : 'portrait' }
        };

        // Show loading state
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.innerHTML = '⏳ Generating...';
        btn.disabled = true;

        if (typeof html2pdf === 'undefined') {
            alert('PDF library not loaded. Please check your internet connection.');
            btn.innerHTML = originalText;
            btn.disabled = false;
            return;
        }

        html2pdf().set(opt).from(element).save().then(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        }).catch(err => {
            console.error(err);
            alert('Error generating PDF. Check console for details.');
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    };

    // Auto-update preview on paste
    document.addEventListener('DOMContentLoaded', function() {
        const pdfSource = document.getElementById('vmo-pdf-source');
        if (pdfSource) {
            pdfSource.addEventListener('input', function() {
                clearTimeout(window.vmoPreviewTimeout);
                window.vmoPreviewTimeout = setTimeout(vmoUpdatePdfPreview, 1000);
            });
        }
    });
})();
</script>

