/**
 * Account page: Stripe checkout modal, interval toggle, top-up price.
 *
 * Expects `ttsAccount` global from wp_localize_script:
 *   - ajaxurl: admin-ajax.php URL
 *   - nonce: mementor_tts_nonce
 *   - stripeKey: Stripe publishable key
 */
(function ($) {
    'use strict';

    var stripe = null;
    var checkoutInstance = null;

    // ----- Stripe init -----

    function initStripe() {
        if (stripe || !window.ttsAccount || !window.ttsAccount.stripeKey) return;
        if (typeof Stripe === 'undefined') return;
        stripe = Stripe(window.ttsAccount.stripeKey);
    }

    // ----- Checkout modal -----

    function openCheckout(clientSecret) {
        initStripe();
        if (!stripe) {
            alert('Stripe is not loaded. Please refresh the page.');
            return;
        }

        var $overlay = $('#tts-checkout-overlay');
        var $container = $('#tts-checkout-container');

        $overlay.addClass('active');
        $container.html(''); // clear previous

        stripe.createEmbeddedCheckoutPage({ clientSecret: clientSecret }).then(function (checkout) {
            checkoutInstance = checkout;
            checkout.mount('#tts-checkout-container');
        });
    }

    function closeCheckout() {
        if (checkoutInstance) {
            checkoutInstance.destroy();
            checkoutInstance = null;
        }
        $('#tts-checkout-overlay').removeClass('active');
    }

    // ----- Checkout triggers -----

    function handleCheckoutClick(e) {
        e.preventDefault();
        var $btn = $(this);
        var type = $btn.data('checkout-type');
        var originalText = $btn.text();

        $btn.prop('disabled', true).text('Loading\u2026');

        var ajaxData = {
            nonce: window.ttsAccount.nonce
        };

        if (type === 'subscription') {
            ajaxData.action = 'tts_checkout_subscription';
            var plan = $btn.data('plan');
            ajaxData.tier_id = $('.tts-upgrade-select[data-plan="' + plan + '"]').val();
            ajaxData.interval = getCurrentInterval();
        } else if (type === 'credits') {
            ajaxData.action = 'tts_checkout_credits';
            ajaxData.package_id = $('#tts-topup-select').val();
        }

        $.post(window.ttsAccount.ajaxurl, ajaxData, function (response) {
            $btn.prop('disabled', false).text(originalText);

            if (!response.success) {
                alert(response.data && response.data.message ? response.data.message : 'Something went wrong.');
                return;
            }

            // If plan was swapped (no checkout needed), reload page
            if (response.data && response.data.swapped) {
                window.location.href = window.ttsAccount.accountUrl + '&refresh=1&upgraded=1';
                return;
            }

            // Open Stripe embedded checkout
            if (response.data && response.data.client_secret) {
                openCheckout(response.data.client_secret);
            }
        }).fail(function () {
            $btn.prop('disabled', false).text(originalText);
            alert('Request failed. Please try again.');
        });
    }

    // ----- Interval toggle -----

    var currentInterval = 'yearly';

    function getCurrentInterval() {
        return currentInterval;
    }

    function handleIntervalToggle() {
        // Flip the interval
        currentInterval = currentInterval === 'yearly' ? 'monthly' : 'yearly';

        // Toggle switch state
        $('#tts-interval-switch').toggleClass('active', currentInterval === 'yearly');

        // Toggle active label
        $('.tts-interval-label').removeClass('active');
        $('.tts-interval-label[data-interval="' + currentInterval + '"]').addClass('active');

        // Update all upgrade dropdown prices
        $('.tts-upgrade-select').each(function () {
            updateUpgradePrice($(this));
        });

        // Show/hide save badge
        if (currentInterval === 'yearly') {
            $('.tts-save-badge').show();
        } else {
            $('.tts-save-badge').hide();
        }
    }

    function formatPrice(price) {
        return price % 1 === 0 ? '$' + price.toFixed(0) : '$' + price.toFixed(2);
    }

    function updateUpgradePrice($select) {
        if (!$select || !$select.length) return;
        var plan = $select.data('plan');
        var $option = $select.find(':selected');
        if (!$option.length) return;
        var price = parseFloat($option.data('price-' + currentInterval));
        $('.tts-upgrade-price[data-plan="' + plan + '"]').text(formatPrice(price));
        var billed = currentInterval === 'yearly' ? $option.data('billed-yearly') : '';
        $('.tts-upgrade-billed[data-plan="' + plan + '"]').text(billed || '');
    }

    // ----- Top-up price -----

    function handleTopUpChange() {
        var $option = $(this).find(':selected');
        var price = parseFloat($option.data('price'));
        $('#tts-topup-price').text(formatPrice(price));
    }

    // ----- Checkout modal close + completion detection -----

    function setupCheckoutObserver() {
        // Poll for iframe navigation to detect checkout completion
        var $container = $('#tts-checkout-container');
        var pollInterval = setInterval(function () {
            if (!$('#tts-checkout-overlay').hasClass('active')) {
                clearInterval(pollInterval);
                return;
            }
            var iframe = $container.find('iframe')[0];
            if (!iframe) return;
            try {
                var iframeSrc = iframe.contentWindow.location.href;
                if (iframeSrc && iframeSrc.indexOf('checkout/return') !== -1) {
                    clearInterval(pollInterval);
                    setTimeout(function () {
                        closeCheckout();
                        window.location.href = window.ttsAccount.accountUrl + '&refresh=1&success=1';
                    }, 2000);
                }
            } catch (e) {
                // Cross-origin — expected before redirect
            }
        }, 1000);
    }

    // ----- Init -----

    $(function () {
        // Checkout triggers
        $(document).on('click', '.tts-checkout-trigger', handleCheckoutClick);

        // Modal close
        $('#tts-checkout-close').on('click', closeCheckout);
        $('#tts-checkout-overlay').on('click', function (e) {
            if (e.target === this) closeCheckout();
        });

        // Interval toggle (switch + labels)
        $(document).on('click', '#tts-interval-switch, .tts-interval-label', handleIntervalToggle);

        // Top-up dropdown
        $('#tts-topup-select').on('change', handleTopUpChange);

        // Upgrade dropdowns (one per plan)
        $(document).on('change', '.tts-upgrade-select', function () {
            updateUpgradePrice($(this));
        });

        // Start polling when modal opens
        var observer = new MutationObserver(function () {
            if ($('#tts-checkout-overlay').hasClass('active')) {
                setupCheckoutObserver();
            }
        });
        var overlay = document.getElementById('tts-checkout-overlay');
        if (overlay) {
            observer.observe(overlay, { attributes: true, attributeFilter: ['class'] });
        }

        // Success flash (after redirect back from checkout)
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success') === '1') {
            // Show a temporary success notice
            var $notice = $('<div class="notice notice-success is-dismissible mementor-tts-notice"><p>Payment successful! Your account has been updated.</p></div>');
            $('.tts-account-page').prepend($notice);
        }
        if (urlParams.get('upgraded') === '1') {
            var $notice2 = $('<div class="notice notice-success is-dismissible mementor-tts-notice"><p>Plan upgraded successfully!</p></div>');
            $('.tts-account-page').prepend($notice2);
        }
    });

})(jQuery);
