(function($){
    // ─── VMO Admin-Page Media Tamer ─────────────────────────────────────────
    // Two distinct failure modes are guarded here:
    //   1) <audio> with a video/image src (e.g. an iPhone .mov picked as a
    //      ringtone). Browsers strip-and-loop the audio track → runaway loop.
    //      → Neutralize and remove the bad <audio> element entirely.
    //   2) <video> with autoplay+loop sitting on an admin page outside a
    //      designated live-preview surface (e.g. a hero clip Jarvis embedded
    //      that re-renders on every dashboard panel). Plays sound over phone
    //      calls and won't stop.
    //      → Strip autoplay/loop, force muted, expose controls so the user
    //        can still play manually. Element is NOT removed; the saved
    //        site markup remains intact for the live preview iframe.
    // The live preview iframe runs in its own document, so this script does
    // not reach the videos inside it; designated preview wrappers in the
    // parent document can opt-in via [data-vmo-allow-autoplay] or by living
    // inside .vmo-live-preview, .vmo-website-preview, #vmo-live-preview-iframe.
    // [VMO_ADMIN_MEDIA_TAMER]
    (function () {
        var BAD_AUDIO_SRC_RE = /\.(mov|mp4|m4v|webm|mkv|avi|3gp|wmv|flv|jpg|jpeg|png|gif|webp|bmp|svg|pdf|heic)(\?|#|$)/i;
        var PREVIEW_SELECTOR = [
            '[data-vmo-allow-autoplay]',
            '.vmo-live-preview',
            '.vmo-website-preview',
            '#vmo-live-preview-iframe',
            '#vmo-website-preview',
            '.vmo-preview-frame',
            'iframe'
        ].join(',');
        function srcOf(el) {
            try { return el.currentSrc || el.src || (el.querySelector && el.querySelector('source') && el.querySelector('source').src) || ''; }
            catch (_) { return ''; }
        }
        function isInsidePreview(el) {
            try { return !!(el.closest && el.closest(PREVIEW_SELECTOR)); }
            catch (_) { return false; }
        }
        function neutralizeBadAudio(el) {
            try {
                var s = srcOf(el);
                if (!s || !BAD_AUDIO_SRC_RE.test(s)) return false;
                el.pause && el.pause();
                el.muted = true;
                el.autoplay = false;
                el.loop = false;
                try { el.removeAttribute('src'); } catch (_) {}
                try { (el.querySelectorAll ? el.querySelectorAll('source') : []).forEach(function (n) { n.remove(); }); } catch (_) {}
                try { el.load && el.load(); } catch (_) {}
                try { el.parentNode && el.parentNode.removeChild(el); } catch (_) {}
                try { console.warn('[VMO] Removed <audio> with non-audio src:', s); } catch (_) {}
                return true;
            } catch (_) { return false; }
        }
        function tameVideo(el) {
            // Inside the designated live-preview surface, leave it alone.
            if (isInsidePreview(el)) return;
            try {
                var hadAutoplay = el.hasAttribute('autoplay') || el.autoplay;
                var hadLoop = el.hasAttribute('loop') || el.loop;
                if (!hadAutoplay && !hadLoop) {
                    // Still force muted on any admin-page video that ends up playing,
                    // so phone calls aren't drowned out.
                    if (!el.muted) { el.muted = true; }
                    return;
                }
                el.pause && el.pause();
                el.autoplay = false;
                el.loop = false;
                el.muted = true;
                try { el.removeAttribute('autoplay'); } catch (_) {}
                try { el.removeAttribute('loop'); } catch (_) {}
                if (!el.controls) { el.controls = true; }
                try { console.info('[VMO] Tamed admin-page <video> (no autoplay/loop):', srcOf(el)); } catch (_) {}
            } catch (_) {}
        }
        function inspect(el) {
            try {
                if (!el || !el.tagName) return;
                var tag = el.tagName.toLowerCase();
                if (tag === 'audio') { neutralizeBadAudio(el); return; }
                if (tag === 'video') { tameVideo(el); return; }
            } catch (_) {}
        }
        function sweep(root) {
            try { (root || document).querySelectorAll('audio, video').forEach(inspect); }
            catch (_) {}
        }
        // Initial sweep + periodic re-sweep for the first 10 seconds (covers async injects).
        sweep(document);
        var n = 0, iv = setInterval(function () { sweep(document); if (++n > 20) clearInterval(iv); }, 500);
        // Live sweep: anything newly inserted is checked instantly.
        try {
            new MutationObserver(function (muts) {
                for (var i = 0; i < muts.length; i++) {
                    var m = muts[i];
                    for (var j = 0; j < m.addedNodes.length; j++) {
                        var node = m.addedNodes[j];
                        if (node && node.nodeType === 1) {
                            if (node.matches && node.matches('audio,video')) inspect(node);
                            else if (node.querySelectorAll) sweep(node);
                        }
                    }
                }
            }).observe(document.documentElement, { childList: true, subtree: true });
        } catch (_) {}
    })();

    $(function(){
        // Always bind Business Wizard trigger (even if ajax config hasn't been localized yet).
        const wizardBtn = document.getElementById('vmo-business-wizard-btn');
        if (wizardBtn && !wizardBtn.dataset.vmoInitWizardBound) {
            wizardBtn.dataset.vmoInitWizardBound = 'true';
            // Capture phase so we can prefer the current consultation launcher even if older scripts bind too.
            // Only block other handlers when the launch succeeds.
            wizardBtn.addEventListener('click', (e) => {
                let launched = false;

                // 1) Preferred: global launcher (defined by vmo-intelligent-consultation.js)
                if (typeof window.launchBusinessWizard === 'function') {
                    try {
                        const res = window.launchBusinessWizard();
                        launched = (res !== false);
                    } catch (_) {
                        launched = false;
                    }
                }

                // 2) If an instance already exists, use it
                if (!launched && window.vmoConsultation && typeof window.vmoConsultation.openBusinessWizard === 'function') {
                    try {
                        const res = window.vmoConsultation.openBusinessWizard();
                        launched = (res !== false);
                    } catch (_) {
                        launched = false;
                    }
                }

                // 3) If class exists, instantiate and open
                if (!launched && window.VMOIntelligentConsultation?.prototype?.openBusinessWizard) {
                    try {
                        const res = (new window.VMOIntelligentConsultation()).openBusinessWizard();
                        launched = (res !== false);
                    } catch (_) {
                        launched = false;
                    }
                }

                if (launched) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
                }
            }, true);
        }

        // Consultation status chip update (runs when ajax config is available).
        const updateConsultationStatus = (ajaxUrl, nonce) => {
            if (!ajaxUrl || !nonce) return;
            $.post(ajaxUrl, { action:'vmo_get_consultation_status', security: nonce })
                .done(res=>{
                    const chip = document.querySelector('#vmo-consultation-status .vmo-chip');
                    if (!chip) return;
                    if (res.success && res.data && res.data.ready) {
                        chip.dataset.ready = 'true';
                        const btn = document.getElementById('vmo-business-wizard-btn');
                        if (btn) btn.textContent = 'Review Consultation';
                    }
                });
        };

        const resolveAjaxConfig = () => {
            try {
                if (typeof vmo_ajax !== 'undefined' && vmo_ajax && vmo_ajax.ajaxurl && vmo_ajax.nonce) {
                    return { ajaxUrl: vmo_ajax.ajaxurl, nonce: vmo_ajax.nonce };
                }
                if (typeof vmoAjax !== 'undefined' && vmoAjax && (vmoAjax.ajax_url || vmoAjax.ajaxurl) && vmoAjax.nonce) {
                    return { ajaxUrl: (vmoAjax.ajax_url || vmoAjax.ajaxurl), nonce: vmoAjax.nonce };
                }
            } catch (_) {}
            return null;
        };

        const cfgNow = resolveAjaxConfig();
        if (cfgNow) {
            updateConsultationStatus(cfgNow.ajaxUrl, cfgNow.nonce);
        } else {
            // vmo_ajax is localized by other scripts that may load after vmo-init.
            let tries = 0;
            const maxTries = 30;
            const t = setInterval(() => {
                tries += 1;
                const cfg = resolveAjaxConfig();
                if (cfg) {
                    clearInterval(t);
                    updateConsultationStatus(cfg.ajaxUrl, cfg.nonce);
                    return;
                }
                if (tries >= maxTries) {
                    clearInterval(t);
                }
            }, 250);
        }
    });
})(jQuery);
// VMO AI Website Builder v8.0.0 - Enhanced Initialization Script
(function() {
    'use strict';
    
    // Initialize debug mode (set to false for production)
    if (typeof window.vmoDebug === 'undefined') {
        window.vmoDebug = false;
    }
    
    // Initialize GSAP ScrollTrigger when available
    document.addEventListener('DOMContentLoaded', function() {
        if (window.gsap && window.ScrollTrigger) {
            // Register ScrollTrigger plugin
            gsap.registerPlugin(ScrollTrigger);
            
            // Initialize ScrollTrigger
            ScrollTrigger.refresh();
            
        if (window.vmoDebug) {
            console.log('VMO: GSAP ScrollTrigger initialized');
        }
        }
        
        // Initialize AOS if available
        if (window.AOS) {
            AOS.init({
                duration: 1000,
                once: true,
                offset: 100
            });
            
        if (window.vmoDebug) {
            console.log('VMO: AOS initialized');
        }
        }
        
        // Global VMO initialization
        if (window.vmoState) {
            console.log('VMO AI Website Builder v8.0.0 initialized');
            
            // Add debug mode toggle (for developers)
            if (window.location.search.includes('vmo-debug=true')) {
                window.vmoDebug = true;
                console.log('VMO Debug mode enabled');
            }
        }
        
        // ========================================
        // WELCOME BONUS NOTIFICATION SYSTEM
        // ========================================
        function vmoNormalizePendingNotifications(rawNotification) {
            if (!rawNotification) return [];
            const parsed = typeof rawNotification === 'string'
                ? JSON.parse(rawNotification)
                : rawNotification;

            if (!parsed) return [];
            return Array.isArray(parsed) ? parsed.filter(Boolean) : [parsed];
        }

        function vmoEscapeSystemHtml(value) {
            const d = document.createElement('div');
            d.textContent = value == null ? '' : String(value);
            return d.innerHTML;
        }

        function vmoShowSystemModal(notification) {
            notification = notification || {};
            const old = document.getElementById('vmo-system-modal-overlay');
            if (old) old.remove();

            const level = String(notification.level || (notification.payment_required ? 'error' : 'info')).toLowerCase();
            const isError = level === 'error' || notification.payment_required || notification.service_locked;
            const title = notification.title || (isError ? 'Your VMO services are paused' : 'VMO Update');
            const message = notification.message || (isError
                ? 'Your VMO services are paused until billing is resolved.'
                : 'Your VMO account has been updated.');
            const accent = isError ? '#ff4d5f' : (level === 'success' ? '#00f5ff' : '#38bdf8');
            const icon = notification.icon || (isError ? '⚠️' : (level === 'success' ? '🎁' : 'ℹ️'));
            const actionUrl = notification.action_url || notification.payment_portal_url || notification.cta_url || (isError ? 'admin.php?page=vmo-my-plan' : '');
            const actionLabel = notification.action_label || (isError ? 'Update Payment Method' : 'Continue Building');
            const retryUrl = notification.retry_url || '';
            const supportUrl = notification.support_url || '';

            const overlay = document.createElement('div');
            overlay.id = 'vmo-system-modal-overlay';
            overlay.style.cssText = `
                position: fixed; inset: 0; z-index: 1000000;
                display: flex; align-items: center; justify-content: center;
                padding: 22px; background: rgba(2, 6, 23, 0.58);
                backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
                animation: vmo-system-modal-fade .18s ease-out;
            `;

            const actionButton = actionUrl ? `<a href="${vmoEscapeSystemHtml(actionUrl)}" style="display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0 20px;border-radius:999px;background:linear-gradient(135deg,#00f5ff,#38bdf8);color:#06111f;text-decoration:none;font-weight:900;box-shadow:0 0 24px rgba(0,245,255,.34);">${vmoEscapeSystemHtml(actionLabel)}</a>` : '';
            const retryButton = retryUrl ? `<a href="${vmoEscapeSystemHtml(retryUrl)}" style="display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0 18px;border-radius:999px;border:1px solid rgba(255,255,255,.18);color:#e5faff;text-decoration:none;font-weight:800;background:rgba(255,255,255,.06);">Retry Payment</a>` : '';
            const supportButton = supportUrl ? `<a href="${vmoEscapeSystemHtml(supportUrl)}" style="display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0 18px;border-radius:999px;border:1px solid rgba(255,255,255,.14);color:#c7f9ff;text-decoration:none;font-weight:800;background:rgba(255,255,255,.04);">Contact Support</a>` : '';

            overlay.innerHTML = `
                <style>
                    @keyframes vmo-system-modal-fade { from { opacity: 0; } to { opacity: 1; } }
                    @keyframes vmo-system-modal-rise { from { opacity: 0; transform: translateY(18px) scale(.96); } to { opacity: 1; transform: translateY(0) scale(1); } }
                    #vmo-system-modal-card:before {
                        content:''; position:absolute; left:0; right:0; top:0; height:3px;
                        background:linear-gradient(90deg, ${accent}, #00f5ff, #7c3aed, ${accent});
                        background-size:300% 100%; animation:vmo-system-modal-sheen 4s linear infinite;
                    }
                    @keyframes vmo-system-modal-sheen { 0% { background-position:0% 50%; } 100% { background-position:300% 50%; } }
                </style>
                <div id="vmo-system-modal-card" role="dialog" aria-modal="true" style="
                    position:relative; overflow:hidden; width:min(620px, calc(100vw - 34px));
                    border-radius:24px; border:1px solid ${accent};
                    background:linear-gradient(145deg, rgba(8,14,33,.96), rgba(15,23,42,.92));
                    color:#e5faff; box-shadow:0 30px 90px rgba(0,0,0,.58), 0 0 45px rgba(0,245,255,.14);
                    padding:30px 30px 26px; font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
                    animation:vmo-system-modal-rise .22s ease-out;
                ">
                    <button type="button" id="vmo-system-modal-x" aria-label="Close" style="position:absolute;top:14px;right:16px;width:34px;height:34px;border-radius:999px;border:1px solid rgba(255,77,95,.45);background:rgba(255,77,95,.12);color:#ff6b7a;font-size:24px;line-height:1;cursor:pointer;font-weight:900;">×</button>
                    <div style="display:flex;gap:16px;align-items:flex-start;padding-right:38px;">
                        <div style="width:54px;height:54px;border-radius:18px;display:flex;align-items:center;justify-content:center;font-size:28px;background:rgba(0,245,255,.08);border:1px solid rgba(0,245,255,.22);box-shadow:inset 0 0 24px rgba(0,245,255,.08);">${vmoEscapeSystemHtml(icon)}</div>
                        <div style="flex:1;min-width:0;">
                            <div style="font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:${accent};font-weight:900;margin-bottom:8px;">VMO Notice</div>
                            <h2 style="margin:0 0 12px;font-size:26px;line-height:1.12;color:#f8fdff;">${vmoEscapeSystemHtml(title)}</h2>
                            <p style="margin:0;color:#cbd5e1;font-size:15px;line-height:1.7;">${vmoEscapeSystemHtml(message)}</p>
                        </div>
                    </div>
                    ${isError ? '<div style="margin-top:18px;border-radius:16px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);padding:14px 16px;color:#dbeafe;font-size:13px;line-height:1.55;">Your website, domain records, and saved work remain in place. Once billing or access is restored, VMO services can continue from where you stopped.</div>' : ''}
                    <div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:24px;align-items:center;">
                        ${actionButton}${retryButton}${supportButton}
                        <button type="button" id="vmo-system-modal-close" style="min-height:44px;padding:0 18px;border-radius:999px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.04);color:#cbd5e1;font-weight:800;cursor:pointer;">Close</button>
                    </div>
                </div>
            `;

            document.body.appendChild(overlay);
            const close = function() { overlay.remove(); };
            const x = document.getElementById('vmo-system-modal-x');
            const closeBtn = document.getElementById('vmo-system-modal-close');
            if (x) x.addEventListener('click', close);
            if (closeBtn) closeBtn.addEventListener('click', close);
            overlay.addEventListener('click', function(e) { if (e.target === overlay) close(); });
        }

        window.vmoShowSystemModal = vmoShowSystemModal;
        window.vmoShowServiceLockModal = function(payload) {
            payload = payload || {};
            vmoShowSystemModal(Object.assign({
                type: 'service_locked',
                level: 'error',
                title: 'Your VMO services are paused',
                payment_required: true,
                service_locked: true,
                action_label: 'Update Payment Method',
                action_url: 'admin.php?page=vmo-my-plan'
            }, payload));
        };

        function vmoShowQueuedSystemNotification(notification) {
            const title = notification && notification.title ? notification.title : 'VMO Update';
            const message = notification && notification.message ? notification.message : '';
            const level = notification && notification.level ? String(notification.level).toLowerCase() : 'info';
            const type = notification && notification.type ? String(notification.type).toLowerCase() : '';
            const modalTypes = ['reward_applied', 'billing_required', 'service_locked', 'payment_required', 'subscription_paused', 'admin_reward', 'user_reward'];

            if (type !== 'a2p_status' && (modalTypes.includes(type) || level === 'success' || level === 'error' || level === 'warning')) {
                vmoShowSystemModal(notification);
                return;
            }

            if (typeof window.showNotification === 'function') {
                const noticeType = (level === 'error') ? 'error' : (level === 'success' ? 'success' : 'info');
                window.showNotification(title + ': ' + message, noticeType);
                return;
            }

            const toast = document.createElement('div');
            const accent = level === 'error'
                ? '#ef4444'
                : (level === 'success' ? '#10b981' : '#3b82f6');

            toast.className = 'vmo-system-toast';
            toast.style.cssText = `
                position: fixed;
                top: 24px;
                right: 24px;
                width: min(360px, calc(100vw - 32px));
                padding: 14px 16px;
                border-radius: 14px;
                border: 1px solid ${accent};
                background: rgba(15, 23, 42, 0.96);
                color: #e5e7eb;
                box-shadow: 0 18px 40px rgba(15, 23, 42, 0.35);
                z-index: 999999;
                opacity: 0;
                transform: translateY(-8px);
                transition: opacity 180ms ease, transform 180ms ease;
            `;

            toast.innerHTML = `
                <div style="font-weight:700; color:${accent}; margin-bottom:6px;">${title}</div>
                <div style="font-size:13px; line-height:1.5; color:#cbd5e1;">${message}</div>
            `;

            document.body.appendChild(toast);
            requestAnimationFrame(() => {
                toast.style.opacity = '1';
                toast.style.transform = 'translateY(0)';
            });

            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(-8px)';
                setTimeout(() => toast.remove(), 220);
            }, 8500);
        }

        // Check for pending notifications (e.g., post-purchase welcome bonus)
        let quickLaunchWelcomeQueued = false;
        if (typeof vmo_ajax !== 'undefined' && vmo_ajax.pending_notification) {
            try {
                const notifications = vmoNormalizePendingNotifications(vmo_ajax.pending_notification);

                if (notifications.length) {
                    notifications.forEach(function(notification, index) {
                        const delay = 1200 + (index * 450);
                        if (notification && notification.type === 'welcome_bonus') {
                            setTimeout(function() {
                                showWelcomeBonusModal(notification);
                            }, delay);
                            return;
                        }

                        if (notification && notification.type === 'quicklaunch_payment') {
                            quickLaunchWelcomeQueued = true;
                            setTimeout(function() {
                                showQuickLaunchPaymentModal(notification);
                            }, delay);
                            return;
                        }

                        setTimeout(function() {
                            vmoShowQueuedSystemNotification(notification);
                        }, delay);
                    });

                    jQuery.post(vmo_ajax.ajaxurl, {
                        action: 'vmo_clear_pending_notification',
                        security: vmo_ajax.nonce
                    });
                }
            } catch (e) {
                console.log('VMO: Could not parse pending notification', e);
            }
        }

        if (typeof vmo_ajax !== 'undefined' && !quickLaunchWelcomeQueued && vmo_ajax.quicklaunch_welcome && vmo_ajax.quicklaunch_welcome.pending) {
            const welcome = vmo_ajax.quicklaunch_welcome;
            const fallbackNotification = {
                type: 'quicklaunch_payment',
                title: welcome.name ? 'Welcome to VMO, ' + welcome.name : 'Welcome to VMO',
                message: 'Your hosted VMO workspace is ready. Jarvis will guide you to the Business Wizard so VMO can begin building the right connected system for you.',
                spoken_message: welcome.spoken_message || '',
                speak_on_open: true,
                remaining_tokens: vmo_ajax.token_balance || 0
            };
            setTimeout(function() {
                showQuickLaunchPaymentModal(fallbackNotification);
            }, 1200);
            jQuery.post(vmo_ajax.ajaxurl, {
                action: 'vmo_clear_pending_notification',
                security: vmo_ajax.nonce
            });
        }
        
        // ========================================
        // TESTER PLAN PERSISTENT REMINDER
        // ========================================
        if (typeof vmo_ajax !== 'undefined' && (vmo_ajax.current_plan === 'tester' || vmo_ajax.current_plan === 'tester_pack')) {
            // Delay slightly to not conflict with sign up bonus
            setTimeout(function() {
                const upgradeLink = vmo_ajax.upgradeUrl || '/vmo-upgrade';
                const reminderToast = document.createElement('div');
                reminderToast.className = 'vmo-tester-reminder';
                reminderToast.style.cssText = `
                    position: fixed;
                    bottom: 25px;
                    right: 25px;
                    width: 380px;
                    background: rgba(22, 33, 62, 0.75);
                    backdrop-filter: blur(12px);
                    -webkit-backdrop-filter: blur(12px);
                    border: 1px solid rgba(0, 255, 136, 0.15);
                    border-left: 4px solid #00ff88;
                    border-radius: 16px;
                    padding: 20px;
                    box-shadow: 
                        0 20px 50px rgba(0, 0, 0, 0.5),
                        0 0 0 1px rgba(255, 255, 255, 0.05),
                        inset 0 0 30px rgba(0, 255, 136, 0.05);
                    z-index: 999990;
                    display: flex;
                    flex-direction: column;
                    gap: 15px;
                    transform: translateY(100px) scale(0.95);
                    opacity: 0;
                    transition: all 0.6s cubic-bezier(0.19, 1, 0.22, 1);
                    font-family: 'Inter', system-ui, sans-serif;
                    overflow: hidden;
                `;
                
                // Add sheen effect
                const sheen = document.createElement('div');
                sheen.style.cssText = `
                    position: absolute;
                    top: 0; left: -100%;
                    width: 50%; height: 100%;
                    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent);
                    transform: skewX(-25deg);
                    animation: vmo-sheen 6s infinite;
                    pointer-events: none;
                `;
                
                // Content grid
                reminderToast.innerHTML = `
                    <div style="display:flex; align-items:flex-start; gap:15px; position:relative; z-index:2;">
                        <div style="
                            font-size: 24px; 
                            background: rgba(0, 255, 136, 0.1); 
                            width: 44px; height: 44px; 
                            border-radius: 12px; 
                            display:flex; align-items:center; justify-content:center;
                            border: 1px solid rgba(0, 255, 136, 0.2);
                            box-shadow: 0 0 20px rgba(0, 255, 136, 0.1);
                        ">⚠️</div>
                        <div style="flex:1;">
                            <h4 style="
                                margin: 0 0 6px 0; 
                                font-size: 16px; 
                                font-weight: 700; 
                                color: #fff; 
                                text-shadow: 0 0 20px rgba(0, 255, 136, 0.3);
                                letter-spacing: -0.01em;
                            ">Upgrade Advised</h4>
                            <p style="
                                margin: 0; 
                                font-size: 13px; 
                                color: rgba(255, 255, 255, 0.75); 
                                line-height: 1.5;
                            ">Your Tester Plan is valid for setup only. Background operations (SEO, Email, Blog) are currently paused.</p>
                        </div>
                    </div>
                    
                    <div style="
                        display:flex; 
                        justify-content:flex-end; 
                        gap:12px; 
                        margin-top:5px; 
                        position:relative; 
                        z-index:2;
                    ">
                        <button id="vmo-close-toast" style="
                            background: transparent;
                            border: none;
                            color: rgba(255,255,255,0.5);
                            font-size: 13px;
                            font-weight: 600;
                            cursor: pointer;
                            padding: 10px 15px;
                            border-radius: 8px;
                            transition: all 0.2s;
                        ">Dismiss</button>
                        <a href="${upgradeLink}" style="
                            background: linear-gradient(135deg, rgba(0, 255, 136, 0.2) 0%, rgba(0, 212, 255, 0.2) 100%);
                            border: 1px solid rgba(0, 255, 136, 0.4);
                            color: #00ff88;
                            padding: 9px 20px;
                            border-radius: 8px;
                            text-decoration: none;
                            font-weight: 600;
                            font-size: 13px;
                            white-space: nowrap;
                            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
                            transition: all 0.2s;
                            text-shadow: 0 0 10px rgba(0, 255, 136, 0.3);
                        " onmouseover="this.style.background='linear-gradient(135deg, #00ff88 0%, #00d4ff 100%)'; this.style.color='#1a1a2e'; this.style.boxShadow='0 0 30px rgba(0,255,136,0.4)';" 
                          onmouseout="this.style.background='linear-gradient(135deg, rgba(0, 255, 136, 0.2) 0%, rgba(0, 212, 255, 0.2) 100%)'; this.style.color='#00ff88'; this.style.boxShadow='0 4px 15px rgba(0,0,0,0.2)';">Upgrade to Pro &rarr;</a>
                    </div>
                    
                    <button id="vmo-toast-x" style="
                        position: absolute;
                        top: 15px;
                        right: 15px;
                        background: none;
                        border: none;
                        color: rgba(255,255,255,0.3);
                        cursor: pointer;
                        font-size: 18px;
                        padding: 5px;
                        line-height: 1;
                        z-index: 10;
                        transition: color 0.2s;
                    ">×</button>
                `;
                
                // Add sheen keyframes
                if (!document.getElementById('vmo-toast-styles')) {
                    const style = document.createElement('style');
                    style.id = 'vmo-toast-styles';
                    style.textContent = `@keyframes vmo-sheen { 0% { left: -100%; } 20% { left: 200%; } 100% { left: 200%; } }`;
                    document.head.appendChild(style);
                }
                
                reminderToast.appendChild(sheen);
                document.body.appendChild(reminderToast);
                
                // Animate in
                requestAnimationFrame(() => {
                    reminderToast.style.transform = 'translateY(0) scale(1)';
                    reminderToast.style.opacity = '1';
                });
                
                // Close handlers
                const closeToast = () => {
                    reminderToast.style.transform = 'translateY(20px) scale(0.95)';
                    reminderToast.style.opacity = '0';
                    setTimeout(() => reminderToast.remove(), 600);
                };
                
                document.getElementById('vmo-close-toast').onclick = closeToast;
                document.getElementById('vmo-toast-x').onclick = closeToast;
                
            }, 3000);
        }

        // ========================================
        // TESTER PLAN — ROTATING MISSED OPS TOASTS
        // Shows individual missed background operation toasts on a rotating schedule
        // so the user is constantly reminded which premium features are paused.
        // ========================================
        if (typeof vmo_ajax !== 'undefined' && (vmo_ajax.current_plan === 'tester' || vmo_ajax.current_plan === 'tester_pack')) {
            const missedOps = Array.isArray(vmo_ajax.upgrade_prompts) ? vmo_ajax.upgrade_prompts : [];
            if (missedOps.length > 0) {
                let opsIndex = 0;
                // Operation icons for visual variety
                const opsIcons = {
                    'weekly_deep_research': '🔍',
                    'weekly_email_research': '📧',
                    'seo_audit': '📊',
                    'competitor_monitoring': '🕵️',
                    'blog_generation': '✍️',
                    'ranking_tracking': '📈',
                    'email_strategy_review': '💌'
                };

                function showMissedOpToast() {
                    if (opsIndex >= missedOps.length) opsIndex = 0;
                    const op = missedOps[opsIndex];
                    opsIndex++;
                    if (!op) return;

                    const icon = opsIcons[op.operation] || '⏸️';
                    const opName = op.operation_name || op.operation || 'Background Operation';
                    const upgradeLink = vmo_ajax.upgradeUrl || '/vmo-upgrade';

                    // Remove any existing missed-op toast
                    const existing = document.getElementById('vmo-missed-op-toast');
                    if (existing) existing.remove();

                    const toast = document.createElement('div');
                    toast.id = 'vmo-missed-op-toast';
                    toast.style.cssText = `
                        position:fixed; top:80px; right:25px; width:340px; z-index:999980;
                        background:rgba(22,33,62,0.8); backdrop-filter:blur(12px); -webkit-backdrop-filter:blur(12px);
                        border:1px solid rgba(245,158,11,0.2); border-left:3px solid #f59e0b;
                        border-radius:12px; padding:14px 16px;
                        box-shadow:0 10px 30px rgba(0,0,0,0.4);
                        transform:translateX(120%) scale(0.95); opacity:0;
                        transition:all 0.5s cubic-bezier(0.19,1,0.22,1);
                        font-family:'Inter',system-ui,sans-serif;
                    `;

                    toast.innerHTML = `
                        <div style="display:flex; align-items:flex-start; gap:10px;">
                            <span style="font-size:20px; flex-shrink:0;">${icon}</span>
                            <div style="flex:1; min-width:0;">
                                <div style="font-size:12px; font-weight:700; color:#f59e0b; margin-bottom:3px;">Missing: ${escOp(opName)}</div>
                                <p style="margin:0; font-size:11.5px; color:rgba(255,255,255,0.65); line-height:1.4;">This feature runs automatically on Starter+ plans to grow your business while you sleep.</p>
                                <a href="${upgradeLink}" style="display:inline-block; margin-top:8px; font-size:11px; color:#a78bfa; text-decoration:none; font-weight:600;" onmouseover="this.style.color='#c4b5fd'" onmouseout="this.style.color='#a78bfa'">Unlock with upgrade →</a>
                            </div>
                            <button onclick="this.closest('#vmo-missed-op-toast').style.opacity='0';this.closest('#vmo-missed-op-toast').style.transform='translateX(120%)';setTimeout(()=>{const e=document.getElementById('vmo-missed-op-toast');if(e)e.remove();},500);" style="background:none; border:none; color:rgba(255,255,255,0.25); cursor:pointer; font-size:14px; padding:2px; flex-shrink:0;">×</button>
                        </div>
                    `;

                    document.body.appendChild(toast);

                    // Animate in
                    requestAnimationFrame(() => {
                        toast.style.transform = 'translateX(0) scale(1)';
                        toast.style.opacity = '1';
                    });

                    // Auto-dismiss after 8 seconds
                    setTimeout(() => {
                        if (document.getElementById('vmo-missed-op-toast')) {
                            toast.style.transform = 'translateX(120%) scale(0.95)';
                            toast.style.opacity = '0';
                            setTimeout(() => { if (toast.parentNode) toast.remove(); }, 500);
                        }
                    }, 8000);
                }

                function escOp(str) {
                    const d = document.createElement('div');
                    d.textContent = str;
                    return d.innerHTML;
                }

                // First missed-op toast after 15 seconds (let page settle),
                // then rotate every 90 seconds (1.5 min)
                setTimeout(showMissedOpToast, 15000);
                setInterval(showMissedOpToast, 90000);
            }
        }
    });
    
    // Expose GSAP utilities globally for the builder
    window.vmoAnimationUtils = {
        // Quick animation presets
        fadeIn: function(element, duration = 1) {
            if (window.gsap) {
                return gsap.fromTo(element, 
                    { opacity: 0, y: 30 }, 
                    { opacity: 1, y: 0, duration: duration, ease: "power2.out" }
                );
            }
        },
        
        slideIn: function(element, direction = 'left', duration = 1) {
            if (window.gsap) {
                const from = direction === 'left' ? { x: -100 } : 
                           direction === 'right' ? { x: 100 } : 
                           direction === 'up' ? { y: -100 } : { y: 100 };
                
                return gsap.fromTo(element, 
                    { ...from, opacity: 0 }, 
                    { x: 0, y: 0, opacity: 1, duration: duration, ease: "power2.out" }
                );
            }
        },
        
        zoomIn: function(element, duration = 1) {
            if (window.gsap) {
                return gsap.fromTo(element, 
                    { scale: 0.8, opacity: 0 }, 
                    { scale: 1, opacity: 1, duration: duration, ease: "back.out(1.7)" }
                );
            }
        },
        
        // Scroll-triggered animations
        animateOnScroll: function(element, animation, options = {}) {
            if (window.gsap && window.ScrollTrigger) {
                return ScrollTrigger.create({
                    trigger: element,
                    start: options.start || "top 80%",
                    end: options.end || "bottom 20%",
                    animation: animation,
                    scrub: options.scrub || false,
                    ...options
                });
            }
        }
    };
    // Simple parallax API: data-parallax="y" (default), or one of: y, x, rotate, scale. Optional: data-parallax-speed (0.1–1)
    function initParallax(rootDoc){
        try {
            if (!window.gsap || !window.ScrollTrigger) return;
            const doc = rootDoc || document;
            const nodes = doc.querySelectorAll('[data-parallax]');
            nodes.forEach(el => {
                const type = (el.getAttribute('data-parallax') || 'y').toLowerCase();
                const speed = parseFloat(el.getAttribute('data-parallax-speed') || '0.25');
                let from = {}, to = {};
                switch(type){
                    case 'x': from={x: -100*speed, opacity:1}; to={x: 100*speed}; break;
                    case 'rotate': from={rotation: -10*speed, opacity:1}; to={rotation: 10*speed}; break;
                    case 'scale': from={scale: 1-0.1*speed, opacity:1}; to={scale: 1+0.1*speed}; break;
                    case 'y':
                    default: from={y: -100*speed, opacity:1}; to={y: 100*speed};
                }
                gsap.fromTo(el, from, {
                    ...to,
                    ease: 'none',
                    scrollTrigger: {
                        trigger: el,
                        start: 'top bottom',
                        end: 'bottom top',
                        scrub: true
                    }
                });
            });
        } catch(e) { if (window.vmoDebug) console.warn('Parallax init skipped', e); }
    }
    document.addEventListener('DOMContentLoaded', function(){ initParallax(document); });
    // Re-init parallax inside the preview iframe when it loads new content
    document.getElementById('vmo-preview-iframe')?.addEventListener('load', function(){
        try { initParallax(this.contentDocument || this.contentWindow.document); } catch(_){}
    });
    
})();

