/**
 * license.js — License upgrade flow.
 *
 * 3-step guided upgrade: current tier → target tier picker → activate.
 * Backed by /api/license/status, /api/license/activate, /api/license/deactivate,
 * /api/license/sync.
 *
 * Cut 24 (Phase H): License upgrade flow polish.
 */

import { api, post } from '../api.js';
import { S, PLAN_CAPS } from '../state.js';

const $ = id => document.getElementById(id);
const esc = s => s == null ? '' : String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');

/* ── Plan definitions ─────────────────────────────────────────────────────── */

const PLANS = [
    {
        id: 'free',
        label: 'Free',
        price: '$0',
        period: 'forever',
        color: 'var(--text-muted)',
        features: [
            `${(PLAN_CAPS.free.maxMemoryEntries).toLocaleString()} memory entries`,
            `${PLAN_CAPS.free.maxOperatives} operative`,
            'Foundation skills',
            'Local-only storage',
        ],
    },
    {
        id: 'pro',
        label: 'Pro',
        price: '$20',
        period: 'per month',
        color: 'var(--accent)',
        features: [
            `${(PLAN_CAPS.pro.maxMemoryEntries).toLocaleString()} memory entries`,
            `${PLAN_CAPS.pro.maxOperatives} operatives`,
            'All built-in skills',
            'Darwin auto-propose',
        ],
    },
    {
        id: 'team',
        label: 'Team',
        price: '$80',
        period: 'per month',
        color: 'var(--secondary)',
        features: [
            `${(PLAN_CAPS.team.maxMemoryEntries / 1000).toLocaleString()}K memory entries`,
            'Unlimited operatives',
            'Custom skills',
            'Darwin auto-propose',
        ],
    },
    {
        id: 'enterprise',
        label: 'Enterprise',
        price: 'Contact us',
        period: '',
        color: 'var(--violet)',
        features: [
            'Unlimited memory',
            'Unlimited operatives',
            'Registry skills',
            'Dedicated support',
        ],
    },
];

/* ── State ─────────────────────────────────────────────────────────────────── */

let _step       = 1;   // 1 = current plan, 2 = pick target, 3 = activate key
let _targetPlan = null;
let _statusData = null;

/* ── Load ─────────────────────────────────────────────────────────────────── */

export async function load() {
    const container = $('license-container');
    if (!container) return;
    container.innerHTML = `<div class="empty"><div class="empty-title">Loading license…</div></div>`;

    const data = await api('/api/license/status', 10_000);
    _statusData = data ?? {};
    S.license   = _statusData;
    _step = 1;
    render();
}

/* ── Render ───────────────────────────────────────────────────────────────── */

export function render() {
    const container = $('license-container');
    if (!container) return;

    const status    = _statusData?.status ?? {};
    const pcu       = _statusData?.pcu ?? {};
    const formatted = _statusData?.formatted ?? {};
    const tier      = String(status.tier ?? 'free').toLowerCase();

    container.innerHTML = `
        <div class="license-wrap">

            <!-- Step indicator -->
            <div class="license-steps">
                ${[1, 2, 3].map(n => `
                    <div class="license-step ${_step === n ? 'active' : _step > n ? 'done' : ''}">
                        <div class="license-step-dot">${_step > n ? '✓' : n}</div>
                        <div class="license-step-label">${['Current plan', 'Choose plan', 'Activate'][n - 1]}</div>
                    </div>
                    ${n < 3 ? '<div class="license-step-connector"></div>' : ''}
                `).join('')}
            </div>

            <!-- Step 1: current plan overview -->
            ${_step === 1 ? _renderStep1(tier, status, pcu, formatted) : ''}

            <!-- Step 2: plan picker -->
            ${_step === 2 ? _renderStep2(tier) : ''}

            <!-- Step 3: activate -->
            ${_step === 3 ? _renderStep3(tier) : ''}

        </div>
    `;

    _attachHandlers();
}

/* ── Step renderers ───────────────────────────────────────────────────────── */

