(function($){ 
    // State for billing cycle (default monthly)
    let currentBilling = 'monthly';

    function refreshPlanPrices() {
        $('.vmo-plan-price').each(function() {
            const $price = $(this);
            const amount = $price.data(currentBilling);
            if (amount) {
                const period = currentBilling === 'annual' ? '/year' : '/month';
                $price.find('.amount').text('$' + amount);
                $price.find('.period').text(period);
            }
        });
    }

    $(function() {
        const initialBilling = $('#billingToggle').data('initialBilling');
        if (initialBilling === 'annual' || initialBilling === 'monthly') {
            currentBilling = initialBilling;
        }

        const $toggle = $('#billingToggle');
        if (currentBilling === 'annual') $toggle.addClass('annual');
        else $toggle.removeClass('annual');

        $('.vmo-billing-label').removeClass('active');
        $(`.vmo-billing-label[data-period="${currentBilling}"]`).addClass('active');
        refreshPlanPrices();
    });

    // === BILLING TOGGLE HANDLER ===
    $(document).on('click', '.vmo-billing-label, .vmo-billing-toggle', function() {
        // Toggle logic
        const $this = $(this);
        if ($this.hasClass('vmo-billing-toggle')) {
            currentBilling = currentBilling === 'monthly' ? 'annual' : 'monthly';
        } else {
            const period = $this.data('period');
            if (period) currentBilling = period;
        }
        
        // Update UI
        const $toggle = $('#billingToggle');
        if (currentBilling === 'annual') $toggle.addClass('annual');
        else $toggle.removeClass('annual');
        
        // Update labels
        $('.vmo-billing-label').removeClass('active');
        $(`.vmo-billing-label[data-period="${currentBilling}"]`).addClass('active');
        
        refreshPlanPrices();
    });

// === PLAN UPGRADE & STRIPE CHECKOUT ===
$(document).on('click', '#vmo_upgrade_plan_btn', function (e) {
    e.stopPropagation();
    $('#vmo-upgrade-menu').toggleClass('open');
});
$(document).on('mouseenter', '.vmo-plan-row', function () {
    $(this).find('.vmo-plan-desc-banner').fadeIn(200);
}).on('mouseleave', '.vmo-plan-row', function () {
    $(this).find('.vmo-plan-desc-banner').fadeOut(200);
});
    // Unified Button Handler (Plans & Top-ups)
    $(document).on('click', '.vmo-plan-btn, .vmo-plan-cta[data-topup]', function (e) {
        e.preventDefault();
        const $btn = $(this);
        
        if (typeof window.vmo_ajax !== 'undefined' && window.vmo_ajax.payments_enabled === false) {
             if (typeof showToast === 'function') showToast('Payments are temporarily disabled.', 'warning');
             else alert('Payments are disabled.');
            return;
        }

        const plan = $btn.data('plan');
        const topup = $btn.data('topup');

        // --- SUBSCRIPTION FLOW ---
        if (plan) {
            const planName = plan.charAt(0).toUpperCase() + plan.slice(1);
            if( confirm(`Subscribe to ${planName} (${currentBilling}) Plan?`) ) {
                 if (typeof showToast === 'function') showToast('Redirecting to Stripe checkout...', 'info');
                 
                 const originalText = $btn.text();
                 $btn.prop('disabled', true).text('Processing...');

                $.post(vmo_ajax.ajaxurl, {
                    action: 'vmo_subscription_checkout',
                    security: vmo_ajax.nonce,
                    plan: plan,
                    billing_cycle: currentBilling
                }, function (res) {
                    if (res.success && res.data.checkout_url) {
                        window.location.href = res.data.checkout_url;
                    } else {
                        if (typeof showToast === 'function') showToast(res.data.message || 'Checkout failed.', 'error');
                        else alert(res.data.message || 'Error occurred.');
                        $btn.prop('disabled', false).text(originalText);
                    }
                }).fail(function(){
                    $btn.prop('disabled', false).text(originalText);
                    if (typeof showToast === 'function') showToast('Network error, please try again.', 'error');
                });
            }
            return;
        }

        // --- TOP-UP FLOW ---
        if (topup) {
            const price = $btn.data('price');
            const label = String(topup).charAt(0).toUpperCase() + String(topup).slice(1);
            
            if( confirm(`Purchase ${label} Add-on for $${price}?`) ) {
                if (typeof showToast === 'function') showToast('Redirecting to Stripe checkout...', 'info');
                
                const originalText = $btn.text();
                $btn.prop('disabled', true).text('Processing...');

                $.post(vmo_ajax.ajaxurl, {
                    action: 'vmo_topup_checkout',
                    security: vmo_ajax.nonce,
                    topup: topup
                }, function (res) {
                    if (res.success && res.data.checkout_url) {
                        window.location.href = res.data.checkout_url;
                    } else {
                        if (typeof showToast === 'function') showToast(res.data.message || 'Checkout failed.', 'error');
                        else alert(res.data.message || 'Error occurred.');
                        $btn.prop('disabled', false).text(originalText);
                    }
                }).fail(function(){
                    $btn.prop('disabled', false).text(originalText);
                    if (typeof showToast === 'function') showToast('Network error, please try again.', 'error');
                });
            }
            return;
        }
    });

// === POST-CHECKOUT RETURN HANDLING (Stripe -> WP Admin) ===
$(function(){
    try {
        const url = new URL(window.location.href);
        const status = url.searchParams.get('payment') || url.searchParams.get('vmo_payment');
        if (!status) return;

        // Clean the URL so the toast doesn't re-trigger on refresh
        url.searchParams.delete('payment');
        url.searchParams.delete('vmo_payment');
        url.searchParams.delete('session_id');
        window.history.replaceState({}, document.title, url.toString());

        if (status === 'success') {
            if (typeof window.showToast === 'function') {
                window.showToast('✅ Purchase successful. Updating your account…', 'success');
            }

            // If a balance refresh function exists, call it (no user-visible “tokens” wording).
            if (typeof window.updateTokenBalance === 'function') {
                let attempts = 0;
                const maxAttempts = 5;
                const tryUpdate = () => {
                    attempts++;
                    window.updateTokenBalance(function(){
                        if (typeof window.showToast === 'function') {
                            window.showToast('✅ Your account is updated.', 'success');
                        }
                    });
                    if (attempts < maxAttempts) {
                        setTimeout(tryUpdate, 1500);
                    }
                };
                tryUpdate();
            }
        } else if (status === 'cancel' || status === 'cancelled') {
            if (typeof window.showToast === 'function') {
                window.showToast('Checkout canceled.', 'warning');
            }
        }
    } catch (e) {
        // No-op
    }
});


    // === THEME/UI TOGGLES ===
    $('#vmo-theme-toggle').off('click').on('click', function () {
        $('body').toggleClass('vmo-light-mode');
        const mode = $('body').hasClass('vmo-light-mode') ? 'light' : 'dark';
        localStorage.setItem('vmo-theme', mode);
    });
    if (localStorage.getItem('vmo-theme') === 'light') {
        $('body').addClass('vmo-light-mode');
    }

    // View Code Toggle
    $('#vmo-view-code-btn').off('click').on('click', function () {
        const isCodeView = $('#vmo-code-view').is(':visible');
        if (!isCodeView) {
            $('#vmo-preview-title').text('Code View');
            $('#vmo-preview-iframe').hide();
            $('#vmo-code-view').show();
        } else {
            $('#vmo-preview-title').text('Live Preview');
            $('#vmo-code-view').hide();
            $('#vmo-preview-iframe').show();
        }
    });

    // === Click Outside to Close Menus (for all popups/menus) ===
    $(document).on('click', function (e) {
        if (!$(e.target).closest('.vmo-load-toggle-group, #vmo_load_project_btn').length) {
            $('#vmo-load-menu').removeClass('open');
        }
        if (!$(e.target).closest('.vmo-upgrade-toggle-group').length) {
            $('#vmo-upgrade-menu').removeClass('open');
        }
    });
    })(jQuery);