/* Settings view — license activation, tier management, upgrade */
const SettingsView = {
    async render() {
        const app = document.getElementById('app');
        let license = {};
        let tier = {};
        try {
            license = await complyApi.getLicense();
            tier = await complyApi.getTier();
        } catch (e) { /* defaults */ }

        const currentTier = license.tier || 'free';
        const licensed = license.licensed || false;

        app.innerHTML = `
        <div class="page-header">
            <h2>Settings</h2>
        </div>

        <div class="card">
            <div class="card-header">Current Plan</div>
            <div class="settings-plan">
                <div class="plan-badge plan-${currentTier}">${currentTier.toUpperCase()}</div>
                <div class="plan-details">
                    <p><strong>Frameworks:</strong> ${(tier.frameworks || []).join(', ') || 'All 8 frameworks'}</p>
                    <p><strong>Max depth:</strong> ${tier.max_depth || 'content'}</p>
                    <p><strong>Exports:</strong> ${(tier.exports || []).join(', ')}</p>
                    ${licensed ? `<p class="plan-licensed">Licensed: ${license.key_prefix || ''}</p>` : ''}
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">Activate License Key</div>
            <div class="form-group">
                <label>License key</label>
                <input class="form-input" id="license-key-input"
                       placeholder="pro-xxxxxxxx-yyyyyyyy" style="font-family: monospace">
            </div>
            <div class="btn-group">
                <button class="btn btn-primary" onclick="SettingsView.activate()">Activate</button>
                ${licensed ? '<button class="btn btn-outline" onclick="SettingsView.deactivate()">Deactivate</button>' : ''}
            </div>
            <div id="license-message"></div>
        </div>

        ${currentTier === 'free' ? this._renderUpgradeCards() : ''}
        `;
    },

    _renderUpgradeCards() {
        return `
        <div class="card">
            <div class="card-header">Upgrade</div>
            <div class="upgrade-grid">
                <div class="upgrade-card">
                    <h3>Pro</h3>
                    <div class="upgrade-price">$99<span>/month</span></div>
                    <ul class="upgrade-features">
                        <li>3 frameworks (EU AI Act, NIST, ISO)</li>
                        <li>Semantic LLM evaluation (BYOK)</li>
                        <li>SARIF, JUnit, Markdown, DOCX export</li>
                        <li>Scan history and regression detection</li>
                        <li>5 projects</li>
                    </ul>
                    <button class="btn btn-primary" onclick="SettingsView.checkout('pro')">Upgrade to Pro</button>
                </div>
                <div class="upgrade-card">
                    <h3>Enterprise</h3>
                    <div class="upgrade-price">$499<span>/month</span></div>
                    <ul class="upgrade-features">
                        <li>All 8 frameworks</li>
                        <li>Three-layer evidence (code + process + traffic)</li>
                        <li>Audit log adapters (Gateway, Kong, Gravitee)</li>
                        <li>Audit bundle ZIP export</li>
                        <li>Unlimited projects</li>
                    </ul>
                    <button class="btn btn-primary" onclick="SettingsView.checkout('enterprise')">Upgrade to Enterprise</button>
                </div>
            </div>
        </div>`;
    },

    async activate() {
        const key = document.getElementById('license-key-input').value.trim();
        if (!key) return;

        const msgEl = document.getElementById('license-message');
        try {
            const result = await complyApi.activateLicense(key);
            msgEl.innerHTML = `<div class="alert alert-success">${result.message}</div>`;
            // Refresh the page to show new tier
            setTimeout(() => SettingsView.render(), 1000);
        } catch (e) {
            msgEl.innerHTML = `<div class="alert alert-error">${e.message}</div>`;
        }
    },

    async deactivate() {
        if (!confirm('Deactivate license and revert to free tier?')) return;
        try {
            await complyApi.deactivateLicense();
            SettingsView.render();
        } catch (e) {
            document.getElementById('license-message').innerHTML =
                `<div class="alert alert-error">${e.message}</div>`;
        }
    },

    async checkout(tier) {
        try {
            const result = await complyApi.createCheckout(tier, 'monthly');
            if (result.url) {
                window.open(result.url, '_blank');
            }
        } catch (e) {
            alert(`Checkout error: ${e.message}\n\nTo use Pro/Enterprise features, activate a license key instead.`);
        }
    },
};