function _renewalNagBanner(status) {
    if (!status.expiresAt) return '';
    const msLeft = new Date(status.expiresAt).getTime() - Date.now();
    const daysLeft = Math.ceil(msLeft / 86_400_000);
    if (daysLeft > 14) return '';
    const urgent = daysLeft <= 3;
    const color = urgent ? 'var(--bad)' : 'var(--warn)';
    const bg    = urgent ? 'oklch(65% 0.22 25 / 8%)' : 'oklch(80% 0.16 80 / 8%)';
    const msg   = daysLeft <= 0
        ? 'Your license has expired. Renew to restore full access.'
        : `Your license expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}. Renew to keep uninterrupted access.`;
    return `
        <div style="background:${bg};border:1px solid ${color};border-radius:8px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;gap:12px">
            <span style="font-size:18px">${urgent ? '🚨' : '⚠️'}</span>
            <div style="flex:1">
                <div style="font:600 13px ui-sans-serif;color:${color};margin-bottom:3px">${urgent ? 'License expiring!' : 'Renewal reminder'}</div>
                <div style="font-size:12px;color:var(--text-muted)">${esc(msg)}</div>
            </div>
            <button class="btn btn-sm" id="lic-renew-nag-btn"
                    style="border-color:${color};color:${color};flex-shrink:0;white-space:nowrap">
                Renew now
            </button>
        </div>`;
}

function _trialActivationBanner(status) {
    if (!status?.trialPhase) return '';
    const motion = status.activationMotion ?? {};
    const required = status.activationRequired === true || status.trialPhase === 'activation' || status.trialPhase === 'expired';
    const days = typeof status.trialDaysRemaining === 'number' ? status.trialDaysRemaining : null;
    const color = status.trialPhase === 'expired' ? 'var(--bad)' : required ? 'var(--warn)' : 'var(--accent)';
    const bg = status.trialPhase === 'expired'
        ? 'oklch(65% 0.22 25 / 8%)'
        : required ? 'oklch(80% 0.16 80 / 8%)' : 'oklch(70% 0.16 250 / 8%)';
    const title = motion.title ?? (required ? 'License required' : '3-day no-license grace');
    const message = motion.message ?? (required
        ? 'The no-license grace period is over. Request a license from the account page or email adarsh@nexus-prime.cfd; the team will share licenses within 24 hours.'
        : 'First 3 days run without a license. Request a license before day 4; the team will share licenses within 24 hours.');
    const remaining = days == null ? '' : `<div style="font-size:11px;color:var(--text-muted);margin-top:4px">${days} day${days === 1 ? '' : 's'} remaining</div>`;
    return `
        <div style="background:${bg};border:1px solid ${color};border-radius:8px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap">
            <div style="flex:1;min-width:220px">
                <div style="font:600 13px ui-sans-serif;color:${color};margin-bottom:3px">${esc(title)}</div>
                <div style="font-size:12px;color:var(--text-muted);line-height:1.45">${esc(message)}</div>
                ${remaining}
            </div>
            <button class="btn btn-primary btn-sm" id="lic-trial-account-btn" style="flex-shrink:0;white-space:nowrap">Request license</button>
            <button class="btn btn-sm" id="lic-trial-activate-btn" style="flex-shrink:0;white-space:nowrap">Activate key</button>
            <button class="btn btn-sm" id="lic-trial-email-btn" style="flex-shrink:0;white-space:nowrap">Email team</button>
        </div>`;
}

function _renderStep1(tier, status, pcu, formatted) {
    const plan = PLANS.find(p => p.id === tier) ?? PLANS[0];
    const valid = status.valid !== false;

    return `
        <div class="license-card card">
            ${_trialActivationBanner(status)}

            <!-- Renewal nag (shown when expiry < 14 days) -->
            ${_renewalNagBanner(status)}

            <div class="license-current-hd">
                <div>
                    <div class="license-current-tier" style="color:${plan.color}">${esc(plan.label)}</div>
                    <div style="font-size:var(--text-sm);color:var(--text-muted);margin-top:2px">
                        ${valid ? '<span style="color:var(--ok)">✓ Active</span>' : '<span style="color:var(--bad)">⚠ Inactive</span>'}
                        ${status.expiresAt ? ` · Expires ${new Date(status.expiresAt).toLocaleDateString()}` : ''}
                    </div>
                </div>
                <div class="license-price">${esc(plan.price)}<span style="font-size:var(--text-sm);color:var(--text-muted)">${plan.period ? ' / ' + plan.period : ''}</span></div>
            </div>

            <!-- Usage bars from PCU -->
            ${_renderUsageBars(pcu, formatted)}

            <!-- Features list -->
            <div class="license-features">
                ${plan.features.map(f => `<div class="license-feature-row">✓ ${esc(f)}</div>`).join('')}
            </div>

            <!-- Actions -->
            <div class="license-actions">
                ${tier !== 'enterprise' ? `<button class="btn btn-primary btn-sm" id="lic-upgrade-btn">Upgrade plan</button>` : ''}
                <button class="btn btn-sm" id="lic-sync-btn">Sync license</button>
                ${valid ? `<button class="btn btn-sm" id="lic-deactivate-btn" style="color:var(--bad)">Deactivate</button>` : ''}
            </div>
            <div id="lic-step1-status" class="license-status-msg"></div>
        </div>
    `;
}

