// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: assets/js/amai-billing.js
// Description: Billing page JS — global toggle, animated prices, yearly nudge, addon pills, modal, Stripe
// Last Edited: 2026-03-22
// ==================================================

(function ($) {
    'use strict';

    var isYearly = true;

    // ── Stripe ──────────────────────────────────────────────
    var stripe = Stripe(amaiBilling.stripePk);

    // ── Global toggle ────────────────────────────────────────
    function initGlobalToggle() {
        var $toggle = $('#am-global-toggle');
        if (!$toggle.length) return;

        // Start in yearly mode
        setYearly(true, false);

        $toggle.on('click keydown', function (e) {
            if (e.type === 'keydown' && e.which !== 13 && e.which !== 32) return;
            e.preventDefault();
            isYearly = !isYearly;
            setYearly(isYearly, true);
        });
    }

    function setYearly(yearly, animate) {
        isYearly = yearly;

        var $track = $('#am-gtog-track');
        var $pill  = $('#am-gtog-pill');
        var $lblM  = $('#am-lbl-monthly');
        var $lblY  = $('#am-lbl-yearly');

        if (yearly) {
            $track.removeClass('am-monthly').addClass('am-yearly');
            $lblM.removeClass('am-active');
            $lblY.addClass('am-active');
            $pill.removeClass('am-hidden');
        } else {
            $track.removeClass('am-yearly').addClass('am-monthly');
            $lblY.removeClass('am-active');
            $lblM.addClass('am-active');
            $pill.addClass('am-hidden');
        }

        updateAllCards(yearly, animate);
    }

    // ── Card price updates ───────────────────────────────────
    function updateAllCards(yearly, animate) {
        $('.am-plan-card').each(function () {
            var $card   = $(this);
            var slug    = $card.data('slug');

            if (slug === 'free') {
                // Update free card period to match toggle
                $('#am-period-free').text(yearly ? '/yr' : '/mo');
                return;
            }

            var monthly  = parseInt($card.data('monthly'),  10);
            var yearlyP  = parseInt($card.data('yearly'),   10);
            var savings  = $card.data('savings');
            var priceId  = yearly ? $card.data('price-yearly') : $card.data('price-monthly');

            // Update displayed number
            var $inner = $card.find('.am-price-inner');
            var $num   = $card.find('.am-price-num');

            $num.text(yearly ? yearlyP : monthly);

            if (animate) {
                $inner.removeClass('am-animating');
                void $inner[0].offsetWidth; // reflow
                $inner.addClass('am-animating');
                setTimeout(function () { $inner.removeClass('am-animating'); }, 400);
            }

            // Period label
            $card.find('.am-price-period').text(yearly ? '/yr' : '/mo');

            // Savings / nudge line
            var $sl = $card.find('.am-savings-line');
            if (yearly) {
                $sl.html('<span class="am-savings-yearly">2 months free - save $' + savings + '/yr</span>');
            } else {
                var saveAmt = '$' + savings;
                $sl.html(
                    '<div class="am-yearly-nudge" role="button" tabindex="0" aria-label="Switch to yearly and save ' + saveAmt + '">' +
                    '<span class="am-nudge-icon">&#127881;</span>' +
                    '<div>' +
                    '<div class="am-nudge-text">Switch to yearly - get 2 months free</div>' +
                    '<span class="am-nudge-save">You save ' + saveAmt + ' a year</span>' +
                    '</div>' +
                    '</div>'
                );
                // Bind nudge click
                $sl.find('.am-yearly-nudge').on('click keydown', function (e) {
                    if (e.type === 'keydown' && e.which !== 13 && e.which !== 32) return;
                    setYearly(true, true);
                });
            }

            // Update upgrade button price ID
            $card.find('.upgrade-btn').data('plan-id', priceId).attr('data-plan-id', priceId);
        });
    }

    // ── Addon pills ──────────────────────────────────────────
    function initAddonPills() {
        $(document).on('click', '.am-addon-pill', function () {
            $(this).closest('.am-addon-pills').find('.am-addon-pill').removeClass('am-addon-pill--selected');
            $(this).addClass('am-addon-pill--selected');
        });
    }

    // ── Module modal ─────────────────────────────────────────
    function initModal() {
        $(document).on('click', '.am-module-link', function () {
            var target = $(this).data('modal');
            $('#am-modal-' + target).addClass('am-open');
        });

        $(document).on('click', '.am-modal-close', function () {
            $(this).closest('.am-modal-overlay').removeClass('am-open');
        });

        $(document).on('click', '.am-modal-overlay', function (e) {
            if ($(e.target).hasClass('am-modal-overlay')) {
                $(this).removeClass('am-open');
            }
        });

        $(document).on('keydown', function (e) {
            if (e.which === 27) {
                $('.am-modal-overlay.am-open').removeClass('am-open');
            }
        });
    }

    // ── Stripe checkout ──────────────────────────────────────
    // ── Upgrade preview modal ───────────────────────────────────────────
    var upgradeGain = {
        'free→starter':             'You\'re unlocking 5 additional modules - more channels, automations, and tools as we keep building.',
        'free→starter_pro':         'Every channel module we build ships to you automatically. Premium AI features like image generation and analytics require Unlimited AI.',
        'free→unlimited_ai':        'Every channel module, now and as we build them, plus the full AI intelligence layer - image generation, content repurposing, analytics, and review responder.',
        'starter→starter_pro':      'Every channel module we build ships to you automatically - no upgrades, no cherry-picking.',
        'starter→unlimited_ai':     'Every channel module, now and as we build them, plus AI image generation, content repurposing across every channel, analytics hub, and review responder.',
        'starter_pro→unlimited_ai': 'You\'re adding the full premium AI layer - image generation, content repurposing across every channel, analytics, and review responder.',
    };

    var $upgradeModal  = $('#am-modal-upgrade');
    var pendingUpgrade = null;

    function fireCheckout(planId, addonId, $btn) {
        $btn.prop('disabled', true).text('Loading…');
        var postData = {
            action:      'amai_create_checkout_session',
            plan_id:     planId,
            _ajax_nonce: amaiBilling.nonce
        };
        if (addonId !== '') {
            postData.addon_id = addonId;
        }
        $.ajax({
            url:  amaiBilling.ajaxurl,
            type: 'POST',
            data: postData,
            success: function (response) {
                if (response.success && response.data.session_id) {
                    stripe.redirectToCheckout({ sessionId: response.data.session_id })
                        .then(function (result) {
                            if (result.error) {
                                alert('Stripe error: ' + result.error.message);
                                $btn.prop('disabled', false).text($btn.data('orig-text'));
                            }
                        });
                } else {
                    var msg = (response.data && response.data.message)
                        ? response.data.message
                        : 'Unknown error. Please try again or contact support.';
                    alert('Checkout failed: ' + msg);
                    $btn.prop('disabled', false).text($btn.data('orig-text'));
                }
            },
            error: function (xhr, status, error) {
                alert('Request failed: ' + error);
                $btn.prop('disabled', false).text($btn.data('orig-text'));
            }
        });
    }

    function initCheckout() {
        $(document).on('click', '.upgrade-btn', function (e) {
            e.preventDefault();
            var $btn     = $(this);
            var planId   = $btn.data('plan-id');
            var $card    = $btn.closest('.am-plan-card');
            var $selPill = $card.find('.am-addon-pill--selected');
            var addonId  = '';
            var target   = $card.data('slug') || '';
            var current  = $('#amai-billing-root').data('current-plan') || '';

            if ($selPill.length) {
                addonId = isYearly
                    ? ($selPill.data('price-yearly') || '')
                    : ($selPill.data('price-monthly') || '');
            }
            if (!planId) {
                alert('No plan selected. Please try again.');
                return;
            }

            var gainKey  = current + '→' + target;
            var gainText = upgradeGain[gainKey] || 'You\'ll get everything in your current plan plus everything ' + $card.find('.am-plan-name').text() + ' adds on top.';
            var price    = isYearly
                ? ('$' + $card.data('yearly') + '/yr, billed today')
                : ('$' + $card.data('monthly') + '/mo, billed today');

            $('#am-up-plan-name').text($card.find('.am-plan-name').text());
            $('#am-up-gain-text').text(gainText);
            $('#am-up-price-note').text(price);

            pendingUpgrade = { planId: planId, addonId: addonId, btn: $btn };
            $upgradeModal.addClass('am-open');
        });

        $('#am-confirm-upgrade').on('click', function () {
            if (!pendingUpgrade) { return; }
            $upgradeModal.removeClass('am-open');
            fireCheckout(pendingUpgrade.planId, pendingUpgrade.addonId, pendingUpgrade.btn);
            pendingUpgrade = null;
        });

        $(document).on('click', '.am-btn-keep-upgrade', function () {
            $upgradeModal.removeClass('am-open');
            pendingUpgrade = null;
            showNotice('Whenever you\'re ready - your content keeps running in the meantime.', 'info');
        });

        $(document).on('click', '#am-modal-upgrade', function (e) {
            if ($(e.target).is('#am-modal-upgrade')) {
                $upgradeModal.removeClass('am-open');
                pendingUpgrade = null;
            }
        });
    }

    // ── Addon pills — show price line when selected ──────────
    function initAddonPricing() {
        $(document).on('click', '.am-addon-pill', function () {
            var $pill    = $(this);
            var $section = $pill.closest('.am-addon-section');
            var $line    = $section.find('.am-addon-price-line');
            var priceMo  = parseInt($pill.data('price-mo'), 10) || 0;
            var priceYr  = parseInt($pill.data('price-yr'), 10) || 0;
            var seats    = parseInt($pill.data('seats'), 10) || 0;

            if (seats === 0) {
                $line.text('');
            } else if (isYearly) {
                $line.text('+$' + priceYr.toLocaleString() + '/yr for ' + seats + ' additional activations');
            } else {
                $line.text('+$' + priceMo.toLocaleString() + '/mo for ' + seats + ' additional activations');
            }
        });
    }

    // ── Cancel subscription ──────────────────────────────────
    function initCancel() {
        var $cancelModal   = $('#am-modal-cancel');
        var $confirmBtn    = $('#am-confirm-cancel');
        var cancelNonce      = '';
        var subId            = '';
        var isDowngradeFlow  = false;

        $(document).on('click', '.am-btn-cancel, .am-btn-downgrade[data-target="free"]', function () {
            var $btn       = $(this);
            cancelNonce    = $btn.data('nonce');
            var previewNonce = $btn.data('preview-nonce');
            subId          = $btn.data('sub-id');
            var planName    = $btn.data('plan-name') || 'your plan';
            var isDowngrade = $btn.hasClass('am-btn-downgrade');
            isDowngradeFlow = isDowngrade;
            var modalTitle  = isDowngrade ? 'Downgrade to ' + planName + '?' : 'Cancel ' + planName + '?';

            $('#am-cancel-title').text(modalTitle);
            $confirmBtn.text(isDowngrade ? 'Yes, downgrade' : 'Yes, cancel now');
            var $cancelSub = $('#am-cancel-sub');
            if (isDowngrade) {
                $cancelSub.text('Your plan changes immediately. Facebook and Instagram stay active.');
            } else {
                $cancelSub.text('We calculate exactly what you haven\'t used and send it straight back.');
            }
            $('#am-refund-loading').show();
            $('#am-refund-amount').hide();
            $('#am-refund-label').hide();
            $('#am-refund-note').text('');
            $confirmBtn.prop('disabled', true);

            $cancelModal.addClass('am-open');

            // Fetch refund preview
            $.ajax({
                url:  amaiBilling.restUrl + 'amai/v1/refund-preview',
                type: 'GET',
                data: { _wpnonce: previewNonce },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', previewNonce);
                },
                success: function (response) {
                    $('#am-refund-loading').hide();
                    var amount    = response.refund_amount || 0;
                    var currency  = (response.currency || 'usd').toUpperCase();
                    var formatted = response.formatted || ('$' + (amount / 100).toFixed(2));

                    if (amount > 0) {
                        $('#am-refund-amount').text(formatted).show();
                        $('#am-refund-label').show();
                        $('#am-refund-note').text('We send it back immediately. No questions. No waiting. That\'s just how we think it should work.');
                    } else {
                        $('#am-refund-amount').text('$0.00').show();
                        $('#am-refund-label').text('No refund due for this billing period').show();
                        $('#am-refund-note').text('Your access continues until the end of your current period.');
                    }
                    $confirmBtn.prop('disabled', false);
                },
                error: function () {
                    $('#am-refund-loading').text('Could not calculate refund - cancellation will still issue any applicable refund automatically.');
                    $confirmBtn.prop('disabled', false);
                }
            });
        });

        // Confirm cancel
        $confirmBtn.on('click', function () {
            $confirmBtn.prop('disabled', true).text('Cancelling…');

            $.ajax({
                url:  amaiBilling.restUrl + 'amai/v1/cancel-subscription',
                type: 'POST',
                data: JSON.stringify({ _wpnonce: cancelNonce, sub_id: subId }),
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', cancelNonce);
                },
                success: function () {
                    $cancelModal.removeClass('am-open');
                    window.location.href = amaiBilling.billingUrl + '&upgrade=cancelled';
                },
                error: function () {
                    $confirmBtn.prop('disabled', false).text(isDowngradeFlow ? 'Yes, downgrade' : 'Yes, cancel now');
                    alert('Something went wrong. Please try again or contact support.');
                }
            });
        });

        // Close modal keeps plan
        $(document).on('click', '.am-btn-keep', function () {
            $cancelModal.removeClass('am-open');
        });
    }

    // ── Downgrade to paid plan ───────────────────────────────────────────
    var downgradeLoss = {
        'agency→unlimited_ai':      'You\'ll lose the multi-client dashboard, white-label UI, client reports, and priority support. All your content and channel connections stay intact.',
        'agency→starter_pro':       'You\'ll lose the multi-client dashboard, white-label UI, AI image generation, content repurposing, analytics, and review responder. Facebook and Instagram stay active. Your posts and channel connections stay intact.',
        'agency→starter':           'You\'ll lose the multi-client dashboard, white-label UI, all premium AI modules, and access to channels beyond your first five. Facebook and Instagram stay active. Your existing posts stay intact.',
        'agency→free':              'You\'ll lose all channels beyond Facebook and Instagram, the multi-client dashboard, white-label UI, and every premium AI module. You keep your API key setup and your post history.',
        'unlimited_ai→starter_pro': 'You\'ll lose AI image generation, content repurposing across channels, the analytics hub, and the review responder. Facebook and Instagram stay active. All your channels and posts stay exactly as they are.',
        'unlimited_ai→starter':     'You\'ll lose all premium AI modules and access to channels beyond your first five. Facebook and Instagram stay active. Your posts and API key setup stay intact.',
        'unlimited_ai→free':        'You\'ll lose all channels beyond Facebook and Instagram and every premium AI module. You keep your API key, your post history, and your approval workflow.',
        'starter_pro→starter':      'You\'ll lose access to channels beyond your first five. Any additional channel connections will be paused until you upgrade. Facebook and Instagram stay active.',
        'starter_pro→free':         'You\'ll lose access to channels beyond Facebook and Instagram, plus all additional modules. Your posts, API key and scheduling stay intact on your remaining channels.',
        'starter→free':             'You\'ll lose access to channels beyond Facebook and Instagram. Your posts, API key and scheduling stay intact on your remaining channels.',
    };

    var $downgradeModal    = $('#am-modal-downgrade');
    var activeDowngradeBtn = null;

    function initDowngrade() {
        $(document).on('click', '.am-btn-downgrade.secondary', function () {
            var $btn     = $(this);
            var target   = $btn.data('target');
            var planName = $btn.data('plan-name');
            var current  = $('#amai-billing-root').data('current-plan') || '';

            var lossKey  = current + '→' + target;
            var lossText = downgradeLoss[lossKey] || 'Your plan will change immediately. Features not included in ' + planName + ' will no longer be available.';

            $('#am-dg-plan-name').text(planName);
            $('#am-dg-loss-text').text(lossText);
            activeDowngradeBtn = $btn;
            $downgradeModal.addClass('am-open');
        });

        $('#am-confirm-downgrade').on('click', function () {
            if (!activeDowngradeBtn) { return; }

            var $btn     = activeDowngradeBtn;
            var target   = $btn.data('target');
            var planName = $btn.data('plan-name');
            var planId   = $btn.data('plan-id');
            var nonce    = $btn.data('nonce');

            $downgradeModal.removeClass('am-open');
            $btn.prop('disabled', true).text('Downgrading…');

            $.ajax({
                url:  amaiBilling.restUrl + 'amai/v1/downgrade-plan',
                type: 'POST',
                data: JSON.stringify({ _wpnonce: nonce, target_plan: target, plan_id: planId }),
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', nonce);
                },
                success: function () {
                    window.location.reload();
                },
                error: function () {
                    $btn.prop('disabled', false).text('Downgrade to ' + planName + ' →');
                    alert('Something went wrong. Please try again or contact support.');
                }
            });
        });

        $(document).on('click', '.am-btn-keep-dg', function () {
            $downgradeModal.removeClass('am-open');
            activeDowngradeBtn = null;
            showNotice('Smart move - everything stays exactly as it is.', 'info');
        });

        $(document).on('click', '#am-modal-downgrade', function (e) {
            if ($(e.target).is('#am-modal-downgrade')) {
                $downgradeModal.removeClass('am-open');
                activeDowngradeBtn = null;
            }
        });
    }

    // ── Notice helper ────────────────────────────────────────────────────────
    function showNotice(msg, type) {
        $('.am-bill-notice').remove();
        var cls = 'am-bill-notice ' + (type || 'info');
        var $n  = $('<div class="' + cls + '">' + msg + '</div>');
        $('#amai-billing-root .am-bill-header').after($n);
        setTimeout(function () {
            $n.css({ transition: 'opacity 1s ease', opacity: '0' });
            setTimeout(function () { $n.remove(); }, 1000);
        }, 7000);
    }

    // ── Notice auto-fade ─────────────────────────────────────
    function initNoticeFade() {
        var $notice = $('.am-bill-notice');
        if (!$notice.length) return;
        setTimeout(function () {
            $notice.css({ transition: 'opacity 1s ease', opacity: '0' });
            setTimeout(function () { $notice.remove(); }, 1000);
        }, 7000);
    }

    // ── Boot ─────────────────────────────────────────────────
    $(document).ready(function () {
        if (!$('#amai-billing-root').length) return;
        initGlobalToggle();
        initAddonPills();
        initAddonPricing();
        initModal();
        initCheckout();
        initCancel();
        initDowngrade();
        initNoticeFade();
    });

}(jQuery));