// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /assets/js/amai-results.js
// Description: Results page -- async Stripe fetch and business type switcher - NUCLEAR+++
// Last Edited: 2026-05-19
// ==================================================
(function () {
    var data = typeof amaiResults !== 'undefined' ? amaiResults : {};

    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    // ── Stripe subscription fetch ─────────────────────────────────────
    function fetchSubscription() {
        if (data.mrrOverride !== null && data.mrrOverride !== undefined) {
            var mrrEl = document.getElementById('amai-results-mrr');
            if (mrrEl) { mrrEl.textContent = '$' + parseFloat(data.mrrOverride).toFixed(2); }
            var metaEl = document.getElementById('amai-results-mrr-meta');
            if (metaEl) { metaEl.textContent = '100% discount applied'; }
            return;
        }
        if (!data.hasStripe) { return; }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', data.ajaxUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) { return; }
            if (xhr.status !== 200) { return; }
            var resp;
            try { resp = JSON.parse(xhr.responseText); } catch (e) { return; }
            if (!resp.success || !resp.data) { return; }
            var d = resp.data;
            var mrrEl = document.getElementById('amai-results-mrr');
            if (mrrEl) { mrrEl.innerHTML = escHtml(d.mrr_formatted || '$0.00'); }
            var subEl = document.getElementById('amai-results-subscribers');
            if (subEl && d.subscriber_count !== undefined) { subEl.textContent = d.subscriber_count; }
            var metaEl = document.getElementById('amai-results-mrr-meta');
            if (metaEl) {
                var metaText = d.billing_period || '';
                if (d.plan_name) {
                    metaText = escHtml(d.plan_name) + (metaText ? ' &middot; ' + escHtml(metaText) : '');
                }
                metaEl.innerHTML = metaText || 'Active subscription';
            }
        };
        var body = 'action=amai_dashboard_subscription&_ajax_nonce=' + encodeURIComponent(data.nonce || '');
        if (data.subId) { body += '&sub_id=' + encodeURIComponent(data.subId); }
        if (data.custId) { body += '&cust_id=' + encodeURIComponent(data.custId); }
        xhr.send(body);
    }

    // ── Business type switcher ────────────────────────────────────────
    function savingIndicator(show) {
        var el = document.getElementById('amai-bt-saving');
        if (!el) { return; }
        el.style.opacity = show ? '1' : '0';
    }

    function setBusinessType(type) {
        savingIndicator(true);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', data.ajaxUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) { return; }
            savingIndicator(false);
            if (xhr.status !== 200) { return; }
            var resp;
            try { resp = JSON.parse(xhr.responseText); } catch (e) { return; }
            if (!resp.success) { return; }
            // Reload to reflect the new business type sections
            window.location.reload();
        };
        var body = 'action=amai_set_business_type&_ajax_nonce=' + encodeURIComponent(data.btNonce || '')
            + '&business_type=' + encodeURIComponent(type);
        xhr.send(body);
    }

    function initSwitcher() {
        var buttons = document.querySelectorAll('.amai-results-bt-btn');
        buttons.forEach(function (btn) {
            btn.addEventListener('click', function () {
                var type = btn.getAttribute('data-type');
                if (!type) { return; }
                setBusinessType(type);
            });
        });
        var resetBtn = document.getElementById('amai-bt-reset');
        if (resetBtn) {
            resetBtn.addEventListener('click', function () {
                setBusinessType('auto');
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            fetchSubscription();
            initSwitcher();
        });
    } else {
        fetchSubscription();
        initSwitcher();
    }
}());