<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// [VMO_TOOLS_ENQUEUE_MEDIA] Make sure WP Media Library scripts are present on
// any admin surface that includes this template, so the Signature Maker's
// "Choose from Media Library" button always opens the real picker.
if ( function_exists( 'wp_enqueue_media' ) ) { wp_enqueue_media(); }
?>
<!-- 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>
            <!-- Bulk SMS Marketing Tool Card -->
            <div class="vmo-tool-card" onclick="if(typeof vmoGateCheck==='function'&&!vmoGateCheck('sms_marketing'))return;vmoCloseToolsModal(); setTimeout(function(){ window.vmoOpenSMSMarketingModal(); }, 100);">
                <div class="vmo-tool-icon">💬</div>
                <div class="vmo-tool-info">
                    <h4>Bulk SMS Marketing</h4>
                    <p>Send targeted SMS campaigns to your contacts via Twilio.</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); display:flex; gap:8px; flex-wrap:wrap;">
                <button class="vmo-btn vmo-btn-primary" onclick="vmoSaveSignature(event)" style="flex:1; min-width:160px;">💾 Save Signature</button>
                <button class="vmo-btn vmo-btn-secondary" onclick="vmoSaveAndInsertSignature(event)" style="flex:1; min-width:200px;" title="Save the signature and append it to the email you are currently composing">💾 Save &amp; Insert into Email</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>
            <button class="vmo-tab-btn" onclick="vmoSwitchComposeTab('drafts')">📂 Drafts</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 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);">Cc:</label>
                            <input type="text" id="vmo-compose-cc" class="vmo-input" placeholder="Optional" style="width:100%; padding:10px;">
                        </div>
                        <div style="flex:1; min-width:200px;">
                            <label style="display:block; margin-bottom:4px; font-weight:600; font-size:13px; color:var(--muted);">Bcc:</label>
                            <input type="text" id="vmo-compose-bcc" class="vmo-input" placeholder="Optional" style="width:100%; padding:10px;">
                        </div>
                    </div>
                </div>

                <div id="vmo-compose-toolbar" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:14px; padding:10px; border:1px solid var(--border); border-radius:10px; background:rgba(255,255,255,0.03);">
                    <button class="vmo-btn-small" onclick="vmoOpenEmailAssistant()">&#10024; Ask VMO to Write This Email</button>
                    <button class="vmo-btn-small" onclick="vmoSwitchComposeTab('templates')">Templates</button>
                    <button class="vmo-btn-small" onclick="vmoOpenProductPicker()">Products</button>
                    <button class="vmo-btn-small" onclick="vmoInsertCheckoutLink()">Checkout</button>
                    <button class="vmo-btn-small" onclick="vmoOpenSignatureModal()">Signature</button>
                    <label class="vmo-btn-small" style="cursor:pointer; margin:0;">Attach<input type="file" id="vmo-compose-attachment-toolbar" style="display:none;" multiple></label>
                    <button class="vmo-btn-small" onclick="vmoSwitchComposeTab('preview')">Preview</button>
                </div>

                <div id="vmo-compose-design-controls" style="display:flex; gap:10px; margin-top:10px; flex-wrap:wrap; padding:10px; border:1px solid var(--border); border-radius:10px; background:rgba(15,225,255,0.04);">
                    <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;">
                            <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_friendly">Warm & Friendly</option>
                            <option value="dark_mode">Dark Mode</option>
                            <option value="glassmorphism_inspired">Glassmorphism-inspired</option>
                            <option value="gradient_flow">Gradient Flow</option>
                            <option value="editorial">Editorial</option>
                            <option value="product_showcase">Product Showcase</option>
                            <option value="event_invitation">Event / Invitation</option>
                            <option value="seasonal_holiday">Seasonal / Holiday</option>
                            <option value="black_friday">Black Friday</option>
                            <option value="restaurant_food">Restaurant / Food</option>
                            <option value="service_business">Service Business</option>
                            <option value="appointment_booking">Appointment / Booking</option>
                            <option value="nonprofit_donation">Nonprofit / Donation</option>
                        </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="follow_up">Follow-Up</option>
                                <option value="thank_you">Thank You</option>
                                <option value="announcement">Announcement</option>
                                <option value="newsletter">Newsletter</option>
                            </optgroup>
                            <optgroup label="Sales / 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="review_request">Review Request</option>
                                <option value="restock_alert">Restock Alert</option>
                            </optgroup>
                            <optgroup label="Business">
                                <option value="welcome_series">Welcome Series</option>
                                <option value="event_invitation">Event Invitation</option>
                                <option value="case_study">Case Study / Testimonial</option>
                                <option value="referral_program">Referral Program</option>
                                <option value="survey_feedback">Survey / Feedback</option>
                            </optgroup>
                            <optgroup label="Seasonal / Holiday">
                                <option value="christmas">🎄 Christmas</option>
                                <option value="halloween">🎃 Halloween</option>
                                <option value="valentine">💝 Valentine's Day</option>
                                <option value="new_year">🥂 New Year</option>
                                <option value="thanksgiving">🦃 Thanksgiving</option>
                                <option value="easter">🐰 Easter / Spring</option>
                                <option value="mothers_day">💐 Mother's Day</option>
                                <option value="fathers_day">👔 Father's Day</option>
                                <option value="birthday">🎂 Customer Birthday</option>
                                <option value="back_to_school">🎒 Back to School</option>
                            </optgroup>
                        </select>
                    </div>
                </div>

                <!-- AI Generation Section -->
                <div id="vmo-compose-ai-legacy-panel" style="display:none; 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>

                    <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>

                <!-- Template Customizer (visible only after a template is loaded) -->
                <div id="vmo-template-customizer" style="display:none; margin-top:15px; padding:14px 16px; background:rgba(15,225,255,0.06); border:1px solid var(--border); border-radius:12px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; flex-wrap:wrap; gap:8px;">
                        <strong style="color:var(--cyan); font-size:13px;">🎨 Template Customizer</strong>
                        <span id="vmo-template-customizer-name" style="font-size:11px; color:var(--muted);"></span>
                    </div>
                    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); gap:10px;">
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>CTA Button Text</span>
                            <input type="text" id="vmo-tpl-cta-text" class="vmo-input" placeholder="Shop the offer" style="width:100%; padding:6px 8px; font-size:13px;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted); grid-column:span 2;">
                            <span>CTA Link (where the button takes the reader)</span>
                            <input type="url" id="vmo-tpl-cta-url" class="vmo-input" placeholder="https://yourbusiness.com/flash-sale" style="width:100%; padding:6px 8px; font-size:13px;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>Header Background</span>
                            <input type="color" id="vmo-tpl-header-bg" value="#0f172a" style="width:100%; height:34px; border:none; background:none; padding:0;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>Header Text Color</span>
                            <input type="color" id="vmo-tpl-header-color" value="#ffffff" style="width:100%; height:34px; border:none; background:none; padding:0;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>Button Background</span>
                            <input type="color" id="vmo-tpl-cta-bg" value="#0ea5e9" style="width:100%; height:34px; border:none; background:none; padding:0;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>Button Text Color</span>
                            <input type="color" id="vmo-tpl-cta-color" value="#ffffff" style="width:100%; height:34px; border:none; background:none; padding:0;">
                        </label>
                        <label style="display:flex; flex-direction:column; gap:4px; font-size:11px; color:var(--muted);">
                            <span>Accent / Eyebrow</span>
                            <input type="color" id="vmo-tpl-accent" value="#7dd3fc" style="width:100%; height:34px; border:none; background:none; padding:0;">
                        </label>
                    </div>
                    <div style="display:flex; gap:8px; margin-top:10px; flex-wrap:wrap;">
                        <button class="vmo-btn-small" onclick="vmoApplyTemplateCustomizations()">Apply changes</button>
                        <button class="vmo-btn-small" onclick="vmoResetTemplateCustomizations()">Reset to template defaults</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="vmoSetEditorMode('visual')" title="Visual editor">Visual</button>
                            <button class="vmo-btn-small" onclick="vmoSetEditorMode('html')" title="HTML editor">HTML</button>
                            <button class="vmo-btn-small" onclick="vmoApplyEditorCommand('bold')" title="Bold">B</button>
                            <button class="vmo-btn-small" onclick="vmoApplyEditorCommand('italic')" title="Italic">I</button>
                            <button class="vmo-btn-small" onclick="vmoApplyEditorCommand('createLink')" title="Link">Link</button>
                        </div>
                    </div>
                    <div id="vmo-compose-visual-editor" contenteditable="true" class="vmo-input" style="width:100%; min-height:320px; background:#fff; color:#111; border-radius:10px; padding:18px; line-height:1.6; overflow:auto;" data-placeholder="Write your email here..."></div>
                    <textarea id="vmo-compose-body" class="vmo-input" rows="18" placeholder="HTML source" style="display:none; width:100%; font-family:monospace; font-size:13px; line-height:1.5; resize:vertical; min-height:320px;"></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>
                    <button class="vmo-btn-small" onclick="vmoPreviewDevice('plain', this)">Plain Text</button>
                    <button class="vmo-btn-small" onclick="vmoPreviewDevice('inbox', this)">Inbox Preview</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>
                    <!-- Seasonal templates: each ships with its own palette + motif -->
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('christmas')" style="background:linear-gradient(135deg, rgba(127,29,29,0.25), rgba(21,128,61,0.18)); border:1px solid #15803d; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🎄</div>
                        <h4 style="margin:0 0 4px; color:#fff; font-size:14px;">Christmas</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Festive red & green, holiday gifts, season offer</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('halloween')" style="background:linear-gradient(135deg, rgba(124,45,18,0.35), rgba(28,25,23,0.45)); border:1px solid #fb923c; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🎃</div>
                        <h4 style="margin:0 0 4px; color:#fb923c; font-size:14px;">Halloween</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Dark orange & purple, spooky savings</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('valentine')" style="background:linear-gradient(135deg, rgba(157,23,77,0.3), rgba(225,29,72,0.2)); border:1px solid #fbcfe8; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">💝</div>
                        <h4 style="margin:0 0 4px; color:#fbcfe8; font-size:14px;">Valentine's Day</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Romantic pink & red, gift ideas</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('new_year')" style="background:linear-gradient(135deg, rgba(12,10,9,0.5), rgba(202,138,4,0.25)); border:1px solid #fbbf24; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🥂</div>
                        <h4 style="margin:0 0 4px; color:#fde68a; font-size:14px;">New Year</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Gold & navy, fresh-start offer</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('thanksgiving')" style="background:linear-gradient(135deg, rgba(124,45,18,0.3), rgba(194,65,12,0.2)); border:1px solid #fed7aa; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🦃</div>
                        <h4 style="margin:0 0 4px; color:#fed7aa; font-size:14px;">Thanksgiving</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Warm autumn tones, gratitude</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('easter')" style="background:linear-gradient(135deg, rgba(134,25,143,0.25), rgba(240,171,252,0.15)); border:1px solid #f0abfc; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🐰</div>
                        <h4 style="margin:0 0 4px; color:#f0abfc; font-size:14px;">Easter / Spring</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Pastel renewal, fresh picks</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('mothers_day')" style="background:linear-gradient(135deg, rgba(190,24,93,0.25), rgba(251,207,232,0.18)); border:1px solid #fbcfe8; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">💐</div>
                        <h4 style="margin:0 0 4px; color:#fbcfe8; font-size:14px;">Mother's Day</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Soft pink, gifts for moms</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('fathers_day')" style="background:linear-gradient(135deg, rgba(30,58,138,0.3), rgba(29,78,216,0.2)); border:1px solid #bfdbfe; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">👔</div>
                        <h4 style="margin:0 0 4px; color:#bfdbfe; font-size:14px;">Father's Day</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Bold navy, gifts for dads</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('birthday')" style="background:linear-gradient(135deg, rgba(88,28,135,0.3), rgba(147,51,234,0.2)); border:1px solid #f0abfc; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🎂</div>
                        <h4 style="margin:0 0 4px; color:#f0abfc; font-size:14px;">Customer Birthday</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Confetti, exclusive birthday gift</p>
                    </div>
                    <div class="vmo-template-card" onclick="vmoSelectTemplate('back_to_school')" style="background:linear-gradient(135deg, rgba(30,64,175,0.25), rgba(234,179,8,0.18)); border:1px solid #fde047; border-radius:12px; padding:20px; cursor:pointer; transition:all 0.2s; text-align:center;" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='none'">
                        <div style="font-size:32px; margin-bottom:8px;">🎒</div>
                        <h4 style="margin:0 0 4px; color:#fde047; font-size:14px;">Back to School</h4>
                        <p style="margin:0; color:var(--muted); font-size:11px;">Bright yellow & blue, must-haves</p>
                    </div>
                </div>
            </div>

            <!-- DRAFTS TAB -->
            <div id="vmo-compose-tab-drafts" class="vmo-compose-tab" style="display:none;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; gap:10px; flex-wrap:wrap;">
                    <div>
                        <h4 style="margin:0 0 4px;">Saved drafts</h4>
                        <p style="margin:0; color:var(--muted); font-size:12px;">Drafts are saved in your VMO mailbox. Open one to keep editing or send it.</p>
                    </div>
                    <button class="vmo-btn-small" onclick="vmoLoadEmailDrafts()">↻ Refresh</button>
                </div>
                <div id="vmo-compose-drafts-list" style="display:flex; flex-direction:column; gap:10px;">
                    <div style="color:var(--muted); text-align:center; padding:30px;">Loading drafts…</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 the current message as a draft you can re-open later">💾 Save as 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>
// [VMO_GLOBAL_ESCAPE_HTML] Defined at the top so every helper below
// (vmoPreviewDevice, template starters, mailbox renderers, etc.) can call
// it regardless of which IIFE wraps them. Previously vmoEscapeHtml lived
// only inside one IIFE and threw "vmoEscapeHtml is not defined" when
// vmoPreviewDevice (top-level) tried to use it.
window.vmoEscapeHtml = window.vmoEscapeHtml || function(str) {
    return String(str == null ? '' : str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
};
if (typeof vmoEscapeHtml === 'undefined') { var vmoEscapeHtml = window.vmoEscapeHtml; }

window.vmoToast = window.vmoToast || function(message, type) {
    var wrap = document.getElementById('vmo-toast-container');
    if (!wrap) {
        wrap = document.createElement('div');
        wrap.id = 'vmo-toast-container';
        wrap.style.cssText = 'position:fixed;right:18px;bottom:18px;z-index:999999;display:flex;flex-direction:column;gap:10px;max-width:360px;';
        document.body.appendChild(wrap);
    }
    var toast = document.createElement('div');
    var bg = type === 'error' ? 'rgba(180,35,24,.96)' : (type === 'success' ? 'rgba(22,101,52,.96)' : 'rgba(15,23,42,.96)');
    toast.style.cssText = 'background:' + bg + ';color:#fff;border:1px solid rgba(255,255,255,.18);border-radius:10px;padding:12px 14px;box-shadow:0 12px 30px rgba(0,0,0,.25);font-size:13px;line-height:1.4;';
    toast.textContent = message || 'Done';
    wrap.appendChild(toast);
    setTimeout(function(){ toast.style.opacity = '0'; toast.style.transform = 'translateY(6px)'; }, 3600);
    setTimeout(function(){ if (toast && toast.parentNode) toast.parentNode.removeChild(toast); }, 4300);
};
if (!window.__vmoNativeAlert) {
    window.__vmoNativeAlert = window.alert;
    window.alert = function(message) {
        window.vmoToast(String(message || ''), 'error');
    };
}

window.vmoConsultationUrl = window.vmoConsultationUrl || '<?php echo esc_js(admin_url('admin.php?page=vmo-ai-builder-main')); ?>';
window.vmoMyPlanUrl = window.vmoMyPlanUrl || '<?php echo esc_js(admin_url('admin.php?page=vmo-my-plan')); ?>';

function vmoCloseEmailSetupNotice() {
    var notice = document.getElementById('vmo-email-setup-notice');
    if (notice) notice.style.display = 'none';
}

function vmoShowEmailSetupNotice(context) {
    var notice = document.getElementById('vmo-email-setup-notice');
    if (!notice) {
        notice = document.createElement('div');
        notice.id = 'vmo-email-setup-notice';
        notice.style.cssText = 'position:fixed;inset:0;z-index:999998;display:none;align-items:center;justify-content:center;background:rgba(2,6,23,.72);padding:20px;';
        notice.innerHTML = '<div style="width:min(520px,100%);background:#0f172a;color:#e5eefb;border:1px solid rgba(125,211,252,.24);border-radius:12px;box-shadow:0 24px 80px rgba(0,0,0,.45);padding:22px;font-family:inherit;">'
            + '<div style="display:flex;align-items:flex-start;gap:12px;margin-bottom:12px;">'
            + '<div style="width:36px;height:36px;border-radius:10px;background:rgba(14,165,233,.16);display:flex;align-items:center;justify-content:center;color:#7dd3fc;font-weight:800;">@</div>'
            + '<div style="flex:1;min-width:0;">'
            + '<h3 style="margin:0 0 8px;color:#fff;font-size:18px;line-height:1.25;">Email setup needed before sending</h3>'
            + '<p data-vmo-email-setup-message style="margin:0;color:#b6c6da;font-size:14px;line-height:1.55;"></p>'
            + '</div>'
            + '</div>'
            + '<div style="display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end;margin-top:18px;">'
            + '<button type="button" class="vmo-btn" data-vmo-email-setup-ask>Ask VMO AI</button>'
            + '<button type="button" class="vmo-btn vmo-btn-primary" data-vmo-email-setup-consult>Open Business Wizard</button>'
            + '<button type="button" class="vmo-btn" data-vmo-email-setup-close>Keep Drafting</button>'
            + '</div>'
            + '</div>';
        document.body.appendChild(notice);
        var closeBtn = notice.querySelector('[data-vmo-email-setup-close]');
        var consultBtn = notice.querySelector('[data-vmo-email-setup-consult]');
        var askBtn = notice.querySelector('[data-vmo-email-setup-ask]');
        if (closeBtn) closeBtn.addEventListener('click', vmoCloseEmailSetupNotice);
        if (consultBtn) consultBtn.addEventListener('click', function() {
            window.location.href = window.vmoConsultationUrl || 'admin.php?page=vmo-ai-builder-main';
        });
        if (askBtn) askBtn.addEventListener('click', function() {
            vmoCloseEmailSetupNotice();
            var prompt = document.getElementById('vmo-email-ai-prompt');
            if (prompt) prompt.value = 'Help me set up business email addresses for my VMO account.';
            if (typeof vmoOpenEmailAssistant === 'function') vmoOpenEmailAssistant();
        });
    }
    var messageEl = notice.querySelector('[data-vmo-email-setup-message]');
    var message = 'You can keep creating and saving AI email drafts, but sending is locked because this account does not currently have a provisioned or connected sending email address. Open the Business Wizard to complete the consultation and email setup, or ask VMO AI to help you set up business email addresses.';
    if (context === 'accounts') {
        message = 'No provisioned email address is connected to this account yet. AI drafts can still be created when your plan and credits are active, but sending will stay locked until VMO creates or connects a business email address.';
    }
    if (messageEl) messageEl.textContent = message;
    notice.style.display = 'flex';
}

function vmoFriendlyEmailAiError(err) {
    var raw = String((err && err.message) ? err.message : err || '').trim();
    var lower = raw.toLowerCase();
    if (lower.indexOf('active subscription') !== -1 || lower.indexOf('subscription required') !== -1) {
        return 'An active VMO plan is required before VMO can generate AI email drafts. Open My Plan to activate a plan, then try again.';
    }
    if (lower.indexOf('insufficient') !== -1 || lower.indexOf('credit') !== -1 || lower.indexOf('token') !== -1) {
        return 'Your VMO credits are not enough for this email generation. Please top up or upgrade your plan, then try again.';
    }
    if (lower.indexOf('invalid nonce') !== -1 || lower.indexOf('not logged in') !== -1 || lower.indexOf('forbidden') !== -1) {
        return 'Your VMO session expired. Refresh the dashboard and try generating the email again.';
    }
    if (lower.indexOf('rest routing') !== -1 || lower.indexOf('no route was found') !== -1 || lower === 'http 404') {
        return 'VMO could not reach the Email AI service. Refresh the dashboard; if it continues, update or reinstall the latest VMO plugin package.';
    }
    return raw || 'VMO could not generate the draft right now. Please try again.';
}

function vmoHandleEmailAiError(err, fallbackMessage) {
    console.error(fallbackMessage || 'Email AI error:', err);
    vmoToast(vmoFriendlyEmailAiError(err), 'error');
}

function vmoIsEmailAiRoutingError(err) {
    var raw = String((err && err.message) ? err.message : err || '').trim().toLowerCase();
    return raw.indexOf('rest routing') !== -1
        || raw.indexOf('no route was found') !== -1
        || raw.indexOf('rest_no_route') !== -1
        || raw === 'http 404'
        || raw.indexOf('fallback unavailable') !== -1;
}

function vmoEmailAiActionForPath(path) {
    var clean = String(path || '');
    if (clean.indexOf('/ai-compose') !== -1) return 'vmo_email_ai_compose';
    if (clean.indexOf('/ai-refine') !== -1) return 'vmo_email_ai_refine';
    if (clean.indexOf('/ai-variants') !== -1) return 'vmo_email_ai_variants';
    if (clean.indexOf('/ai-chat') !== -1) return 'vmo_email_ai_chat';
    return '';
}

function vmoEmailAiGetApiRoot() {
    return window.vmoRestRoot
        || (window.wpApiSettings && window.wpApiSettings.root)
        || <?php echo wp_json_encode( esc_url_raw( rest_url() ) ); ?>
        || (window.location.origin + '/wp-json/');
}

function vmoEmailAiGetWpNonce() {
    return (window.wpApiSettings && window.wpApiSettings.nonce)
        ? window.wpApiSettings.nonce
        : <?php echo wp_json_encode( wp_create_nonce( 'wp_rest' ) ); ?>;
}

function vmoEmailAiAjaxUrl() {
    return window.ajaxurl || <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
}

function vmoEmailAiBuildRestUrl(path, root) {
    var raw = String(path || '');
    if (/^https?:\/\//i.test(raw)) return raw;
    var clean = raw.replace(/^\/+/, '');
    var parts = clean.split('?');
    var route = parts.shift() || '';
    var query = parts.join('?');
    var base = String(root || vmoEmailAiGetApiRoot());
    if (base.indexOf('rest_route=') !== -1) {
        var prefix = base.endsWith('/') ? base : (base + (base.indexOf('rest_route=/') !== -1 ? '' : '/'));
        return prefix + route + (query ? '&' + query : '');
    }
    return base.replace(/\/?$/, '/') + route + (query ? '?' + query : '');
}

function vmoEmailAiRestRootsFor(path) {
    var raw = String(path || '');
    if (/^https?:\/\//i.test(raw) && raw.indexOf('/wp-json/') === -1) return [raw];
    var roots = [];
    [
        vmoEmailAiGetApiRoot(),
        window.location.origin + '/wp-json/',
        (window.wpApiSettings && window.wpApiSettings.altRoot) ? String(window.wpApiSettings.altRoot) : (window.location.origin + '/?rest_route=/')
    ].forEach(function(root) {
        if (root && roots.indexOf(root) === -1) roots.push(root);
    });
    return roots;
}

async function vmoEmailAiFetchJson(url, options) {
    var opts = options || {};
    var headers = Object.assign({}, (opts.headers || {}));
    var nonce = vmoEmailAiGetWpNonce();
    if (nonce && !headers['X-WP-Nonce']) headers['X-WP-Nonce'] = nonce;

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

    var text = await res.text();
    var data;
    try {
        data = text ? JSON.parse(text) : {};
    } catch (e) {
        if (!opts._vmoRetried && String(url).indexOf('/wp-json/') !== -1) {
            try {
                var parsedUrl = new URL(String(url), window.location.origin);
                var idx = parsedUrl.pathname.indexOf('/wp-json/');
                var route = idx >= 0 ? parsedUrl.pathname.slice(idx + '/wp-json'.length) : '';
                if (route) {
                    var alt = parsedUrl.origin + '/?rest_route=' + route + (parsedUrl.search ? '&' + parsedUrl.search.slice(1) : '');
                    return vmoEmailAiFetchJson(alt, Object.assign({}, opts, { _vmoRetried: true }));
                }
            } catch (_) {}
        }
        throw new Error('VMO could not reach the requested service. Please refresh or check REST routing.');
    }

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

    return data;
}

async function vmoEmailAiRestFetch(path, options) {
    var roots = vmoEmailAiRestRootsFor(path);
    var lastError = null;
    for (var i = 0; i < roots.length; i++) {
        try {
            var url = /^https?:\/\//i.test(String(path || '')) && String(path).indexOf('/wp-json/') === -1
                ? String(path)
                : vmoEmailAiBuildRestUrl(path, roots[i]);
            return await vmoEmailAiFetchJson(url, Object.assign({}, options || {}, { _vmoRoot: roots[i] }));
        } catch (err) {
            lastError = err;
            if (!vmoIsEmailAiRoutingError(err)) throw err;
        }
    }
    throw lastError || new Error('VMO could not reach the requested service. Please refresh or check REST routing.');
}

function vmoNormalizeEmailAiResponse(data, path, payload) {
    if (data && data.success === false) {
        var fail = (data.data && data.data.message) || data.message || 'Email AI request failed.';
        throw new Error(fail);
    }
    if (data && data.success === true && data.data && !data.subject && !data.reply && !data.variants) {
        data = data.data;
    }
    if (!data || typeof data !== 'object') {
        throw new Error('Email AI fallback unavailable.');
    }
    if (data.html_body || data.plain_body) {
        return {
            success: true,
            subject: data.subject || 'Draft Email',
            preheader: data.preview_text || data.preheader || '',
            plain_text: data.plain_body || data.plain_text || '',
            html: data.html_body || data.html || (data.plain_body ? String(data.plain_body).replace(/\n/g, '<br>') : ''),
            theme: (payload && payload.theme) || 'modern',
            template_type: (payload && payload.template_type) || 'newsletter',
            recommended_products: [],
            cta: data.cta || {},
            variants: []
        };
    }
    if (!data.success) data.success = true;
    return data;
}

async function vmoEmailAiLegacyCompose(payload, originalError) {
    var fd = new FormData();
    fd.append('action', 'vmo_generate_email_content');
    fd.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '') || vmoEmailAiGetWpNonce());
    fd.append('intent', (payload && (payload.intent || payload.message || payload.prompt)) || 'Generate a business email draft.');
    fd.append('format', 'html');
    try {
        var data = await vmoEmailAiFetchJson(vmoEmailAiAjaxUrl(), { method: 'POST', body: fd });
        return vmoNormalizeEmailAiResponse(data, 'legacy-compose', payload || {});
    } catch (err) {
        throw originalError || err;
    }
}

async function vmoEmailAiAjaxFetch(path, payload, originalError) {
    var action = vmoEmailAiActionForPath(path);
    if (!action) throw originalError || new Error('Email AI fallback unavailable.');

    var fd = new FormData();
    fd.append('action', action);
    fd.append('security', (typeof vmo_builder_nonce !== 'undefined' ? vmo_builder_nonce : '') || vmoEmailAiGetWpNonce());
    fd.append('payload', JSON.stringify(payload || {}));

    try {
        var data = await vmoEmailAiFetchJson(vmoEmailAiAjaxUrl(), { method: 'POST', body: fd });
        return vmoNormalizeEmailAiResponse(data, path, payload || {});
    } catch (err) {
        if (action === 'vmo_email_ai_compose' && vmoIsEmailAiRoutingError(err)) {
            return vmoEmailAiLegacyCompose(payload || {}, originalError || err);
        }
        throw err;
    }
}

async function vmoEmailAiFetch(path, payload) {
    try {
        var fetcher = (window.vmoApiFetch || (typeof vmoApiFetch === 'function' ? vmoApiFetch : vmoEmailAiRestFetch));
        return await fetcher(path, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload || {})
        });
    } catch (err) {
        if (!vmoIsEmailAiRoutingError(err)) {
            throw err;
        }
        return vmoEmailAiAjaxFetch(path, payload || {}, err);
    }
}
window.vmoEmailAiFetch = vmoEmailAiFetch;

