(function () {
    if (typeof window.SS_UPGRADE === 'undefined') return;

    const rawPlans = window.SS_UPGRADE.plans || {};
    const i18n = window.SS_UPGRADE.i18n || {};
    const pricingUrl = window.SS_UPGRADE.pricingUrl || '#';
    const currentPlan = window.SS_UPGRADE.currentPlan || 'free';

    const planOrder = ['free', 'pro', 'authority'];

    /* ------------------------------------------------------
     * PLAN INHERITANCE LOGIC
     * Free → Pro → Authority
     * ------------------------------------------------------ */
    function normalizePlans(plans) {
        const normalized = {};

        planOrder.forEach((plan, index) => {
            normalized[plan] = {
                name: plans[plan]?.name || plan,
                benefits: new Set()
            };

            // inherit all lower-level plans
            for (let i = 0; i <= index; i++) {
                (plans[planOrder[i]]?.benefits || []).forEach(b => {
                    normalized[plan].benefits.add(b);
                });
            }
        });

        return normalized;
    }

    const plans = normalizePlans(rawPlans);

    /* ------------------------------------------------------
     * TABLE BUILDER
     * ------------------------------------------------------ */
    function buildCompareHTML(requiredPlan) {
        let html = '<table class="ss-upgrade-table">';

        html += '<thead><tr><th>Feature</th>';
        planOrder.forEach(p => {
            html += `<th>${plans[p].name}</th>`;
        });
        html += '</tr></thead><tbody>';

        // Collect all features from all plans
        let features = new Set();
        planOrder.forEach(p => {
            (rawPlans[p]?.benefits || []).forEach(f => features.add(f));
        });

        // Build rows
        Array.from(features).forEach(feature => {
            html += `<tr><td>${feature}</td>`;

            planOrder.forEach(plan => {
                const ok = plans[plan].benefits.has(feature);
                html += `<td class="${ok ? 'has' : 'no'}">${ok ? '✓' : '❌'}</td>`;
            });

            html += '</tr>';
        });

        html += '</tbody></table>';
        return html;
    }

    /* ------------------------------------------------------
     * OPEN MODAL
     * ------------------------------------------------------ */
    function openModal(featureName, requiredPlan) {
        let modal = document.getElementById('ss-upgrade-modal');
        if (!modal) return;

        document.getElementById('ss-upgrade-title').textContent =
            i18n.title || "This Feature Requires a Higher Plan";

        document.getElementById('ss-upgrade-feature').textContent =
            featureName || '';

        document.getElementById('ss-upgrade-compare').innerHTML =
            buildCompareHTML(requiredPlan);

        let cta = document.getElementById('ss-upgrade-cta');
        cta.href = pricingUrl;
        cta.textContent = requiredPlan === 'authority'
            ? "Upgrade to Authority"
            : "Upgrade Now";

        modal.style.display = 'block';
        modal.setAttribute('aria-hidden', 'false');
        document.documentElement.classList.add('ss-modal-open');
    }

    /* ------------------------------------------------------
     * CLOSE MODAL
     * ------------------------------------------------------ */
    function closeModal() {
        let modal = document.getElementById('ss-upgrade-modal');
        if (!modal) return;

        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
        document.documentElement.classList.remove('ss-modal-open');
    }

    /* ------------------------------------------------------
     * EVENT LISTENERS
     * ------------------------------------------------------ */
    document.addEventListener('click', function (e) {
        let el = e.target;

        while (el && el !== document.body) {
            if (el.matches && el.matches('.ss-locked, [data-required-plan]')) {
                let feature = el.getAttribute('data-feature')
                    || el.getAttribute('data-ss-feature')
                    || el.textContent.trim();

                let neededPlan = el.getAttribute('data-required-plan') || 'pro';

                e.preventDefault();
                openModal(feature, neededPlan);
                return;
            }
            el = el.parentNode;
        }
    });

    document.addEventListener('click', function (e) {
        if (e.target && e.target.hasAttribute('data-ss-close')) {
            e.preventDefault();
            closeModal();
        }
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') closeModal();
    });
})();