function consumeBuilderResetSentinel() {
    try {
        const key = 'builder_reset_blank_pending';
        const legacyKey = 'builder_reset_demo_pending';
        const value = sessionStorage.getItem(key) === '1' || sessionStorage.getItem(legacyKey) === '1';
        if (value) {
            sessionStorage.removeItem(key);
            sessionStorage.removeItem(legacyKey);
        }
        return value;
    } catch (_) {
        return false;
    }
}

// Original initialization - Fixed jQuery wrapper
jQuery(document).ready(function ($) {
    window.updateTokenBalance();
    window.showToast('Welcome to VMO AI Builder v8.0.0!', 'success');
    const forcedBlankReset = consumeBuilderResetSentinel();
    const serverResetMode = !!((typeof vmo_ajax !== 'undefined' && vmo_ajax.builder_reset_mode) || (typeof vmoAjax !== 'undefined' && vmoAjax.builder_reset_mode));
    const builderResetMode = forcedBlankReset || serverResetMode;

    if (builderResetMode) {
        window.autoLoadLatestProject = false;
        window.currentProjectTitle = null;
        window.currentProjectId = null;
        window.currentLivePageId = null;
        window.vmoLivePermalink = '';
        window.lastContent = '';
        window.vmoHasContent = false;
        window.vmoPreviewIsLive = false;
        window.vmoState = { blocks: [] };

        try {
            if (typeof window.vmoClearStoredCheckpoint === 'function') {
                window.vmoClearStoredCheckpoint();
            } else {
                localStorage.removeItem('vmo_checkpoint_state');
                localStorage.removeItem('vmo_checkpoint_html');
                localStorage.removeItem('vmo_checkpoint_ts');
                localStorage.removeItem('vmo_checkpoint_title');
            }
        } catch (_) {}

        $('#vmo-code-view').text('').val('');

        const iframe = document.getElementById('vmo-preview-iframe');
        if (iframe) {
            iframe.removeAttribute('src');
            iframe.removeAttribute('srcdoc');
            iframe.srcdoc = '';
            delete iframe.dataset.vmoPreviewMode;
        }
    }

    window.renderBlocks();

    if (builderResetMode && typeof window.vmoBlankPreviewFrame === 'function') {
        setTimeout(function() {
            window.vmoBlankPreviewFrame({ force: true, skipPersist: true });
        }, 160);
    }

    // Auto-load the latest generated website into the preview (single-business default)
    if (typeof window.autoLoadLatestProject === 'undefined') window.autoLoadLatestProject = true;
    const shouldAutoLoad = !builderResetMode && window.autoLoadLatestProject && !window.currentProjectTitle && (!window.vmoState || !window.vmoState.blocks || window.vmoState.blocks.length === 0);
    if (shouldAutoLoad && typeof vmo_ajax !== 'undefined') {
        // ── Immediately restore from localStorage (instant, avoids placeholder flash) ──
        (function restoreFromLocalStorage() {
            try {
                const savedState = localStorage.getItem('vmo_checkpoint_state');
                const savedHtml  = localStorage.getItem('vmo_checkpoint_html');
                const normalizedSavedHtml = typeof window.vmoNormalizeBuilderHtml === 'function'
                    ? window.vmoNormalizeBuilderHtml(savedHtml)
                    : (savedHtml || '');
                if (savedState && savedHtml && savedHtml.trim()) {
                    let parsed = JSON.parse(savedState);
                    const canRestoreSavedHtml = typeof window.vmoShouldTreatAsRealContent === 'function'
                        ? window.vmoShouldTreatAsRealContent(normalizedSavedHtml, parsed)
                        : !!normalizedSavedHtml.trim();

                    if (parsed && parsed.blocks && parsed.blocks.length && canRestoreSavedHtml) {
                        window.vmoState = parsed;
                        window.lastContent = normalizedSavedHtml;
                        window.vmoHasContent = true;
                        window.currentProjectTitle = localStorage.getItem('vmo_checkpoint_title') || null;
                        $('#vmo-code-view').text(normalizedSavedHtml);
                        const $ifr = $('#vmo-preview-iframe');
                        if ($ifr.length && !window.vmoPreviewIsLive) $ifr[0].srcdoc = normalizedSavedHtml;
                        if (typeof renderBlocks === 'function') renderBlocks();
                        console.log('[VMO] Restored from localStorage checkpoint');
                    } else if (savedState || savedHtml) {
                        if (typeof window.vmoClearStoredCheckpoint === 'function') {
                            window.vmoClearStoredCheckpoint();
                        }
                        console.log('[VMO] Skipped legacy demo checkpoint restore');
                    }
                }
            } catch (e) { console.warn('[VMO] localStorage restore failed:', e); }
        })();

        // ── Then fetch from server (authoritative) — overwrites localStorage snapshot ──
        $.post(vmo_ajax.ajaxurl, { action: 'vmo_get_latest_project', security: vmo_ajax.nonce })
            .done(function(res){
                if (res && res.success && res.data && res.data.project && res.data.project.html) {
                    const proj = res.data.project;
                    const normalizedProjectHtml = typeof window.vmoNormalizeBuilderHtml === 'function'
                        ? window.vmoNormalizeBuilderHtml(proj.html || '')
                        : (proj.html || '');
                    // Set state
                    let loadedState = proj.state;
                    if (typeof loadedState === 'string') {
                        try { loadedState = JSON.parse(loadedState); } catch(e){ loadedState = { blocks: [] }; }
                    }
                    const canRestoreProject = typeof window.vmoShouldTreatAsRealContent === 'function'
                        ? window.vmoShouldTreatAsRealContent(normalizedProjectHtml, loadedState)
                        : !!normalizedProjectHtml.trim();

                    if (!canRestoreProject) {
                        console.log('[VMO] Skipped legacy demo autoload; blank preview retained');
                        return;
                    }

                    window.currentProjectTitle = proj.title || null;
                    window.currentProjectId = proj.id || null;
                    window.currentLivePageId = proj.live_page_id || null;
                    window.vmoState = loadedState && loadedState.blocks ? loadedState : { blocks: [] };
                    window.lastContent = normalizedProjectHtml;
                    window.vmoHasContent = !!(window.lastContent && window.lastContent.trim());
                    // Paint UI
                    $('#vmo-code-view').text(window.lastContent);
                    const $ifr = $('#vmo-preview-iframe');
                    if ($ifr.length && !window.vmoPreviewIsLive) $ifr[0].srcdoc = window.lastContent;
                    if (typeof window.vmoInjectReplaceButtonsInIframe === 'function') setTimeout(window.vmoInjectReplaceButtonsInIframe, 200);
                    if (typeof primeUndoStackOnLoad === 'function') primeUndoStackOnLoad(window.vmoState);
                    if (typeof renderBlocks === 'function') renderBlocks();
                    if (window.currentProjectId && window.vmoMediaGenerator && typeof window.vmoMediaGenerator.startProjectQueuePolling === 'function') {
                        window.vmoMediaGenerator.startProjectQueuePolling(window.currentProjectId, { source: 'builder' });
                    }
                    if (typeof showToast === 'function') showToast('Loaded latest website ✅', 'success');
                    window.isUnsaved = false;
                }
            });
    }

    // Move all your $(document).on and UI click handlers here, using the new modular functions.
    // Example for block refinement:
    $(document).on('click', '.vmo-refine-btn', function () {
        const sectionIndex = $(this).data('section-index');
        const userEdit = prompt('Describe your refinement for this section:');
        if (!userEdit) return;
        window.refineSectionBlock(sectionIndex, userEdit);
    });

    // ...repeat for other handlers: save, load, insert media, etc.
});