window.vmoSetComposeBody = window.vmoSetComposeBody || function(html) {
    var body = document.getElementById('vmo-compose-body');
    var visual = document.getElementById('vmo-compose-visual-editor');
    if (body) body.value = html || '';
    if (visual) visual.innerHTML = html || '';
};

window.vmoGetComposeBody = window.vmoGetComposeBody || function() {
    var body = document.getElementById('vmo-compose-body');
    var visual = document.getElementById('vmo-compose-visual-editor');
    if (visual && visual.style.display !== 'none') {
        if (body) body.value = visual.innerHTML || '';
        return visual.innerHTML || '';
    }
    return body ? (body.value || '') : '';
};

window.vmoSetEditorMode = window.vmoSetEditorMode || function(mode) {
    var body = document.getElementById('vmo-compose-body');
    var visual = document.getElementById('vmo-compose-visual-editor');
    if (!body || !visual) return;
    if (mode === 'html') {
        body.value = visual.innerHTML || body.value || '';
        visual.style.display = 'none';
        body.style.display = 'block';
    } else {
        visual.innerHTML = body.value || visual.innerHTML || '';
        body.style.display = 'none';
        visual.style.display = 'block';
    }
};

window.vmoApplyEditorCommand = window.vmoApplyEditorCommand || function(command) {
    var visual = document.getElementById('vmo-compose-visual-editor');
    if (!visual) return;
    vmoSetEditorMode('visual');
    visual.focus();
    if (command === 'createLink') {
        var url = window.prompt ? window.prompt('Paste link URL') : '';
        if (!url) return;
        document.execCommand('createLink', false, url);
        return;
    }
    document.execCommand(command, false, null);
};

function vmoSelectTemplate(templateType) {
    var aliases = { 'event_invite': 'event_invitation', 'referral': 'referral_program', 'survey': 'survey_feedback' };
    templateType = aliases[templateType] || 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_invitation': '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_program': 'Create a referral program email explaining rewards, how to share, unique referral link placeholder, and social sharing buttons',
        'survey_feedback': 'Write a customer feedback survey email with an NPS scale visual, a brief survey link button, and a thank-you incentive',
        'christmas': 'Create a Christmas / holiday season promotional email with festive red & green styling, holiday wishes, gift ideas, and a holiday sale CTA',
        'halloween': 'Create a Halloween promotional email with spooky orange & purple styling, treats not tricks copy, and a limited-time scary-good deal CTA',
        'valentine': 'Create a Valentine\'s Day email with romantic pink & red styling, gift ideas for loved ones, and a Valentine sale CTA',
        'new_year': 'Create a New Year email with celebratory gold & navy styling, year-in-review highlights, and a fresh-start offer CTA',
        'thanksgiving': 'Create a Thanksgiving email with warm autumn orange & brown styling, a gratitude message to customers, and a thank-you offer CTA',
        'easter': 'Create an Easter / spring email with pastel styling, spring renewal copy, and a seasonal offer CTA',
        'mothers_day': 'Create a Mother\'s Day email with soft pink styling, gift ideas for moms, and a Mother\'s Day sale CTA',
        'fathers_day': 'Create a Father\'s Day email with bold navy styling, gift ideas for dads, and a Father\'s Day sale CTA',
        'birthday': 'Create a customer birthday email with confetti styling, a personal birthday wish, and an exclusive birthday gift CTA',
        'back_to_school': 'Create a back-to-school email with bright yellow & blue styling, helpful product picks, and a back-to-school savings CTA'
    };
    var intentField = document.getElementById('vmo-compose-intent');
    if (intentField && intents[templateType]) { intentField.value = intents[templateType]; }
    // Reset any prior overrides so the new template's own theme defaults apply.
    window.__vmoTemplateOverrides = null;
    window.__vmoCurrentTemplateType = templateType;
    var starter = vmoBuildEmailTemplateStarter(templateType);
    var subjectEl = document.getElementById('vmo-compose-subject');
    if (subjectEl && starter.subject) subjectEl.value = starter.subject;
    if (starter.html && typeof vmoSetComposeBody === 'function') {
        vmoSetComposeBody(starter.html);
    }
    vmoShowTemplateCustomizer(templateType, starter.theme);
    // Stay on the WRITE tab so the user sees the customizer.
    if (typeof vmoSwitchComposeTab === 'function') { vmoSwitchComposeTab('write'); }
    if (typeof vmoToast === 'function') { vmoToast('Template loaded. Edit the CTA link, colors, or copy below.', 'success'); }
}

// [VMO_TPL_CUSTOMIZER] Show + populate the customizer panel using the theme
// resolved by vmoBuildEmailTemplateStarter so the user starts from the
// template's actual defaults instead of a generic blue.
window.vmoShowTemplateCustomizer = function(templateType, theme) {
    var panel = document.getElementById('vmo-template-customizer');
    if (!panel) return;
    if (!templateType || templateType === 'freeform') { panel.style.display = 'none'; return; }
    panel.style.display = 'block';
    var nameEl = document.getElementById('vmo-template-customizer-name');
    if (nameEl) nameEl.textContent = templateType.replace(/_/g, ' ');
    var t = theme || {};
    var setVal = function(id, v) { var el = document.getElementById(id); if (el && v != null) el.value = v; };
    setVal('vmo-tpl-cta-text', t.ctaText || '');
    setVal('vmo-tpl-cta-url', t.ctaUrl || '');
    setVal('vmo-tpl-header-bg', t.headerBg || '#0f172a');
    setVal('vmo-tpl-header-color', t.headerColor || '#ffffff');
    setVal('vmo-tpl-cta-bg', t.ctaBg || '#0ea5e9');
    setVal('vmo-tpl-cta-color', t.ctaColor || '#ffffff');
    setVal('vmo-tpl-accent', t.accent || '#7dd3fc');
};

window.vmoApplyTemplateCustomizations = function() {
    var t = window.__vmoCurrentTemplateType;
    if (!t) return;
    window.__vmoTemplateOverrides = {
        ctaText:     (document.getElementById('vmo-tpl-cta-text')     || {}).value || '',
        ctaUrl:      (document.getElementById('vmo-tpl-cta-url')      || {}).value || '',
        headerBg:    (document.getElementById('vmo-tpl-header-bg')    || {}).value || '',
        headerColor: (document.getElementById('vmo-tpl-header-color') || {}).value || '',
        ctaBg:       (document.getElementById('vmo-tpl-cta-bg')       || {}).value || '',
        ctaColor:    (document.getElementById('vmo-tpl-cta-color')    || {}).value || '',
        accent:      (document.getElementById('vmo-tpl-accent')       || {}).value || ''
    };
    var starter = vmoBuildEmailTemplateStarter(t);
    if (starter.html && typeof vmoSetComposeBody === 'function') { vmoSetComposeBody(starter.html); }
    if (typeof vmoToast === 'function') { vmoToast('Template updated with your customizations.', 'success'); }
};

window.vmoResetTemplateCustomizations = function() {
    var t = window.__vmoCurrentTemplateType;
    if (!t) return;
    window.__vmoTemplateOverrides = null;
    var starter = vmoBuildEmailTemplateStarter(t);
    if (starter.html && typeof vmoSetComposeBody === 'function') { vmoSetComposeBody(starter.html); }
    vmoShowTemplateCustomizer(t, starter.theme);
    if (typeof vmoToast === 'function') { vmoToast('Reset to template defaults.', 'success'); }
};

function vmoTemplateEsc(value) {
    var div = document.createElement('div');
    div.textContent = String(value || '');
    return div.innerHTML;
}