function _renderStep2(currentTier) {
    return `
        <div class="license-picker">
            <div style="font-size:var(--text-sm);color:var(--text-muted);margin-bottom:16px">
                Select the plan you want to upgrade to:
            </div>
            <div class="license-plan-grid">
                ${PLANS.map(p => `
                    <div class="license-plan-card ${p.id === currentTier ? 'current' : ''} ${_targetPlan === p.id ? 'selected' : ''}"
                         data-plan="${p.id}" role="button" tabindex="0">
                        <div class="license-plan-name" style="color:${p.color}">${esc(p.label)}</div>
                        <div class="license-plan-price">${esc(p.price)}</div>
                        ${p.period ? `<div class="license-plan-period">${esc(p.period)}</div>` : ''}
                        <div class="license-plan-features">
                            ${p.features.map(f => `<div class="license-plan-feature">✓ ${esc(f)}</div>`).join('')}
                        </div>
                        ${p.id === currentTier ? `<div class="license-plan-badge">Current</div>` : ''}
                    </div>
                `).join('')}
            </div>
            <div class="license-actions" style="margin-top:16px">
                <button class="btn btn-sm" id="lic-back-btn">← Back</button>
                ${_targetPlan && _targetPlan !== currentTier
                    ? `<button class="btn btn-primary btn-sm" id="lic-continue-btn">Continue with ${esc(PLANS.find(p=>p.id===_targetPlan)?.label ?? _targetPlan)}</button>`
                    : ''}
            </div>
        </div>
    `;
}

function _renderStep3(currentTier) {
    const plan = PLANS.find(p => p.id === _targetPlan) ?? PLANS[1];
    return `
        <div class="license-card card">
            <div class="license-activate-hd">
                <div class="license-activate-title">Activate ${esc(plan.label)} plan</div>
                <div style="font-size:var(--text-sm);color:var(--text-muted);margin-top:4px">
                    Enter your license key from
                    <a href="https://nexus-prime.cfd/license" target="_blank" rel="noopener"
                       style="color:var(--accent);text-decoration:underline;text-underline-offset:2px">
                        nexus-prime.cfd
                    </a>
                </div>
            </div>

            <div style="margin:16px 0">
                <label class="form-label" for="lic-key-input">License key <span class="req">*</span></label>
                <input id="lic-key-input" class="form-input"
                       type="text" placeholder="NXP-XXXX-XXXX-XXXX"
                       autocomplete="off" spellcheck="false">
            </div>

            <div class="license-actions">
                <button class="btn btn-sm" id="lic-back-btn">← Back</button>
                <button class="btn btn-primary btn-sm" id="lic-activate-btn">Activate license</button>
            </div>
            <div id="lic-step3-status" class="license-status-msg"></div>
        </div>
    `;
}

/* ── Usage bars ───────────────────────────────────────────────────────────── */