// Modal utility (unified full-screen pattern)
(function(){
  if (window.vmoModalUtils) return; // singleton
  const ACTIVE_CLASS = 'vmo-modal-visible';
    function open(modal){
        if (!modal) return;
        // Ensure it is visible (our dashboard templates rely on flex display)
        modal.style.display = 'flex';
        modal.classList.add(ACTIVE_CLASS);
        trapFocus(modal);
    }
    function close(modal){
        if (!modal) return;
        modal.classList.remove(ACTIVE_CLASS);
        // Hide after transition
        modal.style.display = 'none';
        releaseFocus(modal);
    }
  function toggle(modal){ modal.classList.contains(ACTIVE_CLASS)?close(modal):open(modal); }
  function byId(id){ return document.getElementById(id); }
  // Basic focus trap for accessibility
  function trapFocus(root){
    const focusables = root.querySelectorAll('a[href],button,textarea,input,select,[tabindex]:not([tabindex="-1"])');
    if (!focusables.length) return;
    const first = focusables[0]; const last = focusables[focusables.length-1];
    function keyHandler(e){
      if (e.key === 'Tab') {
        if (e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
      } else if (e.key === 'Escape'){ close(root); document.removeEventListener('keydown', keyHandler); }
    }
    document.addEventListener('keydown', keyHandler);
    setTimeout(()=> first.focus(), 30);
    root.dataset.focusTrap = '1';
  }
  function releaseFocus(root){ if (!root) return; if (root.dataset.focusTrap){ delete root.dataset.focusTrap; }}
  // Global delegated listeners (overlay & [data-vmo-close])
  document.addEventListener('click', function(e){
    const t = e.target;
    if (t.matches('[data-vmo-open]')) { const id = t.getAttribute('data-vmo-open'); open(byId(id)); }
    else if (t.matches('[data-vmo-close]')) { const id = t.getAttribute('data-vmo-close'); id?close(byId(id)):close(t.closest('.vmo-fs-modal')); }
    else if (t.classList.contains('vmo-modal-overlay')) { const wrap = t.parentElement; if (wrap && wrap.classList.contains('vmo-fs-modal')) close(wrap); }
  });
  window.vmoModalUtils = { open, close, toggle, byId };
})();

// ========================================
// WELCOME BONUS MODAL FUNCTION
// ========================================
// Displays a celebration modal for the $20 welcome bonus for Starter plan users
function showWelcomeBonusModal(notification) {
    // Create modal overlay
    const modalOverlay = document.createElement('div');
    modalOverlay.id = 'vmo-welcome-bonus-modal';
    modalOverlay.className = 'vmo-welcome-bonus-overlay';
    
    modalOverlay.innerHTML = `
        <div class="vmo-welcome-bonus-modal">
            <div class="vmo-welcome-bonus-header">
                <span class="vmo-welcome-bonus-emoji">🎉</span>
                <h2>${notification.title || 'Welcome to VMO!'}</h2>
            </div>
            <div class="vmo-welcome-bonus-content">
                <div class="vmo-welcome-bonus-amount">
                    <span class="vmo-bonus-value">${notification.amount || '$20.00'}</span>
                    <span class="vmo-bonus-label">BONUS CREDIT</span>
                </div>
                <p class="vmo-welcome-bonus-message">${notification.message || "Thank you for subscribing! We've added a bonus to your account."}</p>
            </div>
            <div class="vmo-welcome-bonus-footer">
                <button class="vmo-welcome-bonus-btn" id="vmo-welcome-bonus-close">Get Started!</button>
            </div>
        </div>
    `;
    
    // Add styles dynamically
    const styles = document.createElement('style');
    styles.textContent = `
        .vmo-welcome-bonus-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 999999;
            animation: vmo-bonus-fade-in 0.3s ease-out;
        }
        
        @keyframes vmo-bonus-fade-in {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes vmo-bonus-pop-in {
            0% { transform: scale(0.8); opacity: 0; }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); opacity: 1; }
        }
        
        @keyframes vmo-bonus-shimmer {
            0% { background-position: -200% center; }
            100% { background-position: 200% center; }
        }
        
        .vmo-welcome-bonus-modal {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            border-radius: 20px;
            padding: 40px;
            max-width: 450px;
            width: 90%;
            text-align: center;
            box-shadow: 0 25px 80px rgba(0, 0, 0, 0.5), 
                        0 0 0 1px rgba(255, 255, 255, 0.1),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1);
            animation: vmo-bonus-pop-in 0.4s ease-out 0.1s both;
            position: relative;
            overflow: hidden;
        }
        
        .vmo-welcome-bonus-modal::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #00ff88, #00d4ff, #ff00ff, #00ff88);
            background-size: 300% 100%;
            animation: vmo-bonus-shimmer 3s linear infinite;
        }
        
        .vmo-welcome-bonus-header {
            margin-bottom: 25px;
        }
        
        .vmo-welcome-bonus-emoji {
            font-size: 60px;
            display: block;
            margin-bottom: 10px;
            animation: vmo-bonus-pop-in 0.5s ease-out 0.3s both;
        }
        
        .vmo-welcome-bonus-header h2 {
            color: #fff;
            font-size: 28px;
            font-weight: 700;
            margin: 0;
            text-shadow: 0 2px 10px rgba(0, 255, 136, 0.3);
        }
        
        .vmo-welcome-bonus-amount {
            background: linear-gradient(135deg, #00ff88 0%, #00d4ff 100%);
            border-radius: 15px;
            padding: 25px;
            margin: 20px 0;
            animation: vmo-bonus-pop-in 0.5s ease-out 0.4s both;
        }
        
        .vmo-bonus-value {
            display: block;
            font-size: 48px;
            font-weight: 800;
            color: #1a1a2e;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        
        .vmo-bonus-label {
            display: block;
            font-size: 14px;
            font-weight: 600;
            color: rgba(26, 26, 46, 0.8);
            letter-spacing: 2px;
            margin-top: 5px;
        }
        
        .vmo-welcome-bonus-message {
            color: rgba(255, 255, 255, 0.85);
            font-size: 16px;
            line-height: 1.6;
            margin: 20px 0;
        }
        
        .vmo-welcome-bonus-btn {
            background: linear-gradient(135deg, #00ff88 0%, #00d4ff 100%);
            border: none;
            border-radius: 10px;
            color: #1a1a2e;
            font-size: 18px;
            font-weight: 700;
            padding: 15px 40px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 20px rgba(0, 255, 136, 0.3);
        }
        
        .vmo-welcome-bonus-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 30px rgba(0, 255, 136, 0.5);
        }
        
        .vmo-welcome-bonus-btn:active {
            transform: translateY(0);
        }
    `;
    
    document.head.appendChild(styles);
    document.body.appendChild(modalOverlay);
    
    // Close button handler
    document.getElementById('vmo-welcome-bonus-close').addEventListener('click', function() {
        modalOverlay.style.animation = 'vmo-bonus-fade-in 0.2s ease-out reverse';
        setTimeout(function() {
            modalOverlay.remove();
            styles.remove();
        }, 200);
    });
    
    // Also close on overlay click
    modalOverlay.addEventListener('click', function(e) {
        if (e.target === modalOverlay) {
            modalOverlay.style.animation = 'vmo-bonus-fade-in 0.2s ease-out reverse';
            setTimeout(function() {
                modalOverlay.remove();
                styles.remove();
            }, 200);
        }
    });
    
    console.log('VMO: Welcome bonus modal displayed');
}

// Make it globally available
window.showWelcomeBonusModal = showWelcomeBonusModal;

function speakQuickLaunchWelcome(notification) {
    if (!notification || !notification.speak_on_open) {
        return;
    }

    const text = (notification.spoken_message || notification.message || '').trim();
    if (!text) {
        return;
    }

    const tryBrowserSpeech = function() {
        if (!window.speechSynthesis || !window.SpeechSynthesisUtterance) {
            return false;
        }

        try {
            window.speechSynthesis.cancel();
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.rate = 0.96;
            utterance.pitch = 1;
            window.speechSynthesis.speak(utterance);
            return true;
        } catch (error) {
            return false;
        }
    };

    const speak = function() {
        if (typeof window.vmoSpeak === 'function') {
            Promise.resolve(window.vmoSpeak(text, 'ash', 'mp3', 1.0, { allowStreaming: true }))
                .catch(function() {
                    tryBrowserSpeech();
                });
            return;
        }

        tryBrowserSpeech();
    };

    setTimeout(speak, 1200);
}

function showQuickLaunchPaymentModal(notification) {
    const modalOverlay = document.createElement('div');
    modalOverlay.id = 'vmo-quicklaunch-payment-modal';
    modalOverlay.className = 'vmo-welcome-bonus-overlay';

    const lineItems = Array.isArray(notification && notification.line_items)
        ? notification.line_items.map(function(item) {
            const usd = item && item.usd_display ? ' <span style="opacity:.72">' + item.usd_display + '</span>' : '';
            return '<li style="display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid rgba(255,255,255,.06);"><span>'
                + (item && item.label ? item.label : 'Setup item')
                + usd
                + '</span><strong style="color:#7dd3fc;white-space:nowrap;">'
                + 'Included</strong></li>';
        }).join('')
        : '';

    modalOverlay.innerHTML = `
        <div class="vmo-welcome-bonus-modal" style="max-width:560px;">
            <div class="vmo-welcome-bonus-header">
                <span class="vmo-welcome-bonus-emoji">✅</span>
                <h2>${notification.title || 'QuickLaunch Payment Successful'}</h2>
            </div>
            <div class="vmo-welcome-bonus-content">
                <div class="vmo-welcome-bonus-amount" style="padding:20px 22px;">
                    <span class="vmo-bonus-value" style="font-size:36px;">${Number(notification && notification.remaining_tokens ? notification.remaining_tokens : 0).toLocaleString()}</span>
                    <span class="vmo-bonus-label">CREDITS READY AT LAUNCH</span>
                </div>
                <p class="vmo-welcome-bonus-message">${notification.message || 'Your QuickLaunch subscription is active and your remaining balance is ready in the builder.'}</p>
                <div style="text-align:left;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06);border-radius:14px;padding:16px 18px;margin-top:18px;">
                    <div style="display:grid;grid-template-columns:1fr auto;gap:10px;font-size:14px;color:#e5e7eb;">
                        <span>Amount paid</span>
                        <strong>${notification && notification.total_paid ? notification.total_paid : 'See transaction email'}</strong>
                        <span>Month-one wallet</span>
                        <strong>${Number(notification && notification.month_one_tokens ? notification.month_one_tokens : 0).toLocaleString()} credits</strong>
                        <span>Hosted setup</span>
                        <strong>Included</strong>
                        <span>Next-cycle credit recovery</span>
                        <strong>None</strong>
                    </div>
                    ${lineItems ? '<div style="margin-top:16px;"><div style="font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:rgba(255,255,255,.58);margin-bottom:8px;">Hosted setup included</div><ul style="list-style:none;margin:0;padding:0;">' + lineItems + '</ul></div>' : ''}
                </div>
            </div>
            <div class="vmo-welcome-bonus-footer" style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;">
                <button class="vmo-welcome-bonus-btn" id="vmo-quicklaunch-payment-speak" type="button">Hear Jarvis Welcome</button>
                <button class="vmo-welcome-bonus-btn" id="vmo-quicklaunch-payment-close">Okay</button>
            </div>
            <button id="vmo-quicklaunch-payment-x" aria-label="Close" style="position:absolute;top:18px;right:18px;background:none;border:none;color:rgba(255,255,255,.45);font-size:24px;line-height:1;cursor:pointer;">×</button>
        </div>
    `;

    const styles = document.createElement('style');
    styles.textContent = `
        #vmo-quicklaunch-payment-modal .vmo-welcome-bonus-modal::before {
            background: linear-gradient(90deg, #10b981, #0ea5e9, #22c55e, #10b981);
            background-size: 300% 100%;
        }
    `;

    document.head.appendChild(styles);
    document.body.appendChild(modalOverlay);

    const closeModal = function() {
        modalOverlay.style.animation = 'vmo-bonus-fade-in 0.2s ease-out reverse';
        setTimeout(function() {
            modalOverlay.remove();
            styles.remove();
        }, 200);
    };

    document.getElementById('vmo-quicklaunch-payment-close').addEventListener('click', closeModal);
    document.getElementById('vmo-quicklaunch-payment-x').addEventListener('click', closeModal);
    document.getElementById('vmo-quicklaunch-payment-speak').addEventListener('click', function() {
        const replayNotification = Object.assign({}, notification, { speak_on_open: true });
        speakQuickLaunchWelcome(replayNotification);
    });
    modalOverlay.addEventListener('click', function(e) {
        if (e.target === modalOverlay) {
            closeModal();
        }
    });

    speakQuickLaunchWelcome(notification);
}

window.showQuickLaunchPaymentModal = showQuickLaunchPaymentModal;