function vmoBuildEmailTemplateStarter(templateType) {
    var siteName = (window.vmoBusinessName || document.title || 'Your Business').replace(/\s+[-|].*$/, '').trim() || 'Your Business';
    var origin = window.location && window.location.origin ? window.location.origin : '';
    var defaultCtaUrl = origin ? origin + '/contact' : '#';
    // Theme defaults: each template gets its own visual identity. Seasonal
    // templates (christmas, halloween, valentine, …) ship with a distinct
    // palette + decorative motif so the gallery is not "all the same".
    // Every value here can be overridden by the customizer panel via
    // window.__vmoTemplateOverrides.
    var themes = {
        product_launch: { headerBg:'#0f172a', headerColor:'#ffffff', accent:'#7dd3fc', ctaBg:'#0ea5e9', ctaColor:'#ffffff', motif:'🚀', pageBg:'#f4f7fb' },
        flash_sale:     { headerBg:'#7f1d1d', headerColor:'#ffffff', accent:'#fde68a', ctaBg:'#dc2626', ctaColor:'#ffffff', motif:'⚡', pageBg:'#fff5f5' },
        newsletter:     { headerBg:'#1e293b', headerColor:'#ffffff', accent:'#93c5fd', ctaBg:'#2563eb', ctaColor:'#ffffff', motif:'📰', pageBg:'#f8fafc' },
        abandoned_cart: { headerBg:'#0f172a', headerColor:'#ffffff', accent:'#fca5a5', ctaBg:'#ef4444', ctaColor:'#ffffff', motif:'🛒', pageBg:'#fafafa' },
        welcome_series: { headerBg:'#065f46', headerColor:'#ffffff', accent:'#a7f3d0', ctaBg:'#10b981', ctaColor:'#ffffff', motif:'👋', pageBg:'#f0fdf4' },
        event_invitation:{headerBg:'#312e81', headerColor:'#ffffff', accent:'#c4b5fd', ctaBg:'#6366f1', ctaColor:'#ffffff', motif:'🎟️', pageBg:'#f5f3ff' },
        review_request: { headerBg:'#78350f', headerColor:'#ffffff', accent:'#fcd34d', ctaBg:'#f59e0b', ctaColor:'#1f2937', motif:'⭐', pageBg:'#fffbeb' },
        referral_program:{headerBg:'#0e7490', headerColor:'#ffffff', accent:'#67e8f9', ctaBg:'#06b6d4', ctaColor:'#ffffff', motif:'🤝', pageBg:'#ecfeff' },
        survey_feedback:{ headerBg:'#3f3f46', headerColor:'#ffffff', accent:'#d4d4d8', ctaBg:'#52525b', ctaColor:'#ffffff', motif:'📊', pageBg:'#fafafa' },
        // Seasonal / holiday
        christmas:      { headerBg:'#7f1d1d', headerColor:'#ffffff', accent:'#fde68a', ctaBg:'#15803d', ctaColor:'#ffffff', motif:'🎄', pageBg:'#fef2f2', decor:'❄️ ❄️ ❄️' },
        halloween:      { headerBg:'#1c1917', headerColor:'#fb923c', accent:'#f97316', ctaBg:'#7c2d12', ctaColor:'#fed7aa', motif:'🎃', pageBg:'#0a0a0a', bodyBg:'#1c1917', bodyColor:'#fde68a', decor:'🦇 🕸️ 🕷️' },
        valentine:      { headerBg:'#9d174d', headerColor:'#ffffff', accent:'#fbcfe8', ctaBg:'#e11d48', ctaColor:'#ffffff', motif:'💝', pageBg:'#fdf2f8', decor:'💕 💖 💕' },
        new_year:       { headerBg:'#0c0a09', headerColor:'#fde68a', accent:'#fbbf24', ctaBg:'#ca8a04', ctaColor:'#0c0a09', motif:'🎆', pageBg:'#fffbeb', decor:'✨ 🥂 ✨' },
        thanksgiving:   { headerBg:'#7c2d12', headerColor:'#ffffff', accent:'#fed7aa', ctaBg:'#c2410c', ctaColor:'#ffffff', motif:'🦃', pageBg:'#fff7ed', decor:'🍂 🌾 🍁' },
        easter:         { headerBg:'#86198f', headerColor:'#ffffff', accent:'#f0abfc', ctaBg:'#a21caf', ctaColor:'#ffffff', motif:'🐰', pageBg:'#fdf4ff', decor:'🌷 🥚 🌸' },
        mothers_day:    { headerBg:'#be185d', headerColor:'#ffffff', accent:'#fbcfe8', ctaBg:'#db2777', ctaColor:'#ffffff', motif:'💐', pageBg:'#fdf2f8', decor:'🌹 💐 🌹' },
        fathers_day:    { headerBg:'#1e3a8a', headerColor:'#ffffff', accent:'#bfdbfe', ctaBg:'#1d4ed8', ctaColor:'#ffffff', motif:'👔', pageBg:'#eff6ff', decor:'⚒️ 🍻 ⚒️' },
        birthday:       { headerBg:'#581c87', headerColor:'#ffffff', accent:'#f0abfc', ctaBg:'#9333ea', ctaColor:'#ffffff', motif:'🎂', pageBg:'#faf5ff', decor:'🎉 🎈 🎁' },
        back_to_school: { headerBg:'#1e40af', headerColor:'#ffffff', accent:'#fde047', ctaBg:'#eab308', ctaColor:'#1e3a8a', motif:'🎒', pageBg:'#fefce8', decor:'✏️ 📚 🍎' }
    };
    var templates = {
        product_launch: {
            subject: 'Introducing something new from ' + siteName,
            eyebrow: 'New launch',
            headline: 'Meet the new offer built for your next step',
            body: 'A fresh product or service is now available. Use this space to explain what changed, who it helps, and why now is the right time to take action.',
            sections: ['What is new', 'Who it is for', 'Why it matters'],
            cta: 'Explore the launch'
        },
        flash_sale: {
            subject: '⚡ Limited-time offer from ' + siteName,
            eyebrow: 'Flash sale — ends soon',
            headline: 'A short window to save on what you need',
            body: 'Use this email to explain the offer, the deadline, and the simplest path to checkout. Keep the promise clear and the action direct.',
            sections: ['Offer details', 'Best-fit customers', 'Deadline'],
            cta: 'Shop the offer'
        },
        newsletter: {
            subject: siteName + ' update',
            eyebrow: 'Business update',
            headline: 'Here is what is new this month',
            body: 'Share the most useful update first, then add two or three short sections with practical news, customer wins, or upcoming events.',
            sections: ['Top story', 'Customer highlight', 'Coming next'],
            cta: 'Read more'
        },
        abandoned_cart: {
            subject: 'Still interested? Your next step is waiting',
            eyebrow: 'Cart reminder',
            headline: 'Your selected item is still available',
            body: 'Remind the customer what they were considering, answer a likely objection, and make it easy to return to checkout.',
            sections: ['What you picked', 'Why customers choose it', 'Return to checkout'],
            cta: 'Return to checkout'
        },
        welcome_series: {
            subject: 'Welcome to ' + siteName,
            eyebrow: 'Welcome',
            headline: 'We are glad you are here',
            body: 'Introduce the business, set expectations, and give the reader one useful first action. Keep it warm and simple.',
            sections: ['What to expect', 'How we help', 'Start here'],
            cta: 'Get started'
        },
        event_invitation: {
            subject: 'You are invited',
            eyebrow: 'Event invitation',
            headline: 'Join us for an upcoming event',
            body: 'Add the date, time, location, agenda, and who should attend. Make the RSVP action clear.',
            sections: ['Date and time', 'Location', 'Agenda'],
            cta: 'RSVP now'
        },
        review_request: {
            subject: 'How did we do?',
            eyebrow: 'Review request',
            headline: 'Your feedback helps us improve',
            body: 'Thank the customer, ask for a quick review, and make the review action easy to complete.',
            sections: ['Rate your experience', 'Share one detail', 'Thank you'],
            cta: 'Leave a review'
        },
        referral_program: {
            subject: 'Share ' + siteName + ' with someone who needs it',
            eyebrow: 'Referral program',
            headline: 'Help someone take the next step',
            body: 'Explain who should be referred, what they receive, and what the sender gets in return if rewards apply.',
            sections: ['Who to refer', 'How it works', 'Reward details'],
            cta: 'Share your link'
        },
        survey_feedback: {
            subject: 'Quick question for you',
            eyebrow: 'Feedback survey',
            headline: 'Tell us what would make this better',
            body: 'Ask for focused feedback and explain how it will be used. Keep the survey promise short.',
            sections: ['One-minute survey', 'What we are improving', 'Thank-you incentive'],
            cta: 'Share feedback'
        },
        // Seasonal templates
        christmas: {
            subject: '🎄 Merry Christmas from ' + siteName,
            eyebrow: 'Holiday season',
            headline: 'Wishing you a warm and joyful Christmas',
            body: 'Share a heartfelt holiday greeting, a curated list of gift ideas, and a special holiday-only offer. Keep the tone festive and grateful.',
            sections: ['Holiday greeting', 'Gift ideas', 'Holiday offer'],
            cta: 'Shop holiday gifts'
        },
        halloween: {
            subject: '🎃 Treats (no tricks) from ' + siteName,
            eyebrow: 'Halloween special',
            headline: 'Something spooky-good is waiting',
            body: 'Lean into the Halloween mood — costumes, candy, spooky savings. Pair the playful copy with one clear, scary-good offer.',
            sections: ['Trick or treat?', 'Spooky picks', 'Limited until midnight'],
            cta: 'Claim your treat'
        },
        valentine: {
            subject: '💝 Made with love by ' + siteName,
            eyebrow: 'Valentine\'s Day',
            headline: 'Show someone they matter this Valentine\'s',
            body: 'Suggest thoughtful gift ideas for partners, friends, or self-love. Keep the copy warm and the offer simple.',
            sections: ['For your love', 'Last-minute picks', 'Valentine offer'],
            cta: 'Find the perfect gift'
        },
        new_year: {
            subject: '🥂 Cheers to a new year from ' + siteName,
            eyebrow: 'New Year',
            headline: 'A fresh start, a fresh offer',
            body: 'Recap a highlight of the past year, set the tone for what is coming, and open the year with one focused offer.',
            sections: ['Year highlights', 'What is next', 'New Year offer'],
            cta: 'Start the year right'
        },
        thanksgiving: {
            subject: '🍂 We are thankful for you',
            eyebrow: 'Thanksgiving',
            headline: 'A simple thank-you from ' + siteName,
            body: 'Express genuine gratitude to the customer, recap how their support helped, and add a small thank-you offer.',
            sections: ['Our gratitude', 'A look back', 'Thank-you offer'],
            cta: 'Accept our thanks'
        },
        easter: {
            subject: '🐰 Spring into ' + siteName,
            eyebrow: 'Easter / Spring',
            headline: 'Fresh starts, fresh picks for spring',
            body: 'Lean into renewal — new arrivals, lighter colors, family-friendly Easter highlights. Keep the offer cheerful.',
            sections: ['New arrivals', 'Family picks', 'Easter offer'],
            cta: 'Hop into spring'
        },
        mothers_day: {
            subject: '💐 Make Mom\'s day with ' + siteName,
            eyebrow: 'Mother\'s Day',
            headline: 'Show Mom she\'s appreciated',
            body: 'Curate gift ideas for moms of all kinds. Pair the warm tone with one practical Mother\'s Day offer.',
            sections: ['Gifts she\'ll love', 'Last-minute ideas', 'Mom\'s Day offer'],
            cta: 'Shop for Mom'
        },
        fathers_day: {
            subject: '👔 Father\'s Day picks from ' + siteName,
            eyebrow: 'Father\'s Day',
            headline: 'Get Dad something he\'ll actually use',
            body: 'Practical, thoughtful gifts for dads. Lead with the bestsellers and back it up with a fair Father\'s Day offer.',
            sections: ['Top picks', 'For the hobby dad', 'Father\'s Day offer'],
            cta: 'Shop for Dad'
        },
        birthday: {
            subject: '🎂 Happy Birthday from ' + siteName,
            eyebrow: 'Your birthday',
            headline: 'It\'s your day — here\'s a gift on us',
            body: 'Wish the customer a happy birthday and give them a no-strings reward. Make the redemption painless.',
            sections: ['Your reward', 'How to use it', 'Have a great day'],
            cta: 'Claim your birthday gift'
        },
        back_to_school: {
            subject: '🎒 Back-to-school savings at ' + siteName,
            eyebrow: 'Back to school',
            headline: 'Stock up before the bell rings',
            body: 'Lead with the must-have list, group items by grade or need, and seal it with a back-to-school offer.',
            sections: ['Must-haves', 'By grade', 'Back-to-school offer'],
            cta: 'Shop back-to-school'
        }
    };
    var data = templates[templateType] || templates.newsletter;
    var theme = themes[templateType] || themes.newsletter;
    // Apply user customizations on top of template defaults.
    var ov = window.__vmoTemplateOverrides || {};
    var headerBg    = ov.headerBg    || theme.headerBg;
    var headerColor = ov.headerColor || theme.headerColor;
    var accent      = ov.accent      || theme.accent;
    var ctaBg       = ov.ctaBg       || theme.ctaBg;
    var ctaColor    = ov.ctaColor    || theme.ctaColor;
    var ctaText     = ov.ctaText     || data.cta;
    var ctaUrl      = ov.ctaUrl      || defaultCtaUrl;
    var pageBg      = theme.pageBg   || '#f4f7fb';
    var bodyBg      = theme.bodyBg   || '#ffffff';
    var bodyColor   = theme.bodyColor|| '#111827';
    var motif       = theme.motif    || '';
    var decor       = theme.decor    || '';

    var sectionBg = bodyBg === '#ffffff' ? '#ffffff' : 'rgba(255,255,255,0.06)';
    var sectionColor = bodyColor;
    var sections = data.sections.map(function(section) {
        return '<td style="padding:14px;border:1px solid #e5e7eb;background:' + vmoTemplateEsc(sectionBg) + ';font-family:Arial,sans-serif;color:' + vmoTemplateEsc(sectionColor) + ';"><strong style="display:block;margin-bottom:6px;color:' + vmoTemplateEsc(sectionColor) + ';">' + vmoTemplateEsc(section) + '</strong><span style="color:#64748b;font-size:13px;line-height:1.5;">Add the details VMO should include here.</span></td>';
    }).join('');
    var motifLine = motif ? ('<div style="font-size:36px;line-height:1;margin-bottom:10px;">' + vmoTemplateEsc(motif) + '</div>') : '';
    var decorLine = decor ? ('<div style="text-align:center;font-size:18px;letter-spacing:6px;margin:8px 0 18px;color:' + vmoTemplateEsc(accent) + ';">' + vmoTemplateEsc(decor) + '</div>') : '';

    var html = '<table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:' + vmoTemplateEsc(pageBg) + ';padding:28px 12px;margin:0;">'
        + '<tr><td align="center"><table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="max-width:640px;background:' + vmoTemplateEsc(bodyBg) + ';border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;">'
        + '<tr><td style="padding:32px 34px 26px;background:' + vmoTemplateEsc(headerBg) + ';font-family:Arial,sans-serif;color:' + vmoTemplateEsc(headerColor) + ';">'
        + motifLine
        + '<p style="margin:0 0 10px;font-size:12px;text-transform:uppercase;font-weight:700;color:' + vmoTemplateEsc(accent) + ';">' + vmoTemplateEsc(data.eyebrow) + '</p>'
        + '<h1 style="margin:0;font-size:32px;line-height:1.15;color:' + vmoTemplateEsc(headerColor) + ';">' + vmoTemplateEsc(data.headline) + '</h1>'
        + '</td></tr><tr><td style="padding:28px 34px;font-family:Arial,sans-serif;color:' + vmoTemplateEsc(bodyColor) + ';background:' + vmoTemplateEsc(bodyBg) + ';">'
        + decorLine
        + '<p style="margin:0 0 22px;font-size:16px;line-height:1.7;color:' + vmoTemplateEsc(bodyColor === '#111827' ? '#334155' : bodyColor) + ';">' + vmoTemplateEsc(data.body) + '</p>'
        + '<table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="margin:0 0 24px;"><tr>' + sections + '</tr></table>'
        + '<a href="' + vmoTemplateEsc(ctaUrl) + '" style="background:' + vmoTemplateEsc(ctaBg) + ';color:' + vmoTemplateEsc(ctaColor) + ';padding:14px 24px;border-radius:8px;text-decoration:none;font-weight:800;display:inline-block;">' + vmoTemplateEsc(ctaText) + '</a>'
        + '</td></tr><tr><td style="padding:20px 34px;background:#f8fafc;font-family:Arial,sans-serif;color:#64748b;font-size:12px;line-height:1.5;">' + vmoTemplateEsc(siteName) + '</td></tr>'
        + '</table></td></tr></table>';
    return {
        subject: data.subject,
        html: html,
        theme: {
            ctaText: ctaText,
            ctaUrl: ctaUrl,
            headerBg: headerBg,
            headerColor: headerColor,
            ctaBg: ctaBg,
            ctaColor: ctaColor,
            accent: accent
        }
    };
}
function vmoPreviewDevice(device, btn) {
    var frame = document.getElementById('vmo-email-preview-frame');
    if (!frame) return;
    var html = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : (document.getElementById('vmo-compose-body') || {}).value || '';
    frame.style.maxWidth = (device === 'mobile') ? '375px' : '100%';
    frame.style.background = '#fff';
    frame.style.color = '#111';
    if (device === 'plain') {
        frame.innerHTML = '<pre style="white-space:pre-wrap;word-wrap:break-word;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:13px;line-height:1.5;">' + vmoEscapeHtml((html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()) + '</pre>';
    } else if (device === 'inbox') {
        var from = (document.getElementById('vmo-compose-from') || {}).value || 'Your business';
        var subject = (document.getElementById('vmo-compose-subject') || {}).value || '(No subject)';
        var snippet = (html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140);
        frame.innerHTML = '<div style="border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;font-family:Arial,sans-serif;"><div style="display:grid;grid-template-columns:160px 1fr;gap:12px;padding:14px 16px;border-bottom:1px solid #eef2f7;"><strong>' + vmoEscapeHtml(from) + '</strong><div><div style="font-weight:700;">' + vmoEscapeHtml(subject) + '</div><div style="color:#64748b;margin-top:4px;">' + vmoEscapeHtml(snippet) + '</div></div></div></div>';
    } else {
        frame.innerHTML = html || '<p style="color:#777;text-align:center;margin-top:50px;">No content to preview.</p>';
    }
    if (btn && btn.parentElement) {
        var btns = btn.parentElement.querySelectorAll('.vmo-btn-small');
        btns.forEach(function(b) { b.classList.remove('active'); });
        btn.classList.add('active');
    }
}
function vmoBuildComposeDraftPayload(extra) {
    var body = document.getElementById('vmo-compose-body');
    var subject = document.getElementById('vmo-compose-subject');
    var currentAccount = (typeof vmoGetCurrentMailboxSelectionForEmailTools === 'function') ? vmoGetCurrentMailboxSelectionForEmailTools() : { account: '', mailbox_id: '' };
    var fromEmail = (document.getElementById('vmo-compose-from') || {}).value || currentAccount.account || '';
    var payload = {
        subject: subject ? (subject.value || 'Untitled draft') : 'Untitled draft',
        message: (typeof vmoGetComposeBody === 'function' ? vmoGetComposeBody() : (body ? body.value : '')),
        to: (document.getElementById('vmo-compose-to') || {}).value || '',
        cc: (document.getElementById('vmo-compose-cc') || {}).value || '',
        bcc: (document.getElementById('vmo-compose-bcc') || {}).value || '',
        from_email: fromEmail,
        account: fromEmail,
        mailbox_id: currentAccount.mailbox_id || '',
        type: 'transactional'
    };
    if (extra && typeof extra === 'object') {
        Object.keys(extra).forEach(function(key) { payload[key] = extra[key]; });
    }
    return payload;
}

function vmoStoreEmailDraftLocally(draftPayload) {
    var drafts = JSON.parse(localStorage.getItem('vmo_email_drafts') || '[]');
    drafts.unshift({
        subject: draftPayload.subject || 'Untitled draft',
        body: draftPayload.message || '',
        timestamp: new Date().toISOString(),
        fallback: true,
        is_ai_generated: !!draftPayload.is_ai_generated
    });
    if (drafts.length > 20) drafts = drafts.slice(0, 20);
    localStorage.setItem('vmo_email_drafts', JSON.stringify(drafts));
    return { success: true, fallback: true };
}

function vmoEmailAjaxSecurityNonce() {
    try {
        if (typeof vmo_builder_nonce !== 'undefined' && vmo_builder_nonce) return vmo_builder_nonce;
        if (window.vmo_ajax && (window.vmo_ajax.security || window.vmo_ajax.nonce)) return window.vmo_ajax.security || window.vmo_ajax.nonce;
        if (window.vmoAjax && (window.vmoAjax.security || window.vmoAjax.nonce)) return window.vmoAjax.security || window.vmoAjax.nonce;
    } catch (_) {}
    return (typeof vmoEmailAiGetWpNonce === 'function') ? vmoEmailAiGetWpNonce() : '';
}

function vmoEmailAdminAjax(action, payload) {
    var body = new FormData();
    var wpNonce = (typeof vmoEmailAiGetWpNonce === 'function') ? vmoEmailAiGetWpNonce() : '';
    body.append('action', action);
    body.append('security', vmoEmailAjaxSecurityNonce());
    body.append('payload', JSON.stringify(payload || {}));
    if (payload && payload.id) body.append('id', payload.id);
    if (payload && payload.per_page) body.append('per_page', payload.per_page);
    if (payload && payload.offset) body.append('offset', payload.offset);
    if (payload && payload.account) body.append('account', payload.account);
    if (payload && payload.mailbox_id) body.append('mailbox_id', payload.mailbox_id);

    return fetch(vmoEmailAiAjaxUrl(), {
        method: 'POST',
        credentials: 'same-origin',
        headers: wpNonce ? { 'X-WP-Nonce': wpNonce } : {},
        body: body
    }).then(function(res) {
        return res.text().then(function(text) {
            var data;
            try {
                data = text ? JSON.parse(text) : {};
            } catch (_) {
                throw new Error('VMO email service returned a non-JSON response. Refresh the dashboard and try again.');
            }
            if (!res.ok || (data && data.success === false)) {
                throw new Error((data && (data.message || (data.data && data.data.message))) || ('HTTP ' + res.status));
            }
            return data;
        });
    });
}

function vmoEmailShouldUseAjaxFallback(err) {
    return typeof vmoIsEmailAiRoutingError === 'function' && vmoIsEmailAiRoutingError(err);
}

window.vmoEmailAttachmentConfig = window.vmoEmailAttachmentConfig || <?php
    $vmo_email_upload_max = function_exists('wp_max_upload_size') ? intval(wp_max_upload_size()) : 0;
    echo wp_json_encode(array(
        'maxUploadBytes' => $vmo_email_upload_max > 0 ? $vmo_email_upload_max : 0,
        'inlineAttachmentBytes' => defined('MB_IN_BYTES') ? 20 * MB_IN_BYTES : 20 * 1024 * 1024,
    ));
?>;
window.vmoComposeAttachments = window.vmoComposeAttachments || [];

function vmoFormatComposeAttachmentBytes(bytes) {
    bytes = Math.max(0, Number(bytes || 0));
    if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(1).replace(/\.0$/, '') + ' GB';
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(1).replace(/\.0$/, '') + ' MB';
    if (bytes >= 1024) return (bytes / 1024).toFixed(1).replace(/\.0$/, '') + ' KB';
    return bytes + ' B';
}

function vmoComposeAttachmentTotal(files) {
    return (Array.isArray(files) ? files : []).reduce(function(total, file) {
        return total + (file && file.size ? Number(file.size) : 0);
    }, 0);
}

function vmoRefreshComposeAttachmentUi() {
    var files = Array.isArray(window.vmoComposeAttachments) ? window.vmoComposeAttachments : [];
    var countEl = document.getElementById('vmo-attachment-count');
    if (!countEl) return;
    if (!files.length) {
        countEl.textContent = '';
        countEl.title = '';
        return;
    }
    var names = files.map(function(file) { return file && file.name ? file.name : 'attachment'; });
    var total = vmoComposeAttachmentTotal(files);
    countEl.textContent = (files.length === 1 ? '1 file' : (files.length + ' files')) + ' attached' + (total ? ' · ' + vmoFormatComposeAttachmentBytes(total) : '');
    countEl.title = names.join(', ');
}

function vmoAddComposeAttachmentFiles(fileList) {
    var incoming = Array.prototype.slice.call(fileList || []).filter(Boolean);
    if (!incoming.length) return;
    var current = Array.isArray(window.vmoComposeAttachments) ? window.vmoComposeAttachments : [];
    var seen = {};
    current.forEach(function(file) {
        if (!file) return;
        seen[[file.name, file.size, file.lastModified].join(':')] = true;
    });
    var maxUploadBytes = Number((window.vmoEmailAttachmentConfig && window.vmoEmailAttachmentConfig.maxUploadBytes) || 0);
    incoming.forEach(function(file) {
        var key = [file.name, file.size, file.lastModified].join(':');
        if (!seen[key]) {
            if (maxUploadBytes > 0 && (vmoComposeAttachmentTotal(current) + Number(file.size || 0)) > maxUploadBytes) {
                var message = 'Selected attachments are larger than this server can upload in one email request. Current limit: ' + vmoFormatComposeAttachmentBytes(maxUploadBytes) + '.';
                if (typeof vmoToast === 'function') vmoToast(message, 'error');
                else alert(message);
                return;
            }
            current.push(file);
            seen[key] = true;
        }
    });
    window.vmoComposeAttachments = current;
    vmoRefreshComposeAttachmentUi();
}

function vmoClearComposeAttachments() {
    window.vmoComposeAttachments = [];
    ['vmo-compose-attachment', 'vmo-compose-attachment-toolbar'].forEach(function(id) {
        var input = document.getElementById(id);
        if (input) input.value = '';
    });
    vmoRefreshComposeAttachmentUi();
}

function vmoBindComposeAttachmentInputs() {
    ['vmo-compose-attachment', 'vmo-compose-attachment-toolbar'].forEach(function(id) {
        var input = document.getElementById(id);
        if (!input || input.__vmoBoundAttachment) return;
        input.__vmoBoundAttachment = true;
        input.addEventListener('change', function() {
            vmoAddComposeAttachmentFiles(input.files || []);
            input.value = '';
        });
    });
}

window.vmoGetComposeAttachments = function() {
    return Array.isArray(window.vmoComposeAttachments) ? window.vmoComposeAttachments.slice() : [];
};
window.vmoClearComposeAttachments = vmoClearComposeAttachments;
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', vmoBindComposeAttachmentInputs);
} else {
    vmoBindComposeAttachmentInputs();
}

