// Tier-gated tabs stay visible to every user but get a dimmed body +
// floating upsell placard when the tier isn't sufficient. No UI hiding
// — consistent with the "gate features, not the app" rule. The dimmed
// body uses the `inert` attribute so tab-through, pointer events, and
// screen readers all skip it.

import {trackEvent, pricingUrlWithContext} from '../js/utils.js';

const TIER_ORDER = ['starter', 'pro', 'venue'];

const LOCKS = {
    dmx: {
        tier: 'pro',
        title: 'DMX output is a Pro feature',
        desc: 'Art-Net and sACN output, unlimited fixtures, and multi-universe support for stage rigs.',
    },
    director: {
        tier: 'pro',
        title: 'Director AI is a Pro feature',
        desc: 'An AI that watches your show, picks moods, and evolves the lights in real time. Bring your own Anthropic API key — Pro/Venue licenses unlock the feature; you bring the meter.',
    },
    midi: {
        tier: 'pro',
        title: 'MIDI control is a Pro feature',
        desc: 'Map any pad or fader on a USB MIDI controller to blackout, scene fire, strobe, movement, and more. Live LED feedback so the controller pulses with the music.',
    },
};

function tierAtLeast(user, required) {
    return TIER_ORDER.indexOf(user) >= TIER_ORDER.indexOf(required);
}

function escapeHtml(s) {
    return String(s).replace(/[&<>"']/g, (c) => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
    }[c]));
}

function capitalize(s) {
    return s ? s[0].toUpperCase() + s.slice(1) : s;
}

function lockTab(tabName, config) {
    const panel = document.querySelector(`[data-tab-panel="${tabName}"]`);
    if (!panel) return;

    // Wrap the existing contents in a dim layer. `inert` keeps keyboard
    // focus, screen readers, and pointer events out — no need to disable
    // controls individually.
    const dim = document.createElement('div');
    dim.className = 'tab-locked-dim';
    dim.inert = true;
    while (panel.firstChild) {
        dim.appendChild(panel.firstChild);
    }
    panel.appendChild(dim);

    const placard = document.createElement('div');
    placard.className = 'tab-locked-placard';
    const pricingUrl = pricingUrlWithContext(`locked_tab_${tabName}`);
    placard.innerHTML = `
        <div class="tab-locked-badge">${escapeHtml(config.tier.toUpperCase())}</div>
        <h3 class="tab-locked-title">${escapeHtml(config.title)}</h3>
        <p class="tab-locked-desc">${escapeHtml(config.desc)}</p>
        <div class="tab-locked-actions">
            <a class="tab-locked-cta" href="${escapeHtml(pricingUrl)}" target="_blank" rel="noopener noreferrer">Get ${escapeHtml(capitalize(config.tier))}</a>
        </div>
        <a class="tab-locked-secondary" href="#" data-jump-tab="settings">Already have a license? &rarr; Settings</a>
    `;
    panel.appendChild(placard);
    panel.classList.add('tab-locked');

    const ctaProps = {surface: 'locked_tab', tab: tabName, tier_required: config.tier};
    trackEvent('upgrade.cta_shown', ctaProps);

    // "Get Pro" opens the pricing page in the external browser. Fires
    // both cta_clicked (funnel intent) and checkout.opened (handoff).
    placard.querySelector('.tab-locked-cta')?.addEventListener('click', () => {
        trackEvent('upgrade.cta_clicked', {...ctaProps, action: 'get_pro'});
        trackEvent('checkout.opened', ctaProps);
    });

    // "→ Settings" click: programmatically flip to the Settings tab via
    // the existing tab-button click path (initTabs already listens there).
    placard.querySelector('[data-jump-tab]')?.addEventListener('click', (e) => {
        e.preventDefault();
        trackEvent('upgrade.cta_clicked', {...ctaProps, action: 'license_entry'});
        const target = e.currentTarget.dataset.jumpTab;
        document.getElementById(`tab-btn-${target}`)?.click();
    });
}

export function initLockedTabs() {
    const tier = window.CONDUCTOR_TIER || 'starter';
    for (const [tabName, config] of Object.entries(LOCKS)) {
        if (!tierAtLeast(tier, config.tier)) {
            lockTab(tabName, config);
        }
    }
}