function _renderUsageBars(pcu, formatted) {
    if (!pcu || Object.keys(pcu).length === 0) return '';
    const bars = [];
    if (pcu.memoryEntries != null && pcu.maxMemoryEntries != null) {
        const pct = Math.min(100, (pcu.memoryEntries / pcu.maxMemoryEntries) * 100);
        bars.push({ label: 'Memory entries', used: pcu.memoryEntries, max: pcu.maxMemoryEntries, pct });
    }
    if (pcu.operatives != null && pcu.maxOperatives != null && isFinite(pcu.maxOperatives)) {
        const pct = Math.min(100, (pcu.operatives / pcu.maxOperatives) * 100);
        bars.push({ label: 'Operatives', used: pcu.operatives, max: pcu.maxOperatives, pct });
    }
    if (pcu.projects != null && pcu.maxProjects != null && isFinite(pcu.maxProjects)) {
        const pct = Math.min(100, (pcu.projects / pcu.maxProjects) * 100);
        bars.push({ label: 'Projects', used: pcu.projects, max: pcu.maxProjects, pct });
    }
    if (!bars.length) return '';
    return `
        <div class="license-usage-bars">
            ${bars.map(b => `
                <div class="license-usage-row">
                    <div class="license-usage-label">
                        <span>${esc(b.label)}</span>
                        <span style="font-family:var(--font-mono);font-size:var(--caption)">${b.used.toLocaleString()} / ${b.max === Infinity ? '∞' : b.max.toLocaleString()}</span>
                    </div>
                    <div class="license-usage-bar-bg">
                        <div class="license-usage-bar-fill" style="width:${b.pct.toFixed(1)}%;background:${b.pct > 85 ? 'var(--bad)' : b.pct > 60 ? 'var(--warn)' : 'var(--accent)'}"></div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

/* ── Event handlers ───────────────────────────────────────────────────────── */

function _attachHandlers() {
    // Step 1
    $('lic-upgrade-btn')?.addEventListener('click', () => { _step = 2; render(); });
    $('lic-sync-btn')?.addEventListener('click', _doSync);
    $('lic-deactivate-btn')?.addEventListener('click', _doDeactivate);
    $('lic-trial-activate-btn')?.addEventListener('click', () => { _step = 3; render(); });
    $('lic-trial-account-btn')?.addEventListener('click', () => {
        window.open('https://nexus-prime.cfd/account', '_blank', 'noopener');
    });
    $('lic-trial-email-btn')?.addEventListener('click', () => {
        window.open('mailto:adarsh@nexus-prime.cfd?subject=Nexus%20Prime%20license%20request', '_blank', 'noopener');
    });
    $('lic-renew-nag-btn')?.addEventListener('click', () => {
        window.open('https://nexus-prime.cfd/license', '_blank', 'noopener');
    });

    // Step 2 — plan cards
    document.querySelectorAll('[data-plan]').forEach(card => {
        card.addEventListener('click', () => {
            _targetPlan = card.dataset.plan;
            render();
        });
        card.addEventListener('keydown', e => {
            if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); card.click(); }
        });
    });
    $('lic-back-btn')?.addEventListener('click', () => {
        _step = Math.max(1, _step - 1);
        render();
    });
    $('lic-continue-btn')?.addEventListener('click', () => { _step = 3; render(); });

    // Step 3
    $('lic-activate-btn')?.addEventListener('click', _doActivate);
    $('lic-key-input')?.addEventListener('keydown', e => {
        if (e.key === 'Enter') _doActivate();
    });
}

async function _doSync() {
    const btn = $('lic-sync-btn');
    const msg = $('lic-step1-status');
    if (btn) btn.disabled = true;
    if (msg) msg.textContent = 'Syncing…';
    const r = await post('/api/license/sync', {}).catch(() => null);
    if (btn) btn.disabled = false;
    if (r?.ok) {
        if (msg) { msg.textContent = r.data?.message ?? 'License synced.'; msg.style.color = 'var(--ok)'; }
        setTimeout(load, 1000);
    } else {
        if (msg) { msg.textContent = r?.error ?? r?.data?.message ?? 'Sync failed.'; msg.style.color = 'var(--bad)'; }
    }
}

async function _doDeactivate() {
    if (!confirm('Deactivate your license and return to the free tier?')) return;
    const r = await post('/api/license/deactivate', {}).catch(() => null);
    if (r?.ok) setTimeout(load, 500);
}

async function _doActivate() {
    const keyInput = $('lic-key-input');
    const btn = $('lic-activate-btn');
    const msg = $('lic-step3-status');
    const key = keyInput?.value?.trim();
    if (!key) { if (msg) { msg.textContent = 'Enter a license key.'; msg.style.color = 'var(--bad)'; } return; }
    if (btn) btn.disabled = true;
    if (msg) msg.textContent = 'Activating…';
    const r = await post('/api/license/activate', { key }).catch(() => null);
    if (btn) btn.disabled = false;
    if (r?.ok) {
        if (msg) { msg.textContent = r.data?.message ?? 'Activated!'; msg.style.color = 'var(--ok)'; }
        setTimeout(load, 1200);
    } else {
        if (msg) { msg.textContent = r?.error ?? r?.data?.message ?? 'Activation failed.'; msg.style.color = 'var(--bad)'; }
    }
}