function vmoGetCurrentMailboxSelectionForEmailTools() {
    var sidebar = document.querySelector('.vmo-account-selector');
    var compose = document.getElementById('vmo-compose-from');
    var readSelection = function(selected) {
        var account = '';
        var mailboxId = '';
        try {
            account = selected ? String(selected.value || '').trim() : '';
            if (selected && selected.selectedOptions && selected.selectedOptions[0]) {
                mailboxId = selected.selectedOptions[0].getAttribute('data-mailbox-id') || '';
            }
        } catch (_) {}
        return { account: account, mailbox_id: mailboxId };
    };

    var composeSelection = readSelection(compose);
    if (composeSelection.account) return composeSelection;

    var sidebarSelection = readSelection(sidebar);
    if (sidebar && sidebar.dataset && sidebar.dataset.vmoProvisioned === '0') return composeSelection;
    return sidebarSelection.account ? sidebarSelection : composeSelection;
}
window.vmoGetCurrentMailboxSelectionForEmailTools = window.vmoGetCurrentMailboxSelectionForEmailTools || vmoGetCurrentMailboxSelectionForEmailTools;

function vmoUpdateDraftBadges(count) {
    var safeCount = Math.max(0, parseInt(count, 10) || 0);
    document.querySelectorAll('[data-vmo-drafts-count], .vmo-drafts-count, #vmo-drafts-count').forEach(function(el) {
        el.textContent = String(safeCount);
    });
}
window.vmoUpdateDraftBadges = window.vmoUpdateDraftBadges || vmoUpdateDraftBadges;

function vmoSyncMailboxSelectorWithComposeFrom() {
    try {
        var compose = document.getElementById('vmo-compose-from');
        var sidebar = document.querySelector('.vmo-account-selector');
        var composeAccount = compose ? String(compose.value || '').trim() : '';
        if (!composeAccount || !sidebar || !sidebar.options || !sidebar.options.length) return;
        var found = Array.prototype.some.call(sidebar.options, function(option) { return option.value === composeAccount; });
        if (!found || sidebar.value === composeAccount) return;
        sidebar.value = composeAccount;
        try { localStorage.setItem('vmo_selected_mailbox_account', composeAccount); } catch (_) {}
    } catch (_) {}
}

function vmoRefreshDraftViewsAfterMutation(syncComposeAccount) {
    if (syncComposeAccount) vmoSyncMailboxSelectorWithComposeFrom();
    try { if (typeof window.vmoLoadEmailDrafts === 'function') window.vmoLoadEmailDrafts(); } catch (_) {}
    try { if (typeof window.vmoRefreshDraftCounts === 'function') window.vmoRefreshDraftCounts(); } catch (_) {}
    try { if (typeof window.vmoRefreshMailCounts === 'function') window.vmoRefreshMailCounts(); } catch (_) {}
    try { if (typeof window.vmoRefreshMail === 'function') window.vmoRefreshMail(); } catch (_) {}
}

function vmoResetComposeForm() {
    ['vmo-compose-to','vmo-compose-cc','vmo-compose-bcc','vmo-compose-subject','vmo-compose-schedule'].forEach(function(id){
        var el = document.getElementById(id);
        if (el) el.value = '';
    });
    var body = document.getElementById('vmo-compose-body');
    var visual = document.getElementById('vmo-compose-visual-editor');
    if (body) body.value = '';
    if (visual) visual.innerHTML = '';
    var attCount = document.getElementById('vmo-attachment-count');
    if (attCount) attCount.textContent = '';
    vmoClearComposeAttachments();
}
window.vmoResetComposeForm = window.vmoResetComposeForm || vmoResetComposeForm;

function vmoSaveEmailDraftPayload(draftPayload, messages) {
    var opts = messages || {};
    var payload = Object.assign({ subject: 'Untitled draft', message: '', type: 'transactional' }, draftPayload || {});
    var fetcher = (typeof window.vmoApiFetch === 'function')
        ? window.vmoApiFetch
        : (typeof vmoApiFetch === 'function' ? vmoApiFetch : null);
    if (!fetcher) {
        return vmoEmailAdminAjax('vmo_save_email_draft', payload).then(function(data) {
            if (data && data.success) {
                if (!opts.silent && typeof vmoToast === 'function') { vmoToast(opts.success || 'Draft saved to VMO.', 'success'); }
                return data;
            }
            throw new Error((data && data.message) || 'Draft save failed');
        }).catch(function(err) {
            var local = vmoStoreEmailDraftLocally(payload);
            if (!opts.silent && typeof vmoToast === 'function') {
                vmoToast('VMO is still loading. The draft was kept on this device — please retry in a moment.', 'error');
            }
            return local;
        });
    }

    return fetcher('vmo-manager/v1/emails/drafts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    }).then(function(data) {
        if (data && data.success) {
            if (!opts.silent && typeof vmoToast === 'function') { vmoToast(opts.success || 'Draft saved to VMO.', 'success'); }
            return data;
        }
        throw new Error((data && data.message) || 'Draft save failed');
    }).catch(function(err) {
        if (vmoEmailShouldUseAjaxFallback(err)) {
            return vmoEmailAdminAjax('vmo_save_email_draft', payload).then(function(data) {
                if (data && data.success) {
                    if (!opts.silent && typeof vmoToast === 'function') { vmoToast(opts.success || 'Draft saved to VMO.', 'success'); }
                    return data;
                }
                throw new Error((data && data.message) || 'Draft save failed');
            }).catch(function(ajaxErr) {
                console.error('VMO draft AJAX fallback failed:', ajaxErr);
                vmoStoreEmailDraftLocally(payload);
                if (!opts.silent && typeof vmoToast === 'function') {
                    var ajaxMsg = (ajaxErr && ajaxErr.message) ? ajaxErr.message : 'Unknown error';
                    vmoToast('Could not save draft to VMO (' + ajaxMsg + '). A local backup was kept; please retry to store it in VMO.', 'error');
                }
                throw ajaxErr;
            });
        }
        console.error('VMO draft save failed:', err);
        // Always keep a local copy as a safety net so the user does not lose work,
        // but show the real error so they know to retry once VMO is reachable.
        vmoStoreEmailDraftLocally(payload);
        if (!opts.silent && typeof vmoToast === 'function') {
            var msg = (err && err.message) ? err.message : 'Unknown error';
            vmoToast('Could not save draft to VMO (' + msg + '). A local backup was kept; please retry to store it in VMO.', 'error');
        }
        throw err;
    });
}
window.vmoBuildComposeDraftPayload = window.vmoBuildComposeDraftPayload || vmoBuildComposeDraftPayload;
window.vmoSaveEmailDraftPayload = window.vmoSaveEmailDraftPayload || vmoSaveEmailDraftPayload;

function vmoSaveDraft() {
    var payload = vmoBuildComposeDraftPayload();
    var subjectValue = (document.getElementById('vmo-compose-subject') || {}).value || '';
    if (!String(subjectValue || '').trim() && !String(payload.message || '').replace(/<[^>]+>/g, ' ').trim()) {
        if (typeof vmoToast === 'function') { vmoToast('Add a subject or message before saving a draft.', 'error'); }
        return Promise.resolve({ success: false });
    }
    return vmoSaveEmailDraftPayload(payload, { success: 'Draft saved to VMO. Starting a fresh email.' })
        .then(function(data) {
            // After a successful save, hand the user a brand-new compose surface so
            // they can write the next message without manual cleanup.
            if (data && data.success && !data.fallback) {
                vmoResetComposeForm();
                if (typeof vmoSwitchComposeTab === 'function') vmoSwitchComposeTab('write');
                vmoRefreshDraftViewsAfterMutation(true);
            }
            return data;
        })
        .catch(function() { return { success: false }; });
}

// ---------------------------------------------------------------------------
// Drafts list (Compose modal -> Drafts tab)
// ---------------------------------------------------------------------------
window.__vmoLoadedDrafts = window.__vmoLoadedDrafts || [];

function vmoEscapeForDraftAttr(s) {
    return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

window.vmoLoadEmailDrafts = function() {
    var listEl = document.getElementById('vmo-compose-drafts-list');
    var fetcher = (typeof window.vmoApiFetch === 'function') ? window.vmoApiFetch : (typeof vmoApiFetch === 'function' ? vmoApiFetch : null);
    var currentAccount = (typeof vmoGetCurrentMailboxSelectionForEmailTools === 'function') ? vmoGetCurrentMailboxSelectionForEmailTools() : { account: '', mailbox_id: '' };
    var query = 'per_page=50'
        + (currentAccount.account ? ('&account=' + encodeURIComponent(currentAccount.account)) : '')
        + (currentAccount.mailbox_id ? ('&mailbox_id=' + encodeURIComponent(currentAccount.mailbox_id)) : '');
    var ajaxPayload = Object.assign({ per_page: 50 }, currentAccount || {});
    var loadPromise = fetcher
        ? fetcher('vmo-manager/v1/emails/drafts?' + query, { method: 'GET' }).catch(function(err) {
            if (vmoEmailShouldUseAjaxFallback(err)) {
                return vmoEmailAdminAjax('vmo_get_email_drafts', ajaxPayload);
            }
            throw err;
        })
        : vmoEmailAdminAjax('vmo_get_email_drafts', ajaxPayload);
    if (listEl) listEl.innerHTML = '<div style="color:var(--muted); text-align:center; padding:30px;">Loading drafts…</div>';
    return loadPromise
        .then(function(data) {
            var drafts = (data && data.success && Array.isArray(data.drafts)) ? data.drafts : [];
            window.__vmoLoadedDrafts = drafts;
            if (typeof window.vmoUpdateDraftBadges === 'function') window.vmoUpdateDraftBadges(drafts.length || 0);
            if (!listEl) return drafts;
            if (!drafts.length) {
                listEl.innerHTML = '<div style="color:var(--muted); text-align:center; padding:30px;">No saved drafts yet. Use <strong>Save as Draft</strong> on a message to keep it here.</div>';
                return drafts;
            }
            listEl.innerHTML = drafts.map(function(d) {
                var subj = vmoEscapeForDraftAttr(d.subject || 'Untitled draft');
                var to   = vmoEscapeForDraftAttr(d.to_email || '');
                var when = vmoEscapeForDraftAttr(d.updated_at || d.created_at || '');
                var snippet = vmoEscapeForDraftAttr(String(d.message || '').replace(/<[^>]+>/g,' ').replace(/\s+/g,' ').trim().slice(0,140));
                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; flex-wrap:wrap;">'
                    +   '<div style="min-width:0; flex:1;">'
                    +     '<div style="font-weight:700; color:#fff; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">' + subj + '</div>'
                    +     '<div style="font-size:12px; color:var(--muted);">To: ' + (to || '<em>no recipient</em>') + ' • ' + when + '</div>'
                    +   '</div>'
                    +   '<div style="display:flex; gap:6px; flex:0 0 auto;">'
                    +     '<button class="vmo-btn-small" onclick="vmoOpenDraftForEdit(' + parseInt(d.id, 10) + ')">Open</button>'
                    +     '<button class="vmo-btn-small" onclick="vmoDeleteEmailDraft(' + parseInt(d.id, 10) + ')" title="Delete draft">Delete</button>'
                    +   '</div>'
                    + '</div>'
                    + (snippet ? '<div style="font-size:12px; color:#cfe3ff; line-height:1.5;">' + snippet + '</div>' : '')
                    + '</div>';
            }).join('');
            return drafts;
        })
        .catch(function(err) {
            console.error('Failed to load drafts:', err);
            if (listEl) listEl.innerHTML = '<div style="color:#ffb4b4; text-align:center; padding:30px;">Could not load drafts: ' + vmoEscapeForDraftAttr(err && err.message || 'Unknown error') + '</div>';
            return [];
        });
};

window.vmoOpenDraftForEdit = function(draftId) {
    var d = (window.__vmoLoadedDrafts || []).find(function(x) { return parseInt(x.id, 10) === parseInt(draftId, 10); });
    if (!d) {
        if (typeof vmoToast === 'function') vmoToast('Draft not found. Refresh the list and try again.', 'error');
        return;
    }
    var setVal = function(id, v) { var el = document.getElementById(id); if (el) el.value = v == null ? '' : v; };
    setVal('vmo-compose-to', d.to_email);
    setVal('vmo-compose-cc', d.cc_email);
    setVal('vmo-compose-bcc', d.bcc_email);
    setVal('vmo-compose-subject', d.subject);
    var fromSel = document.getElementById('vmo-compose-from');
    if (fromSel && d.from_email) {
        var found = Array.prototype.some.call(fromSel.options, function(o) { return o.value === d.from_email; });
        if (found) fromSel.value = d.from_email;
    }
    if (typeof vmoSetComposeBody === 'function') vmoSetComposeBody(d.message || '');
    if (typeof vmoSwitchComposeTab === 'function') vmoSwitchComposeTab('write');
    if (typeof vmoToast === 'function') vmoToast('Draft loaded. Edit and send when ready.', 'success');
};

window.vmoDeleteEmailDraft = function(draftId) {
    if (!draftId) return;
    if (!window.confirm('Delete this draft? This cannot be undone.')) return;
    var fetcher = (typeof window.vmoApiFetch === 'function') ? window.vmoApiFetch : (typeof vmoApiFetch === 'function' ? vmoApiFetch : null);
    var deletePromise = fetcher
        ? fetcher('vmo-manager/v1/emails/' + parseInt(draftId, 10), { method: 'DELETE' }).catch(function(err) {
            if (vmoEmailShouldUseAjaxFallback(err)) {
                return vmoEmailAdminAjax('vmo_delete_email_draft', { id: parseInt(draftId, 10) });
            }
            throw err;
        })
        : vmoEmailAdminAjax('vmo_delete_email_draft', { id: parseInt(draftId, 10) });
    deletePromise
        .then(function() {
            if (typeof vmoToast === 'function') vmoToast('Draft deleted.', 'success');
            vmoRefreshDraftViewsAfterMutation(false);
        })
        .catch(function(err) {
            if (typeof vmoToast === 'function') vmoToast('Could not delete draft: ' + (err && err.message || 'Unknown error'), 'error');
        });
};
</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>

<!-- VMO Email AI Assistant Modal -->
<?php /*
  ==================================================================
  FUTURE ROADMAP - JARVIS-STYLE EMAIL ORCHESTRATION (next version)
  ==================================================================
  This modal currently supports: conversational chat -> draft preview
  -> Use This Email -> editable compose body -> manual send/save.

  The NEXT version must extend this surface so a user can simply say
  (or type) a single instruction like:
      "Send a persuasive email to <contacts>, telling them <message>,
       track opens and replies, and keep replying until they
       <purchase | register | book | reply | etc.>"
  ...and VMO will:
    1. Generate the draft via the email_ai_chat nano-agent
       (already in includes/class-vmo-manager-api.php).
    2. If the user is in a voice conversation, READ THE DRAFT ALOUD
       through assets/vmo-tts-hd.js and loop refine -> re-read until
       the user verbally approves.
    3. Resolve recipients from the CRM directory and report
       recipient_count + estimated token cost. If the cost would
       materially impact the user's balance, advise them BEFORE send.
    4. On explicit user approval, send through the operational mail
       transport for the chosen From identity so the messages appear
       in the user's own Sent folder (as if they typed each one).
    5. KEEP the approved draft in Drafts after send so it can be
       reused or forked.
    6. Track opens, clicks, and inbound replies. The Emails UI must
       show the full trace per contact: original prompt, every
       refinement turn, the final approved copy, the sent message,
       all recipient replies, and any AI auto-replies.
    7. Provide a per-thread / per-campaign "AI auto-reply" TOGGLE
       (default OFF). When ON, inbound replies route back through the
       nano-agent with the full thread + the desired outcome goal,
       and it auto-replies until the goal is achieved, the user
       toggles auto-reply off, or human discretion is required (in
       which case an Action is created in the Today/Actions surface
       instead).
    8. PRESERVE every manual control already in this modal and the
       compose modal so power users can still do everything by hand.
       Iron Man's Jarvis principle: the AI does it all by default,
       but the dashboard remains fully usable without the AI.

  Hooks the next dev should wire to / extend (do NOT regress them):
    - vmoEmailAiAddDraftFromEnvelope(draft)  // adds AI draft to right pane
    - vmoUseEmailVariant(id)                 // inserts to editable compose body
    - vmoSaveEmailDraftPayload / vmoBuildComposeDraftPayload
    - window.VMOAudioCoordinator             // mic arbitration
    - assets/vmo-tts-hd.js                   // read-aloud loop
    - assets/vmo-voice-panel.js              // voice in/out surface
    - REST: vmo-manager/v1/emails/ai-chat    // returns {reply, ready_to_draft, draft, ...}

  Source-of-truth manual (extended FUTURE ROADMAP section):
    EVERY VMO FEATURE MANUAL/EMAILING SYSTEM/
    vmo_emailing_system_source_of_truth_with_interfaces.txt
  ==================================================================
*/ ?>
<div id="vmo-email-ai-modal" class="vmo-tools-overlay">
    <div class="vmo-modal-content vmo-email-modal" style="max-width: 1100px;">
        <div class="vmo-modal-header">
            <h3>&#10024; VMO Email Assistant</h3>
            <button class="vmo-modal-close" onclick="vmoCloseEmailAssistant()">×</button>
        </div>
        <div class="vmo-modal-body" style="display:grid; grid-template-columns:minmax(280px, 0.9fr) minmax(360px, 1.1fr); gap:16px; height: 650px; overflow:hidden;">
            <div style="display:flex; flex-direction:column; min-width:0; border:1px solid var(--border); border-radius:10px; overflow:hidden;">
                <div style="padding:12px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; gap:10px;">
                    <strong style="color:var(--cyan-soft);">Ask VMO</strong>
                    <button class="vmo-btn-small" onclick="vmoEmailResetAssistant()" title="Reset chat and drafts">Reset</button>
                </div>
                <div id="vmo-email-ai-chat-log" style="flex:1; overflow:auto; padding:14px; display:flex; flex-direction:column; gap:10px;">
                    <?php
                    $vmo_email_greet_user_id = get_current_user_id();
                    $vmo_email_greet_first_name = '';
                    if (function_exists('vmo_get_greeting_display_name')) {
                        $vmo_email_greet_first_name = (string) vmo_get_greeting_display_name();
                    }
                    if ($vmo_email_greet_first_name === '' && $vmo_email_greet_user_id) {
                        $vmo_email_greet_user_obj = get_userdata($vmo_email_greet_user_id);
                        if ($vmo_email_greet_user_obj) {
                            $vmo_email_greet_first_name = (string) ($vmo_email_greet_user_obj->first_name ?: $vmo_email_greet_user_obj->display_name ?: '');
                        }
                    }
                    $vmo_email_greet_business = $vmo_email_greet_user_id ? (string) get_user_meta($vmo_email_greet_user_id, 'business_name', true) : '';
                    if ($vmo_email_greet_business === '') {
                        $vmo_email_greet_business = (string) get_user_meta($vmo_email_greet_user_id, 'vmo_business_name', true);
                    }
                    if ($vmo_email_greet_business === '') {
                        $vmo_email_greet_business = (string) get_bloginfo('name');
                    }
                    $vmo_email_greet_name_part = $vmo_email_greet_first_name !== '' ? ('Welcome, ' . esc_html($vmo_email_greet_first_name) . '.') : 'Welcome.';
                    $vmo_email_greet_biz_part = $vmo_email_greet_business !== '' ? (' Your ' . esc_html($vmo_email_greet_business) . ' profile is loaded - audience, offers, and tone are already in context.') : ' Your business profile is loaded and ready.';
                    ?>
                    <div id="vmo-email-ai-greeting" style="background:rgba(255,255,255,0.05); padding:12px; border-radius:10px; color:var(--ink);"
                         data-vmo-user-name="<?php echo esc_attr($vmo_email_greet_first_name); ?>"
                         data-vmo-business-name="<?php echo esc_attr($vmo_email_greet_business); ?>">
                        <?php echo $vmo_email_greet_name_part; ?> I'm your VMO Email Agent.<?php echo $vmo_email_greet_biz_part; ?> Tell me the recipient and the action you want them to take, and I'll prepare a draft. Each draft appears on the right - select <strong>Use This Email</strong> to load it into your editable compose body.
                    </div>
                </div>
                <div style="padding:12px; border-top:1px solid var(--border); display:flex; flex-direction:column; gap:10px;">
                    <textarea id="vmo-email-ai-prompt" class="vmo-input" rows="3" placeholder="e.g. Send a friendly follow-up to past clients about our new pricing..." style="resize:vertical;"></textarea>
                    <div style="display:flex; gap:8px; flex-wrap:wrap;">
                        <button class="vmo-btn vmo-btn-primary" onclick="vmoEmailAiChat()">Send</button>
                        <button id="vmo-email-ai-voice-btn" class="vmo-btn" onclick="vmoToggleEmailAiVoice()" title="Dictate prompt">Voice</button>
                    </div>
                </div>
            </div>
            <div style="display:flex; flex-direction:column; min-width:0; border:1px solid var(--border); border-radius:10px; overflow:hidden;">
                <div style="padding:12px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; gap:10px;">
                    <strong style="color:var(--cyan-soft);">Draft Previews</strong>
                    <button class="vmo-btn-small" onclick="vmoEmailClearGeneratedDrafts()" title="Remove all generated drafts">Clear</button>
                </div>
                <div id="vmo-email-variants-list" style="flex:1; overflow:auto; padding:14px; display:flex; flex-direction:column; gap:12px;">
                    <div style="color:var(--muted); text-align:center; padding:40px 20px;">Drafts will appear here as you chat. Click <strong>Use This Email</strong> on any draft to load it into the editable compose body.</div>
                </div>
            </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');
    };

    // Bounds applied to any logo selected for the signature so it always fits
    // the slot in the rendered email signature, regardless of the source image.
    window.VMO_SIG_LOGO_MAX_W = 160; // px in rendered HTML
    window.VMO_SIG_LOGO_MAX_H = 56;  // px in rendered HTML

    function vmoHasUsableWpMedia() {
        return !!(
            window.wp &&
            window.wp.media &&
            window.wp.media.view &&
            (window.wp.media.view.MediaFrame || window.wp.media.view.Frame) &&
            document.getElementById('tmpl-media-modal') &&
            document.getElementById('tmpl-attachment') &&
            (window._wpMediaViewsL10n || (window.wp.media.view && window.wp.media.view.settings) || (window.wp.media.model && window.wp.media.model.settings))
        );
    }

    function vmoEnsureWpMedia(cb) {
        if (vmoHasUsableWpMedia()) { cb(true); return; }
        if (window.wp && window.wp.media) { cb(false); return; }
        if (window.__vmoWpMediaLoading) {
            window.__vmoWpMediaLoadingCbs = window.__vmoWpMediaLoadingCbs || [];
            window.__vmoWpMediaLoadingCbs.push(cb);
            return;
        }
        window.__vmoWpMediaLoading = true;
        window.__vmoWpMediaLoadingCbs = [cb];
        var fire = function(ok) {
            window.__vmoWpMediaLoading = false;
            var cbs = window.__vmoWpMediaLoadingCbs || [];
            window.__vmoWpMediaLoadingCbs = [];
            cbs.forEach(function(fn){ try { fn(ok); } catch(_){} });
        };
        try {
            var ajaxUrl = (window.vmoAjax && vmoAjax.ajax_url) || window.ajaxurl || '/wp-admin/admin-ajax.php';
            var adminBase = ajaxUrl.replace(/admin-ajax\.php.*$/, '');
            var v = String(Date.now());
            // Bundle of scripts wp_enqueue_media() normally pulls in.
            var bundle = [
                'jquery','utils','underscore','backbone','wp-util','wp-backbone',
                'plupload','plupload-html5','wp-plupload',
                'jquery-ui-core','jquery-ui-position','jquery-ui-widget',
                'jquery-ui-mouse','jquery-ui-sortable','jquery-ui-draggable',
                'jquery-ui-resizable','jquery-ui-menu','jquery-ui-button',
                'mediaelement','wp-mediaelement',
                'media-models','media-views','media-editor','media-audiovideo',
                'image-edit'
            ].join(',');
            var styles = ['media-views','buttons','wp-mediaelement','imgareaselect','wp-jquery-ui-dialog'].join(',');
            // Load CSS first (non-blocking).
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = adminBase + 'load-styles.php?c=0&load%5B%5D=' + encodeURIComponent(styles) + '&ver=' + v;
            document.head.appendChild(link);
            // Load JS bundle.
            var s = document.createElement('script');
            s.src = adminBase + 'load-scripts.php?c=0&load%5B%5D=' + encodeURIComponent(bundle) + '&ver=' + v;
            s.onload = function() {
                // Some installs need a tick before wp.media.view.* constructors register.
                setTimeout(function(){ fire(vmoHasUsableWpMedia()); }, 50);
            };
            s.onerror = function() { fire(false); };
            document.head.appendChild(s);
        } catch (_) {
            fire(false);
        }
    }

    function vmoBestMediaImageUrl(item) {
        if (!item) return '';
        const sizes = item.media_details && item.media_details.sizes ? item.media_details.sizes : {};
        const preferred = ['medium', 'thumbnail', 'large', 'full'];
        for (const sizeName of preferred) {
            if (sizes[sizeName] && sizes[sizeName].source_url) {
                return sizes[sizeName].source_url;
            }
        }
        return item.source_url || '';
    }

    function vmoCloseSignatureLogoFallbackPicker() {
        const existing = document.getElementById('vmo-signature-logo-media-fallback');
        if (existing) existing.remove();
    }

    function vmoLoadSignatureLogoImages(search) {
        const fd = new FormData();
        fd.append('action', 'vmo_get_signature_media_images');
        fd.append('security', vmoSignatureSecurityNonce());
        fd.append('search', search || '');
        fd.append('per_page', '72');
        return vmoSignatureAjaxFetch(fd).then(function(resp) {
            const images = resp && resp.success && resp.data && Array.isArray(resp.data.images) ? resp.data.images : [];
            return images.map(function(item) {
                return {
                    id: item.id || 0,
                    source_url: item.url || item.source_url || '',
                    preview_url: item.preview_url || item.url || item.source_url || '',
                    title: { rendered: item.title || item.filename || 'Logo' },
                    slug: item.filename || item.title || 'Logo'
                };
            });
        }).catch(function(ajaxError) {
            const restRoot = ((window.wpApiSettings && window.wpApiSettings.root) || <?php echo wp_json_encode( esc_url_raw( rest_url() ) ); ?>).replace(/\/?$/, '/');
            const headers = { 'Accept': 'application/json' };
            const nonce = typeof vmoGetWpNonce === 'function' ? vmoGetWpNonce() : '';
            if (nonce) headers['X-WP-Nonce'] = nonce;
            const qs = new URLSearchParams({ media_type: 'image', per_page: '72', _fields: 'id,source_url,media_details,title,slug,mime_type' });
            if (search) qs.set('search', search);
            return vmoFetchJson(restRoot + 'wp/v2/media?' + qs.toString(), {
                credentials: 'same-origin',
                headers: headers
            }).catch(function(restError) {
                console.error('VMO media library load failed:', ajaxError, restError);
                throw restError;
            });
        });
    }

    function vmoOpenSignatureLogoFallbackPicker() {
        vmoCloseSignatureLogoFallbackPicker();
        const ajaxUrl = (window.vmoAjax && vmoAjax.ajax_url) || window.ajaxurl || '/wp-admin/admin-ajax.php';
        const adminBase = ajaxUrl.replace(/admin-ajax\.php.*$/, '');
        const overlay = document.createElement('div');
        overlay.id = 'vmo-signature-logo-media-fallback';
        overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483000;background:rgba(5,9,16,.72);display:flex;align-items:center;justify-content:center;padding:24px;';
        overlay.innerHTML = '<div style="width:min(980px,96vw);max-height:86vh;background:#fff;color:#101828;border-radius:10px;box-shadow:0 24px 80px rgba(0,0,0,.36);display:flex;flex-direction:column;overflow:hidden;">'
            + '<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 16px;border-bottom:1px solid #eaecf0;">'
            + '<strong style="font-size:16px;">Select Company Logo</strong>'
            + '<div style="display:flex;align-items:center;gap:8px;">'
            + '<a href="' + adminBase + 'upload.php" target="_blank" rel="noopener" style="font-size:13px;color:#2563eb;text-decoration:none;">Open Media Library</a>'
            + '<button type="button" data-vmo-media-close style="border:0;background:#f2f4f7;color:#101828;border-radius:6px;padding:7px 10px;cursor:pointer;">Close</button>'
            + '</div></div>'
            + '<div style="display:flex;gap:8px;align-items:center;padding:12px 16px;border-bottom:1px solid #eaecf0;">'
            + '<input type="search" data-vmo-media-search placeholder="Search images" style="flex:1;min-width:0;border:1px solid #d0d5dd;border-radius:7px;padding:8px 10px;">'
            + '<button type="button" data-vmo-media-search-btn style="border:1px solid #d0d5dd;background:#fff;color:#101828;border-radius:7px;padding:8px 12px;cursor:pointer;">Search</button>'
            + '</div>'
            + '<div data-vmo-media-status style="padding:18px;color:#475467;">Loading images...</div>'
            + '<div data-vmo-media-grid style="display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:12px;padding:0 16px 16px;overflow:auto;"></div>'
            + '</div>';
        document.body.appendChild(overlay);
        overlay.addEventListener('click', function(event) {
            if (event.target === overlay || event.target.closest('[data-vmo-media-close]')) {
                vmoCloseSignatureLogoFallbackPicker();
            }
        });

        const status = overlay.querySelector('[data-vmo-media-status]');
        const grid = overlay.querySelector('[data-vmo-media-grid]');
        const searchInput = overlay.querySelector('[data-vmo-media-search]');
        const searchBtn = overlay.querySelector('[data-vmo-media-search-btn]');
        const loadImages = function(search) {
            status.textContent = 'Loading images...';
            grid.innerHTML = '';
            vmoLoadSignatureLogoImages(search)
        .then(function(items) {
            const images = Array.isArray(items) ? items : [];
            if (!images.length) {
                status.textContent = 'No image files were found in the WordPress Media Library.';
                return;
            }
            status.textContent = '';
            grid.innerHTML = images.map(function(item) {
                const url = item.preview_url || vmoBestMediaImageUrl(item);
                const fullUrl = item.source_url || item.url || url;
                const title = item.title && item.title.rendered ? item.title.rendered : (item.slug || 'Logo');
                return '<button type="button" data-vmo-logo-url="' + vmoEscapeHtml(fullUrl) + '" data-vmo-logo-name="' + vmoEscapeHtml(title) + '" style="border:1px solid #d0d5dd;background:#fff;border-radius:8px;padding:8px;cursor:pointer;text-align:left;min-height:142px;display:flex;flex-direction:column;gap:8px;">'
                    + '<span style="height:92px;display:flex;align-items:center;justify-content:center;background:#f8fafc;border-radius:6px;overflow:hidden;"><img src="' + vmoEscapeHtml(url) + '" alt="" style="max-width:100%;max-height:92px;object-fit:contain;"></span>'
                    + '<span style="font-size:12px;line-height:1.3;color:#344054;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + vmoEscapeHtml(title) + '</span>'
                    + '</button>';
            }).join('');
            grid.querySelectorAll('[data-vmo-logo-url]').forEach(function(button) {
                button.addEventListener('click', function() {
                    const url = button.getAttribute('data-vmo-logo-url') || '';
                    const name = button.getAttribute('data-vmo-logo-name') || (url ? url.split('/').pop() : 'Selected image');
                    vmoApplySignatureLogo(url, name);
                    vmoCloseSignatureLogoFallbackPicker();
                });
            });
        })
        .catch(function(error) {
            console.error('VMO media fallback failed:', error);
            status.innerHTML = 'VMO could not load images from the Media Library. <a href="' + adminBase + 'upload.php" target="_blank" rel="noopener" style="color:#2563eb;">Open Media Library</a>';
        });
        };
        if (searchBtn) searchBtn.addEventListener('click', function(){ loadImages(searchInput ? searchInput.value : ''); });
        if (searchInput) searchInput.addEventListener('keydown', function(event){ if (event.key === 'Enter') { event.preventDefault(); loadImages(searchInput.value); } });
        loadImages('');
    }

    function vmoApplySignatureLogo(url, filename) {
        const cleanUrl = String(url || '');
        const input = document.getElementById('vmo-sig-logo');
        if (input) input.value = cleanUrl;
        const nameEl = document.getElementById('vmo-sig-logo-filename');
        if (nameEl) nameEl.textContent = filename || (cleanUrl ? cleanUrl.split('/').pop() : 'No logo selected');
        const wrap = document.getElementById('vmo-sig-logo-preview-wrap');
        const img = document.getElementById('vmo-sig-logo-preview');
        if (img) {
            img.src = cleanUrl;
            // Clamp the preview so the user sees the size that will actually render
            // in the signature, regardless of the source image's native dimensions.
            img.style.maxWidth = window.VMO_SIG_LOGO_MAX_W + 'px';
            img.style.maxHeight = window.VMO_SIG_LOGO_MAX_H + 'px';
            img.style.width = 'auto';
            img.style.height = 'auto';
            img.style.objectFit = 'contain';
            img.style.display = 'block';
        }
        if (wrap) wrap.style.display = cleanUrl ? 'block' : 'none';
    }

    window.vmoPickSignatureLogo = function() {
        var triggerBtn = (document.activeElement && document.activeElement.tagName === 'BUTTON') ? document.activeElement : null;
        if (triggerBtn) { triggerBtn.dataset.vmoOrigText = triggerBtn.textContent; triggerBtn.textContent = 'Opening Media Library...'; triggerBtn.disabled = true; }
        var restoreBtn = function(){ if (triggerBtn) { triggerBtn.disabled = false; if (triggerBtn.dataset.vmoOrigText) triggerBtn.textContent = triggerBtn.dataset.vmoOrigText; } };
        window.setTimeout(function() {
            restoreBtn();
            vmoOpenSignatureLogoFallbackPicker();
        }, 0);
    };

    // Map of platform -> {prefix shown to the user, full URL template using {handle}}.
    // The user only types their handle; we prepend the platform-specific URL on save.
    window.vmoSocialPlatformMeta = window.vmoSocialPlatformMeta || {
        linkedin:  { label: 'LinkedIn',  prefix: 'linkedin.com/in/',     template: 'https://www.linkedin.com/in/{handle}' },
        twitter:   { label: 'Twitter/X', prefix: 'x.com/',                template: 'https://x.com/{handle}' },
        facebook:  { label: 'Facebook',  prefix: 'facebook.com/',         template: 'https://www.facebook.com/{handle}' },
        instagram: { label: 'Instagram', prefix: 'instagram.com/',        template: 'https://www.instagram.com/{handle}' },
        youtube:   { label: 'YouTube',   prefix: 'youtube.com/@',         template: 'https://www.youtube.com/@{handle}' },
        tiktok:    { label: 'TikTok',    prefix: 'tiktok.com/@',          template: 'https://www.tiktok.com/@{handle}' },
        github:    { label: 'GitHub',    prefix: 'github.com/',           template: 'https://github.com/{handle}' },
        website:   { label: 'Website',   prefix: 'https://',              template: '{handle}' }
    };

    function vmoSocialBuildUrl(platform, handle) {
        const meta = window.vmoSocialPlatformMeta[platform];
        const cleaned = String(handle || '').trim().replace(/^[@\/]+/, '').replace(/[\s?#].*$/, '').replace(/\/+$/, '');
        if (!cleaned) return '';
        if (platform === 'website') {
            return /^https?:\/\//i.test(cleaned) ? cleaned : ('https://' + cleaned);
        }
        if (!meta) return cleaned;
        return meta.template.replace('{handle}', cleaned);
    }

    function vmoSocialExtractHandle(platform, url) {
        const meta = window.vmoSocialPlatformMeta[platform];
        const raw = String(url || '').trim();
        if (!raw) return '';
        if (platform === 'website') return raw;
        if (!meta) return raw;
        // Strip protocol + known host prefix to leave just the handle.
        let h = raw.replace(/^https?:\/\//i, '').replace(/^www\./i, '');
        const prefixes = [meta.prefix.replace(/^https?:\/\//i, '').replace(/^www\./i, '')];
        // Tolerate alternates (twitter.com vs x.com, m.facebook.com, etc.)
        if (platform === 'twitter') prefixes.push('twitter.com/');
        if (platform === 'facebook') prefixes.push('m.facebook.com/');
        for (const p of prefixes) {
            if (h.toLowerCase().indexOf(p.toLowerCase()) === 0) { h = h.slice(p.length); break; }
        }
        return h.replace(/^[@\/]+/, '').replace(/\/+$/, '');
    }

    function vmoSocialApplyPlatform(rowEl) {
        const sel = rowEl.querySelector('select.vmo-social-select');
        const input = rowEl.querySelector('input.vmo-social-url');
        const hintEl = rowEl.querySelector('.vmo-social-hint');
        if (!sel || !input) return;
        const meta = window.vmoSocialPlatformMeta[sel.value] || {};
        if (sel.value === 'website') {
            input.placeholder = 'yoursite.com';
        } else {
            input.placeholder = '@your-handle  (or just your-handle)';
        }
        if (hintEl) {
            const handle = String(input.value || '').trim().replace(/^[@\/]+/, '') || 'your-handle';
            const preview = (typeof vmoSocialBuildUrl === 'function') ? vmoSocialBuildUrl(sel.value, handle) : '';
            hintEl.textContent = preview ? ('Becomes: ' + preview) : '';
        }
    }

    window.vmoAddSocialInput = function(platform, handle) {
        const container = document.getElementById('vmo-sig-socials-container');
        const row = document.createElement('div');
        // Use CSS grid with three explicit tracks so the handle input always
        // gets the leftover space and the Remove button stays a small fixed
        // square. Previously a flex layout caused the input to render as a
        // tiny strip while the close button absorbed all the row width.
        row.style.cssText = 'display:grid; grid-template-columns:130px minmax(0,1fr) 32px; gap:8px; align-items:center; margin-bottom:10px;';
        row.innerHTML = `
            <select class="vmo-input vmo-social-select" style="width:100%; min-width:0;">
                <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="tiktok">TikTok</option>
                <option value="github">GitHub</option>
                <option value="website">Website</option>
            </select>
            <input type="text" class="vmo-input vmo-social-url" placeholder="@your-handle" style="width:100%; min-width:0; box-sizing:border-box;">
            <button class="vmo-btn" type="button" title="Remove this social link" aria-label="Remove" style="width:32px; height:32px; padding:0; line-height:1; display:flex; align-items:center; justify-content:center; flex:0 0 32px;">×</button>
            <div class="vmo-social-hint" style="grid-column:2 / span 2; font-size:11px; color:var(--muted); margin-top:-2px;"></div>
        `;
        container.appendChild(row);
        const sel = row.querySelector('select');
        const input = row.querySelector('input.vmo-social-url');
        const removeBtn = row.querySelector('button');
        if (platform && sel) sel.value = platform;
        if (handle && input) input.value = handle;
        if (removeBtn) removeBtn.addEventListener('click', () => row.remove());
        sel.addEventListener('change', () => vmoSocialApplyPlatform(row));
        input.addEventListener('input', () => vmoSocialApplyPlatform(row));
        vmoSocialApplyPlatform(row);
    };

    // Kept for backward compatibility but no longer used.
    window.vmoAutoDetectSocial = function(input) { /* no-op */ };

    function vmoSignatureAjaxUrlCandidates() {
        const urls = [];
        const add = (url) => {
            if (!url || typeof url !== 'string') return;
            const clean = url.trim();
            if (clean && urls.indexOf(clean) === -1) urls.push(clean);
        };
        try { add(window.ajaxurl); } catch (_) {}
        try { add(window.vmo_ajax && (window.vmo_ajax.ajaxurl || window.vmo_ajax.ajax_url)); } catch (_) {}
        try { add(window.vmoAjax && (window.vmoAjax.ajaxurl || window.vmoAjax.ajax_url || window.vmoAjax.url)); } catch (_) {}
        add(<?php echo wp_json_encode( esc_url_raw( admin_url( 'admin-ajax.php' ) ) ); ?>);
        try { add(window.location.origin + '/wp-admin/admin-ajax.php'); } catch (_) {}
        return urls;
    }

    function vmoSignatureSecurityNonce() {
        try {
            if (typeof vmo_builder_nonce !== 'undefined' && vmo_builder_nonce) return vmo_builder_nonce;
            if (window.vmo_ajax && (window.vmo_ajax.security || window.vmo_ajax.nonce)) return window.vmo_ajax.security || window.vmo_ajax.nonce;
            if (window.vmoAjax && (window.vmoAjax.security || window.vmoAjax.nonce)) return window.vmoAjax.security || window.vmoAjax.nonce;
        } catch (_) {}
        return (typeof vmoGetWpNonce === 'function') ? vmoGetWpNonce() : '';
    }

    function vmoCloneFormData(formData) {
        const cloned = new FormData();
        formData.forEach((value, key) => cloned.append(key, value));
        return cloned;
    }

    async function vmoSignatureAjaxFetch(formData) {
        const urls = vmoSignatureAjaxUrlCandidates();
        const security = vmoSignatureSecurityNonce();
        const wpNonce = (typeof vmoGetWpNonce === 'function') ? vmoGetWpNonce() : '';
        let lastError = null;

        for (const url of urls) {
            try {
                const body = vmoCloneFormData(formData);
                if (security && !body.has('security')) body.append('security', security);

                const headers = {};
                if (wpNonce) headers['X-WP-Nonce'] = wpNonce;

                const res = await fetch(url, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers,
                    body
                });
                const text = await res.text();
                let data = null;
                try {
                    data = text ? JSON.parse(text) : {};
                } catch (_) {
                    const trimmed = String(text || '').trim();
                    if (trimmed === '0') {
                        lastError = new Error('VMO signature service did not answer on admin-ajax. Refresh the dashboard or reinstall the latest plugin package.');
                        continue;
                    }
                    if (trimmed === '-1') {
                        throw new Error('Your VMO session expired. Refresh the dashboard and try saving the signature again.');
                    }
                    // [VMO_SIG_NONJSON_DEBUG] Surface the first chunk of the
                    // server response so the user (and support) can see what
                    // actually came back instead of a generic message.
                    try { console.warn('[VMO] Signature endpoint returned non-JSON:', trimmed.slice(0, 800)); } catch (_) {}
                    var preview = trimmed.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200);
                    lastError = new Error('VMO signature service returned a non-JSON response' + (preview ? (': "' + preview + '"') : '.') + ' Refresh the dashboard and try again.');
                    continue;
                }

                if (data === 0) {
                    lastError = new Error('VMO signature service did not answer on admin-ajax. Refresh the dashboard or reinstall the latest plugin package.');
                    continue;
                }
                if (data === -1) {
                    throw new Error('Your VMO session expired. Refresh the dashboard and try saving the signature again.');
                }

                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;
            } catch (err) {
                lastError = err;
            }
        }

        throw lastError || new Error('VMO could not reach the signature service. Please refresh the dashboard and try again.');
    }

    window.vmoSaveSignature = function(e) {
        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;

        // Required: full name. Without it the server INSERT fails (NOT NULL).
        if (!String(name || '').trim()) {
            alert('Please enter the Full Name that should appear on the signature.');
            const nameEl = document.getElementById('vmo-sig-name');
            if (nameEl) nameEl.focus();
            return;
        }

        const socials = [];
        document.querySelectorAll('#vmo-sig-socials-container > div').forEach(div => {
            const sel = div.querySelector('select');
            const input = div.querySelector('input.vmo-social-url');
            if (!sel || !input) return;
            const platform = sel.value;
            const handle = String(input.value || '').trim();
            if (!handle) return;
            // Build the full URL from the handle for the server. The server will
            // also normalize, but doing it here keeps the saved value readable.
            const url = (typeof vmoSocialBuildUrl === 'function') ? vmoSocialBuildUrl(platform, handle) : handle;
            if (url) socials.push({ platform, url });
        });

        const formData = new FormData();
        formData.append('action', 'vmo_save_email_signature');
        formData.append('security', vmoSignatureSecurityNonce());
        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);

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

        vmoSignatureAjaxFetch(formData)
        .then(data => {
            if (data && data.success) {
                alert('Signature saved!');
                vmoCloseSignatureModal();
            } else {
                var rawMsg = (data && data.data && data.data.message) ? data.data.message : 'Unable to save signature.';
                var dbErr = (data && data.data && data.data.db_error) ? (' (DB: ' + data.data.db_error + ')') : '';
                try { if (data && data.data) console.warn('[VMO] Save signature server error payload:', data.data); } catch (_) {}
                alert('Error: ' + rawMsg + dbErr);
            }
        })
        .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'; }
        });
    };

    // [VMO_SIG_BUILD_HTML] Build the inline-styled HTML signature block
    // from whatever is currently in the Signature Maker form. Used by
    // "Save & Insert into Email" and by future per-account loaders.
    window.vmoBuildSignatureHtml = function() {
        var name = (document.getElementById('vmo-sig-name') || {}).value || '';
        var role = (document.getElementById('vmo-sig-role') || {}).value || '';
        var color = (document.getElementById('vmo-sig-color') || {}).value || '#0fe1ff';
        var logo = (document.getElementById('vmo-sig-logo') || {}).value || '';
        var website = (document.getElementById('vmo-sig-website') || {}).value || '';
        var esc = window.vmoEscapeHtml;
        var socials = [];
        document.querySelectorAll('#vmo-sig-socials-container > div').forEach(function(div) {
            var sel = div.querySelector('select');
            var input = div.querySelector('input.vmo-social-url');
            if (!sel || !input) return;
            var platform = sel.value;
            var handle = String(input.value || '').trim();
            if (!handle) return;
            var url = (typeof vmoSocialBuildUrl === 'function') ? vmoSocialBuildUrl(platform, handle) : handle;
            if (!url) return;
            var label = platform.charAt(0).toUpperCase() + platform.slice(1);
            socials.push('<a href="' + esc(url) + '" style="color:' + esc(color) + ';text-decoration:none;margin-right:10px;">' + esc(label) + '</a>');
        });
        var parts = [];
        parts.push('<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="font-family:Arial,Helvetica,sans-serif;color:#222;font-size:13px;line-height:1.5;border-top:2px solid ' + esc(color) + ';padding-top:10px;margin-top:18px;">');
        parts.push('<tr>');
        if (logo) {
            // [VMO_SIG_LOGO_FIT] Constrain logo proportionally so it cannot distort,
            // displace adjacent signature content, or blow out an email client layout.
            // max-width/max-height + width/height:auto + object-fit:contain together force
            // a proportional fit inside the slot regardless of the source dimensions.
            var maxW = (window.VMO_SIG_LOGO_MAX_W || 160);
            var maxH = (window.VMO_SIG_LOGO_MAX_H || 56);
            parts.push('<td style="padding-right:14px;vertical-align:top;width:' + maxW + 'px;"><img src="' + esc(logo) + '" alt="" width="' + maxW + '" style="max-width:' + maxW + 'px;max-height:' + maxH + 'px;width:auto;height:auto;object-fit:contain;display:block;border:0;"></td>');
        }
        parts.push('<td style="vertical-align:top;">');
        if (name) { parts.push('<div style="font-weight:700;font-size:15px;color:#111;">' + esc(name) + '</div>'); }
        if (role) { parts.push('<div style="color:#555;margin-top:2px;">' + esc(role) + '</div>'); }
        if (website) { parts.push('<div style="margin-top:4px;"><a href="' + esc(website) + '" style="color:' + esc(color) + ';text-decoration:none;">' + esc(website) + '</a></div>'); }
        if (socials.length) { parts.push('<div style="margin-top:6px;">' + socials.join('') + '</div>'); }
        parts.push('</td>');
        parts.push('</tr></table>');
        return parts.join('');
    };

    // [VMO_SIG_SAVE_AND_INSERT] Save signature, then append/replace it in
    // the Compose Email body so the user does not have to reload, copy or
    // re-do anything. If the Compose modal is not open, just save.
    window.vmoSaveAndInsertSignature = function(e) {
        var nameEl = document.getElementById('vmo-sig-name');
        if (nameEl && !String(nameEl.value || '').trim()) {
            alert('Please enter the Full Name that should appear on the signature.');
            nameEl.focus();
            return;
        }
        var btn = e && e.currentTarget ? e.currentTarget : (e && e.target ? e.target : null);
        if (btn) { btn.disabled = true; btn.dataset.vmoOrigText = btn.textContent; btn.textContent = 'Saving & inserting…'; }
        var formData = new FormData();
        formData.append('action', 'vmo_save_email_signature');
        formData.append('security', vmoSignatureSecurityNonce());
        formData.append('account', (document.getElementById('vmo-sig-account') || {}).value || 'default');
        formData.append('name', (document.getElementById('vmo-sig-name') || {}).value || '');
        formData.append('designation', (document.getElementById('vmo-sig-role') || {}).value || '');
        formData.append('theme_color', (document.getElementById('vmo-sig-color') || {}).value || '');
        formData.append('logo_url', (document.getElementById('vmo-sig-logo') || {}).value || '');
        formData.append('website_url', (document.getElementById('vmo-sig-website') || {}).value || '');
        var socials = [];
        document.querySelectorAll('#vmo-sig-socials-container > div').forEach(function(div) {
            var sel = div.querySelector('select');
            var input = div.querySelector('input.vmo-social-url');
            if (!sel || !input) return;
            var p = sel.value;
            var h = String(input.value || '').trim();
            if (!h) return;
            var url = (typeof vmoSocialBuildUrl === 'function') ? vmoSocialBuildUrl(p, h) : h;
            if (url) socials.push({ platform: p, url: url });
        });
        formData.append('social_links', JSON.stringify(socials));

        vmoSignatureAjaxFetch(formData).then(function(data) {
            var sigHtml = window.vmoBuildSignatureHtml();
            // Try to insert into the active compose body (visual or html mode).
            var visual = document.getElementById('vmo-compose-visual-editor');
            var bodyTa = document.getElementById('vmo-compose-body');
            var inserted = false;
            if (visual && visual.offsetParent !== null) {
                // Strip any prior signature block we previously inserted.
                visual.innerHTML = (visual.innerHTML || '').replace(/<!--vmo-sig-start-->[\s\S]*?<!--vmo-sig-end-->/g, '');
                visual.innerHTML += '<!--vmo-sig-start-->' + sigHtml + '<!--vmo-sig-end-->';
                inserted = true;
            } else if (bodyTa) {
                var cur = bodyTa.value || '';
                cur = cur.replace(/<!--vmo-sig-start-->[\s\S]*?<!--vmo-sig-end-->/g, '');
                bodyTa.value = cur + '\n<!--vmo-sig-start-->' + sigHtml + '<!--vmo-sig-end-->';
                inserted = true;
            }
            if (data && data.success) {
                if (typeof vmoToast === 'function') {
                    vmoToast(inserted ? 'Signature saved and inserted into your email.' : 'Signature saved.', 'success');
                } else {
                    alert(inserted ? 'Signature saved and inserted into your email.' : 'Signature saved.');
                }
                vmoCloseSignatureModal();
            } else {
                var rawMsg = (data && data.data && data.data.message) ? data.data.message : 'Unable to save signature.';
                var dbErr = (data && data.data && data.data.db_error) ? (' (DB: ' + data.data.db_error + ')') : '';
                alert('Saved locally but server reported: ' + rawMsg + dbErr);
            }
        }).catch(function(err) {
            console.error('Save & insert signature failed:', err);
            alert('Error saving signature: ' + (err && err.message ? err.message : 'Unknown error'));
        }).finally(function() {
            if (btn) { btn.disabled = false; btn.textContent = btn.dataset.vmoOrigText || '💾 Save & Insert into Email'; }
        });
    };

    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', vmoSignatureSecurityNonce());

        vmoSignatureAjaxFetch(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 => {
                    const platform = s && s.platform ? String(s.platform) : 'website';
                    const url = s && s.url ? String(s.url) : '';
                    // Show the handle (not the full URL) in the input now.
                    const handle = (typeof vmoSocialExtractHandle === 'function') ? vmoSocialExtractHandle(platform, url) : url;
                    vmoAddSocialInput(platform, handle);
                });
            })
            .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', vmoSignatureSecurityNonce());

        vmoSignatureAjaxFetch(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 = async function(folder) {
        const folderKey = String(folder || 'inbox');
        try { window.vmoCurrentMailboxFolder = folderKey; } 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*="${folderKey}"]`);
        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(folderKey) + '…</div>';

        const hasAccounts = await vmoMailboxHasAccounts();
        if (hasAccounts === false && folderKey !== 'drafts') {
            listEl.innerHTML = vmoMailboxNoAccountHtml(folderKey);
            return;
        }

        const params = new URLSearchParams();
        params.set('folder', folderKey);
        params.set('type', 'transactional');

        vmoApiFetch('vmo-manager/v1/emails?' + params.toString(), { method: 'GET' })
        .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(folderKey)}</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(folderKey).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(folderKey)}')">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>VMO could not load this mailbox folder right now. Please refresh the dashboard and try again.</p>
            `;
        });
    };

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

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

        const safeFolder = String(folder || (window.vmoCurrentMailboxFolder || 'inbox'));

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

        vmoApiFetch('vmo-manager/v1/emails/' + emailId, { method: 'GET' })
        .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 safeFolder = String(folder || (window.vmoCurrentMailboxFolder || 'inbox'));
        vmoApiFetch('vmo-manager/v1/emails/' + emailId, { method: 'DELETE' })
        .then(() => {
            window.vmoSwitchBulkFolder(safeFolder);
        })
        .catch(err => {
            console.error('Email delete error:', err);
            vmoToast('Network error deleting email.', 'error');
        });
    };

    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');
        if (typeof vmoPopulateComposeAccounts === 'function') {
            vmoPopulateComposeAccounts();
        }
    };

    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 = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : 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>';
                }
            }

            if (tabName === 'drafts' && typeof window.vmoLoadEmailDrafts === 'function') {
                window.vmoLoadEmailDrafts();
            }
        }
    };

    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.vmoRestRoot || (window.wpApiSettings && 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 '';
        }
    }

    function vmoBuildRestUrl(path, root) {
        const raw = String(path || '');
        if (/^https?:\/\//i.test(raw)) return raw;
        const clean = raw.replace(/^\/+/, '');
        const parts = clean.split('?');
        const route = parts.shift() || '';
        const query = parts.join('?');
        const base = String(root || vmoGetApiRoot());
        if (base.indexOf('rest_route=') !== -1) {
            const prefix = base.endsWith('/') ? base : (base + (base.indexOf('rest_route=/') !== -1 ? '' : '/'));
            return prefix + route + (query ? '&' + query : '');
        }
        return base.replace(/\/?$/, '/') + route + (query ? '?' + query : '');
    }

    function vmoRestRootsFor(path) {
        const raw = String(path || '');
        if (/^https?:\/\//i.test(raw) && raw.indexOf('/wp-json/') === -1) return [raw];
        const roots = [];
        const primary = vmoGetApiRoot();
        const originRoot = window.location.origin + '/wp-json/';
        const queryRoot = (window.wpApiSettings && window.wpApiSettings.altRoot) ? String(window.wpApiSettings.altRoot) : (window.location.origin + '/?rest_route=/');
        [primary, originRoot, queryRoot].forEach(root => {
            if (root && roots.indexOf(root) === -1) roots.push(root);
        });
        return roots;
    }

    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 fetchOpts = Object.assign({}, opts);
        delete fetchOpts._vmoRoot;
        const res = await fetch(url, Object.assign({}, fetchOpts, {
            headers,
            credentials: 'same-origin'
        }));

        const text = await res.text();
        let data;
        try {
            data = text ? JSON.parse(text) : {};
        } catch (e) {
            if (!opts._vmoRetried && String(url).indexOf('/wp-json/') !== -1) {
                try {
                    const parsedUrl = new URL(String(url), window.location.origin);
                    const idx = parsedUrl.pathname.indexOf('/wp-json/');
                    const route = idx >= 0 ? parsedUrl.pathname.slice(idx + '/wp-json'.length) : '';
                    if (route) {
                        const alt = parsedUrl.origin + '/?rest_route=' + route + (parsedUrl.search ? '&' + parsedUrl.search.slice(1) : '');
                        return vmoFetchJson(alt, Object.assign({}, opts, { _vmoRetried: true }));
                    }
                } catch (_) {}
            }
            throw new Error('VMO could not reach the requested service. Please refresh or check REST routing.');
        }

        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;
    }

    async function vmoApiFetch(path, options) {
        const roots = vmoRestRootsFor(path);
        let lastError = null;
        for (const root of roots) {
            try {
                const url = /^https?:\/\//i.test(String(path || '')) && String(path).indexOf('/wp-json/') === -1
                    ? String(path)
                    : vmoBuildRestUrl(path, root);
                return await vmoFetchJson(url, Object.assign({}, options || {}, { _vmoRoot: root }));
            } catch (err) {
                lastError = err;
                const message = String(err && err.message || '');
                const routingError = message.includes('REST routing') || message.includes('No route was found') || message === 'HTTP 404' || message.includes('rest_no_route');
                if (!routingError) {
                    throw err;
                }
            }
        }
        throw lastError || new Error('VMO could not reach the requested service. Please refresh or check REST routing.');
    }
    window.vmoApiFetch = window.vmoApiFetch || vmoApiFetch;
    window.vmoFetchJson = window.vmoFetchJson || vmoFetchJson;

    function vmoPopulateComposeAccounts() {
        const select = document.getElementById('vmo-compose-from');
        if (!select || select.__vmoLoadingAccounts) return;
        const previous = select.value || '';
        select.__vmoLoadingAccounts = true;
        select.innerHTML = '<option value="">Checking email accounts...</option>';

        vmoApiFetch('vmo-manager/v1/email-accounts', { method: 'GET' })
            .then(data => {
                const accounts = Array.isArray(data && data.accounts) ? data.accounts : [];
                select.innerHTML = '';
                if (!accounts.length) {
                    const option = document.createElement('option');
                    option.value = '';
                    option.textContent = 'No provisioned email yet - drafts only';
                    select.appendChild(option);
                    select.dataset.vmoProvisioned = '0';
                    return;
                }

                accounts.forEach(account => {
                    const email = account && account.email ? String(account.email) : '';
                    if (!email) return;
                    const option = document.createElement('option');
                    option.value = email;
                    option.textContent = account.display_name ? String(account.display_name) + ' <' + email + '>' : email;
                    if (account.id) option.dataset.mailboxId = String(account.id);
                    select.appendChild(option);
                });
                select.dataset.vmoProvisioned = select.options.length ? '1' : '0';
                if (previous) {
                    const found = Array.from(select.options).some(option => option.value === previous);
                    if (found) select.value = previous;
                }
                if (!select.value && select.options.length) select.selectedIndex = 0;
            })
            .catch(err => {
                console.error('Failed to load compose email accounts:', err);
                select.innerHTML = '<option value="">Email accounts unavailable - drafts only</option>';
                select.dataset.vmoProvisioned = '0';
            })
            .finally(() => {
                select.__vmoLoadingAccounts = false;
            });
    }

    function vmoMailboxNoAccountHtml(folder) {
        const folderLabel = vmoEscapeHtml(String(folder || 'inbox'));
        return '<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:220px;color:var(--muted);padding:32px;text-align:center;">'
            + '<div style="font-size:42px;margin-bottom:12px;opacity:.45;">&#128231;</div>'
            + '<h4 style="margin:0 0 8px;color:#e6f3ff;font-size:16px;">No provisioned email account yet</h4>'
            + '<p style="margin:0 0 14px;max-width:520px;line-height:1.5;">Your ' + folderLabel + ' will appear after VMO creates or connects a business email address. You can still create AI drafts, but incoming and sent mail need a real mailbox.</p>'
            + '<div style="display:flex;gap:10px;flex-wrap:wrap;justify-content:center;">'
            + '<button type="button" class="vmo-btn vmo-btn-primary" onclick="window.location.href=window.vmoConsultationUrl||\'admin.php?page=vmo-ai-builder-main\'">Open Business Wizard</button>'
            + '<button type="button" class="vmo-btn" onclick="vmoShowEmailSetupNotice(\'accounts\')">Setup options</button>'
            + '</div>'
            + '</div>';
    }

    async function vmoMailboxHasAccounts() {
        if (typeof window.__vmoMailboxHasAccounts === 'boolean') {
            return window.__vmoMailboxHasAccounts;
        }
        try {
            const data = await vmoApiFetch('vmo-manager/v1/email-accounts', { method: 'GET' });
            const accounts = Array.isArray(data && data.accounts) ? data.accounts : [];
            window.__vmoMailboxHasAccounts = accounts.length > 0;
            return window.__vmoMailboxHasAccounts;
        } catch (err) {
            console.error('Failed to check email accounts:', err);
            window.__vmoMailboxHasAccounts = null;
            return null;
        }
    }

    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 search = searchEl ? (searchEl.value || '').trim() : '';

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

        const params = new URLSearchParams();
        if (search) params.set('search', search);
        params.set('per_page', '24');

        vmoStoreProductsFetch(search, 24)
        .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;">
                            <button class="action-btn primary" onclick="vmoInsertSingleProductCard(${id})">Insert card</button>
                            <button class="action-btn" onclick="vmoInsertSingleBuyButton(${id})">Buy button</button>
                            <button class="action-btn" onclick="vmoInsertProductUpsellBlock(${id})">Upsell block</button>
                            ${p.buy_url ? `<a class="action-btn" href="${vmoEscapeHtml(p.buy_url)}" target="_blank" rel="noopener">Open 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 = 'VMO could not load products. Please refresh or check REST routing.';
            vmoToast('VMO could not load products. Please refresh or check REST routing.', 'error');
        });
    };

    window.vmoInsertSelectedProducts = function() {
        const checks = Array.from(document.querySelectorAll('.vmo-product-pick:checked'));
        if (!checks.length) {
            vmoToast('Please select at least one product.', 'error');
            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) {
            vmoToast('Selected products are no longer loaded. Please search again and re-select.', 'error');
            return;
        }

        vmoCheckoutForProductIds(ids).then(checkoutUrl => {
        try {
            if (!selected.length) {
                vmoToast('Could not load selected product details.', 'error');
                return;
            }

            const cards = selected.map(p => {
                p = vmoProductWithCheckout(p, checkoutUrl);
                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.checkout_url || p.buy_url || p.store_url || '#';
                const btnLabel = (p.checkout_url || 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 current = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : (document.getElementById('vmo-compose-body').value || '');
            vmoSetComposeBody(current + '\n' + cards + '\n');
            window.__vmoSelectedEmailProductIds = ids;
            vmoCloseProductPicker();
            vmoSwitchComposeTab('preview');
            vmoToast('Product block inserted.', 'success');
        } catch (err) {
            console.error('Insert products error:', err);
            vmoToast('Error while inserting products.', 'error');
        }
        });
    };

    function vmoAppendToCompose(html, message) {
        const current = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : (document.getElementById('vmo-compose-body').value || '');
        vmoSetComposeBody(current + '\n' + html + '\n');
        if (message) vmoToast(message, 'success');
    }

    function vmoFindCachedProduct(id) {
        const cached = (function(){ try { return Array.isArray(window.__vmoStoreProducts) ? window.__vmoStoreProducts : []; } catch(_) { return []; } })();
        return cached.find(p => Number(p.id) === Number(id));
    }

    function vmoStoreProductsFetch(search, perPage) {
        const params = new URLSearchParams();
        if (search) params.set('search', search);
        params.set('per_page', String(perPage || 24));
        return vmoApiFetch('vmo-manager/v1/store/products?' + params.toString(), { method: 'GET' })
            .catch(function(err) {
                console.warn('VMO product REST fallback:', err);
                return vmoEmailAdminAjax('vmo_get_store_products', { search: search || '', per_page: perPage || 24 });
            });
    }

    function vmoStoreCheckoutFetch(ids) {
        ids = Array.from(new Set((ids || []).map(Number).filter(Boolean)));
        const payload = ids.length ? { product_ids: ids } : {};
        return vmoApiFetch('vmo-manager/v1/store/checkout', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        }).catch(function(err) {
            console.warn('VMO checkout REST fallback:', err);
            return vmoEmailAdminAjax('vmo_get_store_checkout', payload);
        });
    }

    function vmoCheckoutUrlFromData(data, ids, allowStoreFallback) {
        ids = Array.from(new Set((ids || []).map(Number).filter(Boolean)));
        const mode = String((data && data.mode) || '');
        const checkoutUrl = data && (data.checkout_url || data.store_url) ? String(data.checkout_url || data.store_url) : '';
        if (!checkoutUrl) return '';
        if (!allowStoreFallback && ids.length > 1 && mode.indexOf('store_multi_fallback') !== -1) {
            return '';
        }
        return checkoutUrl;
    }

    function vmoCheckoutForProductIds(ids) {
        ids = Array.from(new Set((ids || []).map(Number).filter(Boolean)));
        if (!ids.length) return Promise.resolve('');
        return vmoStoreCheckoutFetch(ids).then(data => {
            return data && data.success ? vmoCheckoutUrlFromData(data, ids, false) : '';
        }).catch(err => {
            console.warn('VMO checkout URL fallback:', err);
            return '';
        });
    }

    function vmoProductWithCheckout(product, checkoutUrl) {
        const copy = Object.assign({}, product || {});
        if (checkoutUrl) copy.checkout_url = checkoutUrl;
        return copy;
    }

    function vmoProductCardHtml(p, includeSecondary) {
        const name = vmoEscapeHtml(p.name || 'Product');
        const img = p.image_url ? `<img src="${vmoEscapeHtml(p.image_url)}" alt="${name}" width="560" style="width:100%; max-width:560px; height:auto; border-radius:12px; display:block; margin:0 auto 16px;" />` : '';
        const price = p.price_display ? vmoEscapeHtml(p.price_display) : '';
        const desc = p.description ? vmoEscapeHtml(p.description) : '';
        const href = p.checkout_url || p.buy_url || p.store_url || '#';
        const secondary = includeSecondary && p.store_url ? `<p style="margin:12px 0 0;"><a href="${vmoEscapeHtml(p.store_url)}" style="color:#2271b1; text-decoration:none;">See more options</a></p>` : '';
        return `
<table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="margin:20px 0;background:#ffffff;border:1px solid #e5e7eb;border-radius:14px;">
  <tr>
    <td align="center" style="padding:22px;font-family:Arial,sans-serif;color:#222;">
      ${img}
      <h2 style="margin:0 0 8px;font-size:24px;line-height:1.25;">${name}</h2>
      ${desc ? `<p style="margin:0 0 12px;color:#555;line-height:1.6;">${desc}</p>` : ''}
      ${price ? `<p style="margin:0 0 16px;font-size:18px;font-weight:700;">${price}</p>` : ''}
      <a href="${vmoEscapeHtml(href)}" style="background:#2271b1;color:#fff;padding:13px 22px;text-decoration:none;border-radius:8px;font-weight:700;display:inline-block;">Buy Now</a>
      ${secondary}
    </td>
  </tr>
</table>`;
    }

    window.vmoInsertSingleProductCard = function(id) {
        const product = vmoFindCachedProduct(id);
        if (!product) {
            vmoToast('Product details are not loaded. Search again and retry.', 'error');
            return;
        }
        window.__vmoSelectedEmailProductIds = [Number(id)];
        vmoCheckoutForProductIds([Number(id)]).then(url => {
            vmoAppendToCompose(vmoProductCardHtml(vmoProductWithCheckout(product, url), false), 'Product card inserted.');
        });
    };

    window.vmoInsertSingleBuyButton = function(id) {
        const product = vmoFindCachedProduct(id);
        if (!product) {
            vmoToast('Product details are not loaded. Search again and retry.', 'error');
            return;
        }
        window.__vmoSelectedEmailProductIds = [Number(id)];
        vmoStoreCheckoutFetch([Number(id)]).then(data => {
            const url = (data && data.success && vmoCheckoutUrlFromData(data, [Number(id)], true)) || product.checkout_url || product.buy_url || product.store_url || '#';
            vmoAppendToCompose(`<div style="text-align:center; margin:24px 0;"><a href="${vmoEscapeHtml(url)}" style="background:#2271b1;color:#fff;padding:13px 22px;text-decoration:none;border-radius:8px;font-weight:700;display:inline-block;">Buy Now</a></div>`, 'Buy button inserted.');
        }).catch(err => {
            console.error('Buy button checkout error:', err);
            vmoToast('VMO could not reach the checkout service. Please refresh or check REST routing.', 'error');
        });
    };

    window.vmoInsertProductUpsellBlock = function(id) {
        const product = vmoFindCachedProduct(id);
        if (!product) {
            vmoToast('Product details are not loaded. Search again and retry.', 'error');
            return;
        }
        window.__vmoSelectedEmailProductIds = [Number(id)];
        vmoCheckoutForProductIds([Number(id)]).then(url => {
            vmoAppendToCompose(vmoProductCardHtml(vmoProductWithCheckout(product, url), true), 'Product and upsell block inserted.');
        });
    };

    window.vmoInsertCheckoutLink = function() {
        let ids = Array.from(document.querySelectorAll('.vmo-product-pick:checked')).map(c => Number(c.value)).filter(Boolean);
        if (!ids.length) {
            ids = Array.isArray(window.__vmoSelectedEmailProductIds) ? window.__vmoSelectedEmailProductIds.map(Number).filter(Boolean) : [];
        }
        if (ids.length) window.__vmoSelectedEmailProductIds = ids;
        vmoStoreCheckoutFetch(ids)
        .then(data => {
            const url = (data && data.success && vmoCheckoutUrlFromData(data, ids, true)) ? vmoCheckoutUrlFromData(data, ids, true) : (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 current = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : (document.getElementById('vmo-compose-body').value || '');
            vmoSetComposeBody(current + '\n' + html + '\n');
            vmoSwitchComposeTab('preview');
            vmoToast('Checkout button inserted.', 'success');
        })
        .catch(err => {
            console.error('Checkout link error:', err);
            vmoToast('VMO could not reach the checkout service. Please refresh or check REST routing.', 'error');
        });
    };

    window.vmoEmailVariants = window.vmoEmailVariants || [];
    window.__vmoEmailActiveVariantId = window.__vmoEmailActiveVariantId || null;

    function vmoEmailVariantBody(variant) {
        if (!variant) return '';
        return variant.body_html || variant.html || variant.body_text || variant.plain_text || variant.message || variant.body || '';
    }

    function vmoEmailVariantPlain(variant) {
        if (!variant) return '';
        return variant.body_text || variant.plain_text || vmoEmailDraftText(vmoEmailVariantBody(variant));
    }

    function vmoEmailDraftText(value) {
        const raw = String(value || '');
        if (!raw) return '';
        const div = document.createElement('div');
        div.innerHTML = raw;
        return (div.textContent || div.innerText || raw.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim();
    }

    function vmoEmailHasDraftContent(value) {
        return vmoEmailDraftText(value).length > 8;
    }

    function vmoEmailLooksLikeRefineInstruction(value) {
        const text = String(value || '').toLowerCase();
        const refineOnly = /\b(refine|revise|rewrite|improve|shorter|persuasive|luxury|urgent|friendlier|make it|polish|tighten)\b/.test(text);
        const generationRequest = /\b(write|draft|compose|create|generate|build)\b/.test(text);
        return refineOnly && !generationRequest;
    }

    function vmoEmailShouldBlockDraftGeneration(payload) {
        const state = payload && payload.draft_state ? payload.draft_state : {};
        const hasExistingDraft = !!state.has_compose_body || !!state.has_generated_variants;
        return !hasExistingDraft && !window.__vmoEmailLastStrategy && vmoEmailLooksLikeRefineInstruction((payload && payload.intent) || '');
    }

    function vmoEmailDraftSignature(value) {
        return vmoEmailDraftText(value).toLowerCase().slice(0, 4000);
    }

    function vmoEmailComposeMatchesVariant(variant) {
        const composeBody = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : ((document.getElementById('vmo-compose-body') || {}).value || '');
        const variantBody = vmoEmailVariantBody(variant);
        return vmoEmailDraftSignature(composeBody) !== '' && vmoEmailDraftSignature(composeBody) === vmoEmailDraftSignature(variantBody);
    }

    function vmoEmailActiveVariant() {
        const variants = Array.isArray(window.vmoEmailVariants) ? window.vmoEmailVariants : [];
        return variants.find(v => String(v.id) === String(window.__vmoEmailActiveVariantId)) || variants[0] || null;
    }

    function vmoEmailNeedsDraftMessage(instruction) {
        const action = String(instruction || 'refine this email').trim().toLowerCase();
        return 'I need an actual draft before I can ' + action + '. Paste or select the email you want revised, or give me the audience, goal, offer, and CTA so I can draft from a real brief.';
    }

    function vmoEmailAskForDraftContext(instruction) {
        const prompt = document.getElementById('vmo-email-ai-prompt');
        vmoEmailChatAppend(vmoEmailNeedsDraftMessage(instruction), 'assistant', {
            needs_context: true,
            follow_up_questions: [
                'Who is the email going to?',
                'What should the reader do after reading?',
                'Paste the current draft here if one already exists.'
            ],
            recommended_next_steps: [
                'Paste or insert the draft to revise.',
                'Or describe the audience, offer, and CTA, then choose Draft From Plan.'
            ]
        });
        if (prompt) prompt.focus();
        if (typeof vmoToast === 'function') vmoToast('Add a draft or email brief first.', 'error');
    }

    function vmoAddEmailVariant(payload) {
        if (!payload || !payload.success) return null;
        const variant = Object.assign({}, payload, {
            id: payload.id || ('variant_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7)),
            created_at: payload.created_at || new Date().toISOString()
        });
        window.vmoEmailVariants.unshift(variant);
        window.vmoEmailVariants = window.vmoEmailVariants.slice(0, 12);
        window.__vmoEmailActiveVariantId = variant.id;
        vmoRenderEmailVariants();
        return variant;
    }

    function vmoRenderEmailVariants() {
        const list = document.getElementById('vmo-email-variants-list');
        if (!list) return;
        const variants = Array.isArray(window.vmoEmailVariants) ? window.vmoEmailVariants : [];
        if (!variants.length) {
            list.innerHTML = '<div style="color:var(--muted); text-align:center; padding:40px 20px;">Drafts will appear here as you chat. Click <strong>Use This Email</strong> on any draft to load it into the editable compose body.</div>';
            return;
        }
        list.innerHTML = variants.map((v, idx) => {
            const subject = vmoEscapeHtml(v.subject || 'Draft Email');
            const preheader = vmoEscapeHtml(v.preheader || '');
            const themeLabel = vmoEscapeHtml((v.theme || v.theme_hint || 'professional').replace(/_/g, ' '));
            const saved = (v.draft_id || v.saved) ? '<span style="color:#8ee8b0; font-size:11px; font-weight:700; margin-left:8px;">Saved</span>' : '';
            const bodyHtml = vmoEmailVariantBody(v) || '<p style="color:#666;font-family:sans-serif;">(empty draft)</p>';
            const srcdoc = '<!doctype html><html><head><meta charset="utf-8"><base target="_blank"><style>body{margin:0;padding:16px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;color:#111;background:#fff;font-size:14px;line-height:1.5;}img{max-width:100%;height:auto;}a{color:#0d6efd;}</style></head><body>' + (bodyHtml || '') + '</body></html>';
            const safeSrcdoc = srcdoc.replace(/"/g, '&quot;');
            return `
                <div class="vmo-card" style="background:rgba(255,255,255,.03); border:1px solid var(--border); padding:12px;">
                    <div style="display:flex; justify-content:space-between; gap:10px; align-items:flex-start; margin-bottom:8px;">
                        <div style="min-width:0;">
                            <div style="font-size:11px; text-transform:uppercase; color:var(--cyan-soft); font-weight:700; letter-spacing:.5px;">Draft ${idx + 1} - ${themeLabel}${saved}</div>
                            <div style="font-size:15px; font-weight:700; margin-top:4px; color:#fff;">${subject}</div>
                            ${preheader ? `<div style="color:var(--muted); font-size:12px; margin-top:2px;">${preheader}</div>` : ''}
                        </div>
                    </div>
                    <iframe sandbox="allow-same-origin" srcdoc="${safeSrcdoc}" style="width:100%; height:240px; border:1px solid var(--border); border-radius:8px; background:#fff;"></iframe>
                    <div style="display:flex; gap:6px; flex-wrap:wrap; margin-top:10px;">
                        <button class="vmo-btn vmo-btn-primary vmo-btn-small" onclick="vmoUseEmailVariant('${v.id}')">Use This Email</button>
                        <button class="vmo-btn-small" onclick="vmoRefineEmailVariant('${v.id}')">Refine</button>
                        <button class="vmo-btn-small" onclick="vmoEmailSaveVariantDraft('${v.id}')">Save Draft</button>
                        <button class="vmo-btn-small" onclick="vmoDuplicateEmailVariant('${v.id}')">Duplicate</button>
                        <button class="vmo-btn-small" onclick="vmoDeleteEmailVariant('${v.id}')">Remove</button>
                    </div>
                </div>`;
        }).join('');
    }

    function vmoFindEmailVariant(id) {
        return (window.vmoEmailVariants || []).find(v => String(v.id) === String(id));
    }

    function vmoEmailSelectedProductIds() {
        const checked = Array.from(document.querySelectorAll('.vmo-product-pick:checked')).map(c => Number(c.value)).filter(Boolean);
        const remembered = Array.isArray(window.__vmoSelectedEmailProductIds) ? window.__vmoSelectedEmailProductIds.map(Number).filter(Boolean) : [];
        return Array.from(new Set(checked.concat(remembered)));
    }

    function vmoEmailPayloadBase() {
        const body = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : ((document.getElementById('vmo-compose-body') || {}).value || '');
        const prompt = (document.getElementById('vmo-email-ai-prompt') || {}).value || (document.getElementById('vmo-compose-intent') || {}).value || '';
        return {
            intent: prompt,
            message: prompt,
            theme: (document.getElementById('vmo-compose-theme') || {}).value || 'modern',
            template_type: (document.getElementById('vmo-compose-template') || {}).value || 'freeform',
            subject: (document.getElementById('vmo-compose-subject') || {}).value || '',
            body: body,
            html: body,
            to: (document.getElementById('vmo-compose-to') || {}).value || '',
            from_email: (document.getElementById('vmo-compose-from') || {}).value || '',
            cc: (document.getElementById('vmo-compose-cc') || {}).value || '',
            bcc: (document.getElementById('vmo-compose-bcc') || {}).value || '',
            product_ids: vmoEmailSelectedProductIds(),
            strategy_context: window.__vmoEmailLastStrategy || {},
            conversation_history: Array.isArray(window.__vmoEmailAiConversation) ? window.__vmoEmailAiConversation.slice(-8) : [],
            agent_profile: 'vmo-email-gpt-5.5-nano',
            agent_name: 'VMO Email GPT 5.5 Nano Agent',
            model_hint: 'gpt-5.5-nano',
            draft_state: {
                has_compose_body: vmoEmailHasDraftContent(body),
                has_generated_variants: Array.isArray(window.vmoEmailVariants) && window.vmoEmailVariants.length > 0,
                active_variant_id: window.__vmoEmailActiveVariantId || '',
                current_body_preview: vmoEmailDraftText(body).slice(0, 700)
            }
        };
    }

    window.vmoOpenEmailAssistant = function() {
        const modal = document.getElementById('vmo-email-ai-modal');
        const prompt = document.getElementById('vmo-email-ai-prompt');
        const composeIntent = document.getElementById('vmo-compose-intent');
        if (prompt && composeIntent && composeIntent.value && !prompt.value) prompt.value = composeIntent.value;
        if (modal) modal.classList.add('vmo-show');
        vmoRenderEmailVariants();
    };

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

    function vmoEmailChatListHtml(label, items, asButtons) {
        if (!Array.isArray(items) || !items.length) return '';
        const clean = items.map(item => String(item || '').trim()).filter(Boolean).slice(0, 6);
        if (!clean.length) return '';
        const body = asButtons
            ? '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:6px;">' + clean.map(item => '<button type="button" class="vmo-btn-small" data-vmo-email-question="' + vmoEscapeHtml(item) + '" onclick="vmoEmailAskPreset(this.getAttribute(\'data-vmo-email-question\'))">' + vmoEscapeHtml(item) + '</button>').join('') + '</div>'
            : '<ul style="margin:6px 0 0 18px;padding:0;display:grid;gap:4px;">' + clean.map(item => '<li>' + vmoEscapeHtml(item) + '</li>').join('') + '</ul>';
        return '<div style="margin-top:10px;"><div style="font-size:11px;text-transform:uppercase;color:var(--cyan-soft);font-weight:800;letter-spacing:0;">' + vmoEscapeHtml(label) + '</div>' + body + '</div>';
    }

    function vmoEmailRenderAssistantMessage(div, text, meta) {
        const data = meta || {};
        let html = '<div style="white-space:pre-wrap;line-height:1.5;">' + vmoEscapeHtml(text || '') + '</div>';
        if (data.ready_to_draft && data.draft && data.draft.subject) {
            html += '<div style="margin-top:8px;font-size:12px;color:#8ee8b0;font-weight:700;">Draft created -> see right panel</div>';
        }
        html += vmoEmailChatListHtml('Quick replies', data.follow_up_questions || [], true);
        div.innerHTML = html;
    }

    function vmoEmailChatAppend(text, who, meta) {
        const log = document.getElementById('vmo-email-ai-chat-log');
        if (!log) return;
        const div = document.createElement('div');
        div.style.cssText = (who === 'user')
            ? 'align-self:flex-end;max-width:85%;background:rgba(15,225,255,.13);padding:10px 12px;border-radius:10px;'
            : 'align-self:flex-start;max-width:90%;background:rgba(255,255,255,.05);padding:10px 12px;border-radius:10px;';
        if (who === 'assistant' && meta) {
            vmoEmailRenderAssistantMessage(div, text, meta);
        } else {
            div.textContent = text;
        }
        log.appendChild(div);
        log.scrollTop = log.scrollHeight;
        window.__vmoEmailAiConversation = window.__vmoEmailAiConversation || [];
        window.__vmoEmailAiConversation.push({ role: who === 'assistant' ? 'assistant' : 'user', content: String(text || '') });
        window.__vmoEmailAiConversation = window.__vmoEmailAiConversation.slice(-16);
        return div;
    }

    window.vmoEmailAskPreset = function(text) {
        const prompt = document.getElementById('vmo-email-ai-prompt');
        if (prompt) prompt.value = text || '';
        window.vmoEmailAiChat();
    }

    let vmoEmailAiRecognition = null;
    let vmoEmailAiListening = false;

    window.vmoToggleEmailAiVoice = function() {
        const prompt = document.getElementById('vmo-email-ai-prompt');
        const btn = document.getElementById('vmo-email-ai-voice-btn');
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (!prompt || !SpeechRecognition) {
            vmoToast('Voice input is not available in this browser.', 'error');
            return;
        }

        if (vmoEmailAiListening && vmoEmailAiRecognition) {
            try { vmoEmailAiRecognition.stop(); } catch (_) {}
            return;
        }

        if (window.VMOAudioCoordinator && typeof window.VMOAudioCoordinator.requestMic === 'function') {
            const ok = window.VMOAudioCoordinator.requestMic('email-assistant', { bargeIn: true });
            if (!ok) {
                vmoToast('Microphone is currently in use.', 'error');
                return;
            }
        }

        vmoEmailAiRecognition = new SpeechRecognition();
        vmoEmailAiRecognition.lang = document.documentElement.lang || 'en-US';
        vmoEmailAiRecognition.interimResults = true;
        vmoEmailAiRecognition.continuous = false;
        let baseText = prompt.value || '';
        let finalText = '';

        vmoEmailAiRecognition.onstart = function() {
            vmoEmailAiListening = true;
            if (btn) btn.textContent = 'Listening...';
        };
        vmoEmailAiRecognition.onresult = function(event) {
            let interim = '';
            for (let i = event.resultIndex; i < event.results.length; i++) {
                const transcript = event.results[i][0].transcript || '';
                if (event.results[i].isFinal) finalText += transcript + ' ';
                else interim += transcript;
            }
            prompt.value = (baseText ? baseText.trim() + ' ' : '') + (finalText + interim).trim();
        };
        vmoEmailAiRecognition.onerror = function() {
            vmoToast('Voice input stopped. Please try again.', 'error');
        };
        vmoEmailAiRecognition.onend = function() {
            vmoEmailAiListening = false;
            if (btn) btn.textContent = 'Voice';
            if (window.VMOAudioCoordinator && typeof window.VMOAudioCoordinator.releaseMic === 'function') {
                window.VMOAudioCoordinator.releaseMic('email-assistant');
            }
        };
        vmoEmailAiRecognition.start();
    };

    window.addEventListener('vmo:mic-revoke', function(event) {
        const detail = event && event.detail ? event.detail : {};
        if (detail.from === 'email-assistant' && vmoEmailAiRecognition) {
            try { vmoEmailAiRecognition.stop(); } catch (_) {}
        }
    });

    window.vmoEmailAiAddDraftFromEnvelope = function(draft) {
        if (!draft || (!draft.body_html && !draft.body_text && !draft.html)) return null;
        const id = draft.id || ('draft_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7));
        const variant = {
            id: id,
            success: true,
            subject: draft.subject || 'Draft Email',
            preheader: draft.preheader || '',
            body_html: draft.body_html || draft.html || '',
            body_text: draft.body_text || draft.plain_text || '',
            html: draft.body_html || draft.html || '',
            plain_text: draft.body_text || draft.plain_text || '',
            cta: draft.cta || {},
            theme: draft.theme || draft.theme_hint || 'modern',
            theme_hint: draft.theme_hint || '',
            template_type: draft.template_type || '',
            created_at: draft.created_at || new Date().toISOString()
        };
        window.vmoEmailVariants = Array.isArray(window.vmoEmailVariants) ? window.vmoEmailVariants : [];
        window.vmoEmailVariants.unshift(variant);
        window.vmoEmailVariants = window.vmoEmailVariants.slice(0, 12);
        window.__vmoEmailActiveVariantId = variant.id;
        vmoRenderEmailVariants();
        return variant;
    };

    window.vmoEmailAiChat = function() {
        const promptEl = document.getElementById('vmo-email-ai-prompt');
        const prompt = (promptEl || {}).value || '';
        if (!prompt.trim()) {
            if (typeof vmoToast === 'function') vmoToast('Type a message for the VMO Email Agent.', 'error');
            if (promptEl) promptEl.focus();
            return;
        }
        vmoEmailChatAppend(prompt, 'user');
        if (promptEl) promptEl.value = '';
        const thinking = vmoEmailChatAppend('Thinking...', 'assistant');
        const payload = vmoEmailPayloadBase();
        payload.message = prompt;
        payload.intent = prompt;
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-chat', payload).then(data => {
            if (thinking && thinking.parentNode) thinking.parentNode.removeChild(thinking);
            if (data && data.recommended_theme) {
                const themeSel = document.getElementById('vmo-compose-theme');
                if (themeSel) themeSel.value = data.recommended_theme;
            }
            if (data && data.recommended_template_type) {
                const templateSel = document.getElementById('vmo-compose-template');
                if (templateSel) templateSel.value = data.recommended_template_type;
            }
            window.__vmoEmailLastStrategy = data || null;
            const reply = (data && data.reply) ? data.reply : "Tell me a bit more about who this is for and what you want them to do.";
            vmoEmailChatAppend(reply, 'assistant', data || {});
            if (data && data.ready_to_draft && data.draft) {
                window.vmoEmailAiAddDraftFromEnvelope(data.draft);
                if (typeof vmoToast === 'function') vmoToast('New draft ready - check the right panel.', 'success');
            }
        }).catch(err => {
            if (thinking && thinking.parentNode) thinking.parentNode.removeChild(thinking);
            vmoHandleEmailAiError(err, 'Email AI chat error');
        });
    };

    window.vmoEmailAiGenerate = function() {
        const payload = vmoEmailPayloadBase();
        if (!payload.intent.trim()) {
            vmoToast('Tell VMO what kind of email you want to send.', 'error');
            return;
        }
        if (vmoEmailShouldBlockDraftGeneration(payload)) {
            vmoEmailAskForDraftContext(payload.intent);
            return;
        }
        vmoEmailChatAppend(payload.intent, 'user');
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-compose', payload).then(data => {
            const variant = vmoAddEmailVariant(data);
            if (variant) {
                vmoEmailChatAppend('I created a structured email with subject, preheader, plain text, and HTML. You can preview or insert it.', 'assistant');
                vmoToast('Email variant generated.', 'success');
            }
        }).catch(err => {
            vmoHandleEmailAiError(err, 'Email AI compose error');
        });
    };

    window.vmoEmailAiGenerateVariants = function() {
        const payload = vmoEmailPayloadBase();
        if (!payload.intent.trim()) {
            vmoToast('Tell VMO what kind of email you want to send.', 'error');
            return;
        }
        if (vmoEmailShouldBlockDraftGeneration(payload)) {
            vmoEmailAskForDraftContext(payload.intent);
            return;
        }
        payload.count = 3;
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-variants', payload).then(data => {
            const variants = Array.isArray(data.variants) ? data.variants : [data];
            variants.forEach(vmoAddEmailVariant);
            vmoToast('Email variants generated.', 'success');
        }).catch(err => {
            vmoHandleEmailAiError(err, 'Email AI variants error');
        });
    };

    window.vmoUseEmailVariant = function(id) {
        const variant = vmoFindEmailVariant(id);
        if (!variant) return;
        window.__vmoEmailActiveVariantId = variant.id;
        const subject = document.getElementById('vmo-compose-subject');
        if (subject) subject.value = variant.subject || '';
        const bodyHtml = vmoEmailVariantBody(variant) || '';
        if (typeof vmoSetComposeBody === 'function') vmoSetComposeBody(bodyHtml);
        // Make sure both editor surfaces stay editable for direct user edits.
        const visual = document.getElementById('vmo-compose-visual-editor');
        if (visual) {
            visual.setAttribute('contenteditable', 'true');
            visual.removeAttribute('disabled');
            visual.style.pointerEvents = 'auto';
        }
        const bodyTa = document.getElementById('vmo-compose-body');
        if (bodyTa) bodyTa.removeAttribute('readonly');
        if (variant.theme && document.getElementById('vmo-compose-theme')) document.getElementById('vmo-compose-theme').value = variant.theme;
        if (variant.template_type && document.getElementById('vmo-compose-template')) document.getElementById('vmo-compose-template').value = variant.template_type;
        // Stash CTA + preheader on the compose modal for later send/save.
        try {
            const composeModal = document.getElementById('vmo-compose-modal') || document.body;
            if (composeModal) {
                if (variant.preheader) composeModal.setAttribute('data-vmo-preheader', variant.preheader);
                if (variant.cta && variant.cta.label) composeModal.setAttribute('data-vmo-cta-label', variant.cta.label);
                if (variant.cta && variant.cta.href) composeModal.setAttribute('data-vmo-cta-href', variant.cta.href);
            }
        } catch (_) {}
        vmoCloseEmailAssistant();
        if (typeof vmoSwitchComposeTab === 'function') vmoSwitchComposeTab('write');
        if (typeof vmoToast === 'function') vmoToast('Draft inserted - edit anything before sending.', 'success');
    };

    window.vmoPreviewEmailVariant = function(id) {
        const variant = vmoFindEmailVariant(id);
        if (!variant) return;
        window.__vmoEmailActiveVariantId = variant.id;
        const subject = document.getElementById('vmo-compose-subject');
        const previousSubject = subject ? subject.value : '';
        const previousBody = vmoGetComposeBody();
        if (subject) subject.value = variant.subject || '';
        vmoSetComposeBody(variant.html || variant.plain_text || '');
        vmoSwitchComposeTab('preview');
        vmoToast('Previewing selected variant. Use This Email to keep it.', 'success');
        setTimeout(function() {
            if (subject) subject.value = previousSubject;
            vmoSetComposeBody(previousBody);
        }, 250);
    };

    window.vmoRefineEmailVariant = function(id) {
        const variant = vmoFindEmailVariant(id);
        if (!variant) return;
        const prompt = (document.getElementById('vmo-email-ai-prompt') || {}).value || 'Refine this email';
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-refine', Object.assign(vmoEmailPayloadBase(), {
                instructions: prompt,
                subject: variant.subject || '',
                html: vmoEmailVariantBody(variant),
                template_type: variant.template_type || vmoEmailPayloadBase().template_type,
                theme: variant.theme || vmoEmailPayloadBase().theme
            })).then(data => {
            const refined = vmoAddEmailVariant(data);
            if (refined) vmoEmailChatAppend('I refined that draft and added the new version to the generated options.', 'assistant');
            vmoToast('Refined variant generated.', 'success');
        }).catch(err => {
            vmoHandleEmailAiError(err, 'Email refine error');
        });
    };

    window.vmoEmailSaveVariantDraft = function(id) {
        const variant = vmoFindEmailVariant(id);
        if (!variant) return Promise.resolve({ success: false });
        const content = vmoEmailVariantBody(variant);
        if (!String(variant.subject || '').trim() && !vmoEmailHasDraftContent(content)) {
            vmoToast('This generated option is empty, so there is nothing to save.', 'error');
            return Promise.resolve({ success: false });
        }
        const base = (typeof window.vmoBuildComposeDraftPayload === 'function') ? window.vmoBuildComposeDraftPayload() : {};
        const payload = Object.assign({}, base, {
            subject: variant.subject || base.subject || 'Untitled draft',
            message: content,
            is_ai_generated: true,
            preheader: variant.preheader || ''
        });
        const saver = (typeof window.vmoSaveEmailDraftPayload === 'function') ? window.vmoSaveEmailDraftPayload : null;
        if (!saver) {
            vmoSetComposeBody(content);
            const subject = document.getElementById('vmo-compose-subject');
            if (subject) subject.value = payload.subject;
            return vmoSaveDraft();
        }
        return saver(payload, { success: 'AI draft saved to Drafts', local: 'AI draft saved locally because VMO storage was unreachable' }).then(function(data) {
            variant.saved = true;
            if (data && data.draft_id) variant.draft_id = data.draft_id;
            vmoRenderEmailVariants();
            return data;
        });
    };

    window.vmoEmailSaveActiveDraft = function() {
        const variant = vmoEmailActiveVariant();
        if (variant) {
            return vmoEmailSaveVariantDraft(variant.id);
        }
        const payload = (typeof window.vmoBuildComposeDraftPayload === 'function') ? window.vmoBuildComposeDraftPayload() : null;
        const subjectValue = (document.getElementById('vmo-compose-subject') || {}).value || '';
        if (payload && (String(subjectValue || '').trim() || vmoEmailHasDraftContent(payload.message))) {
            return vmoSaveDraft();
        }
        vmoEmailAskForDraftContext('save a draft');
        return Promise.resolve({ success: false });
    };

    window.vmoEmailQuickRefine = function(instruction) {
        const instructionText = String(instruction || '').trim() || 'Refine this email';
        const prompt = document.getElementById('vmo-email-ai-prompt');
        const first = (window.vmoEmailVariants || [])[0];
        if (first) {
            if (prompt) prompt.value = instructionText;
            vmoRefineEmailVariant(first.id);
            return;
        }
        const currentHtml = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : ((document.getElementById('vmo-compose-body') || {}).value || '');
        if (vmoEmailHasDraftContent(currentHtml)) {
            if (prompt) prompt.value = instructionText;
            vmoEmailChatAppend(instructionText, 'user');
            vmoEmailAiFetch('vmo-manager/v1/emails/ai-refine', Object.assign(vmoEmailPayloadBase(), {
                instructions: instructionText,
                subject: (document.getElementById('vmo-compose-subject') || {}).value || 'Draft Email',
                html: currentHtml
            })).then(data => {
                const refined = vmoAddEmailVariant(data);
                if (refined) vmoEmailChatAppend('I refined the current compose draft and added it as a generated option.', 'assistant');
                vmoToast('Current draft refined.', 'success');
            }).catch(err => {
                vmoHandleEmailAiError(err, 'Email quick refine error');
            });
            return;
        }
        vmoEmailAskForDraftContext(instructionText);
    };

    window.vmoDuplicateEmailVariant = function(id) {
        const variant = vmoFindEmailVariant(id);
        if (!variant) return;
        vmoAddEmailVariant(Object.assign({}, variant, { id: null, created_at: new Date().toISOString() }));
        vmoToast('Variant duplicated.', 'success');
    };

    window.vmoDeleteEmailVariant = function(id) {
        window.vmoEmailVariants = (window.vmoEmailVariants || []).filter(v => String(v.id) !== String(id));
        if (String(window.__vmoEmailActiveVariantId) === String(id)) window.__vmoEmailActiveVariantId = null;
        vmoRenderEmailVariants();
        vmoToast('Generated draft removed.', 'success');
    };

    window.vmoEmailClearGeneratedDrafts = function(clearCompose) {
        const variants = Array.isArray(window.vmoEmailVariants) ? window.vmoEmailVariants.slice() : [];
        const composeMatchesGenerated = variants.some(vmoEmailComposeMatchesVariant);
        window.vmoEmailVariants = [];
        window.__vmoEmailActiveVariantId = null;
        vmoRenderEmailVariants();
        if (clearCompose === true || composeMatchesGenerated) {
            const subject = document.getElementById('vmo-compose-subject');
            if (subject) subject.value = '';
            vmoSetComposeBody('');
            const preview = document.getElementById('vmo-email-preview-frame');
            if (preview) preview.innerHTML = '<p style="color:#777;text-align:center;margin-top:50px;">No content to preview.</p>';
        }
        vmoToast('Generated drafts cleared.', 'success');
    };

    window.vmoEmailResetAssistant = function() {
        const ok = !window.confirm || window.confirm('Reset the Email Assistant, generated drafts, prompt, and current compose draft?');
        if (!ok) return;
        window.vmoEmailVariants = [];
        window.__vmoEmailActiveVariantId = null;
        window.__vmoEmailLastStrategy = null;
        window.__vmoEmailAiConversation = [];
        const prompt = document.getElementById('vmo-email-ai-prompt');
        if (prompt) prompt.value = '';
        const intent = document.getElementById('vmo-compose-intent');
        if (intent) intent.value = '';
        const refine = document.getElementById('vmo-compose-refine');
        if (refine) refine.value = '';
        const subject = document.getElementById('vmo-compose-subject');
        if (subject) subject.value = '';
        vmoSetComposeBody('');
        const preview = document.getElementById('vmo-email-preview-frame');
        if (preview) preview.innerHTML = '<p style="color:#777;text-align:center;margin-top:50px;">No content to preview.</p>';
        const log = document.getElementById('vmo-email-ai-chat-log');
        if (log) log.innerHTML = '<div style="background:rgba(255,255,255,0.05); padding:12px; border-radius:10px; color:var(--ink);">Hi - I\'m your VMO Email Agent. Tell me who the email is going to and what you want them to do, and I\'ll draft it for you. Each draft I create appears on the right; pick one and I\'ll drop it into your editable compose body.</div>';
        vmoRenderEmailVariants();
        vmoToast('Email Assistant reset.', 'success');
    };

    window.vmoGenerateEmailContent = function() {
        const intentEl = document.getElementById('vmo-compose-intent');
        const promptEl = document.getElementById('vmo-email-ai-prompt');
        const intent = intentEl ? intentEl.value : '';
        if (promptEl && intent && !promptEl.value) promptEl.value = intent;
        if (!intent.trim()) {
            vmoOpenEmailAssistant();
            vmoToast('Tell VMO what kind of email you want to send.', 'error');
            return;
        }
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-compose', vmoEmailPayloadBase()).then(data => {
            const subject = document.getElementById('vmo-compose-subject');
            if (subject) subject.value = data.subject || 'Draft Email';
            vmoSetComposeBody(data.html || data.plain_text || '');
            vmoAddEmailVariant(data);
            vmoSwitchComposeTab('preview');
            vmoToast('Draft generated.', 'success');
        }).catch(err => {
            vmoHandleEmailAiError(err, 'Compose generate error');
        });
    };

    window.vmoRegenerateEmailVariant = function() {
        const refine = (document.getElementById('vmo-compose-refine') || {}).value || '';
        const currentHtml = vmoGetComposeBody();
        if (!refine.trim()) {
            vmoToast('Please enter a refinement prompt.', 'error');
            return;
        }
        if (!currentHtml.trim()) {
            vmoToast('Generate a draft first, then refine.', 'error');
            return;
        }
        vmoEmailAiFetch('vmo-manager/v1/emails/ai-refine', Object.assign(vmoEmailPayloadBase(), {
                instructions: refine,
                subject: (document.getElementById('vmo-compose-subject') || {}).value || '',
                html: currentHtml
            })).then(data => {
            const subject = document.getElementById('vmo-compose-subject');
            if (subject) subject.value = data.subject || subject.value;
            vmoSetComposeBody(data.html || data.plain_text || '');
            vmoAddEmailVariant(data);
            vmoSwitchComposeTab('preview');
            vmoToast('Variant regenerated.', 'success');
        }).catch(err => {
            vmoHandleEmailAiError(err, 'Compose refine error');
        });
    };

    window.vmoSendEmail = function() {
        const to = document.getElementById('vmo-compose-to').value;
        const subject = document.getElementById('vmo-compose-subject').value;
        const body = (typeof vmoGetComposeBody === 'function') ? vmoGetComposeBody() : document.getElementById('vmo-compose-body').value;
        const schedule = document.getElementById('vmo-compose-schedule').value;
        const btn = (typeof event !== 'undefined' && event && event.target) ? event.target : null;

        // 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) {
            vmoShowEmailSetupNotice('send');
            return;
        }
        
        if (!to || !subject || !body) {
            vmoToast('Please fill in To, Subject, and Message.', 'error');
            return;
        }

        const originalText = btn ? btn.innerHTML : '';
        if (btn) {
            btn.innerHTML = schedule ? 'Scheduling...' : 'Sending...';
            btn.disabled = true;
        }

        let mailboxId = '';
        try {
            const composeSel = document.getElementById('vmo-compose-from');
            const selectedOption = composeSel && composeSel.selectedOptions && composeSel.selectedOptions[0] ? composeSel.selectedOptions[0] : null;
            mailboxId = selectedOption && selectedOption.dataset ? (selectedOption.dataset.mailboxId || selectedOption.getAttribute('data-mailbox-id') || '') : '';
        } catch (e) { mailboxId = ''; }
        if (!mailboxId) {
            try {
                const accountSel = document.querySelector('.vmo-account-selector');
                const selectedAccount = accountSel && accountSel.selectedOptions && accountSel.selectedOptions[0] ? accountSel.selectedOptions[0] : null;
                mailboxId = selectedAccount && selectedAccount.dataset ? (selectedAccount.dataset.mailboxId || selectedAccount.getAttribute('data-mailbox-id') || '') : '';
            } catch (e) { mailboxId = ''; }
        }

        const payload = {
            to: to,
            subject: subject,
            message: body,
            type: 'transactional',
            mailbox_id: mailboxId,
            cc: (document.getElementById('vmo-compose-cc') || {}).value || '',
            bcc: (document.getElementById('vmo-compose-bcc') || {}).value || ''
        };

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

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

        const attachments = typeof window.vmoGetComposeAttachments === 'function' ? window.vmoGetComposeAttachments() : [];
        let requestOptions;
        if (attachments.length) {
            const formData = new FormData();
            Object.keys(payload).forEach(function(key) {
                formData.append(key, payload[key] == null ? '' : payload[key]);
            });
            attachments.forEach(function(file) {
                formData.append('attachments[]', file, file.name || 'attachment');
            });
            requestOptions = {
                method: 'POST',
                body: formData
            };
        } else {
            requestOptions = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            };
        }

        vmoApiFetch('vmo-manager/v1/emails/send', requestOptions)
        .then(data => {
            if (data.success || data.sent) {
                vmoToast(schedule ? 'Email scheduled successfully.' : 'Email sent successfully.', 'success');
                vmoCloseComposeModal();
                if (typeof window.vmoClearComposeAttachments === 'function') {
                    window.vmoClearComposeAttachments();
                }
                // Clear fields
                document.getElementById('vmo-compose-to').value = '';
                const cc = document.getElementById('vmo-compose-cc');
                const bcc = document.getElementById('vmo-compose-bcc');
                if (cc) cc.value = '';
                if (bcc) bcc.value = '';
                document.getElementById('vmo-compose-subject').value = '';
                vmoSetComposeBody('');
                document.getElementById('vmo-compose-schedule').value = '';
            } else {
                vmoToast('Error sending email: ' + (data.message || 'Unknown error'), 'error');
            }
        })
        .catch(err => {
            console.error('Email send error:', err);
            vmoToast('Network error occurred while sending email.', 'error');
        })
        .finally(() => {
            if (btn) {
                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();
        if (typeof vmoSetEditorMode === 'function') {
            vmoSetEditorMode('visual');
        }

        // 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>

