<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License &amp; Billing — VerseBlocks</title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif; background: #f3f4f6; color: #1f2937; min-height: 100vh; display: flex; flex-direction: column; }
        .header { background: #fff; border-bottom: 1px solid #e5e7eb; padding: 16px 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }
        .header h1 { font-size: 18px; font-weight: 600; color: #111827; }
        .header p { font-size: 13px; color: #6b7280; margin-top: 4px; }
        .content { padding: 24px; flex: 1; max-width: 800px; width: 100%; margin: 0 auto; }
        .section { background: #fff; border-radius: 8px; border: 1px solid #e5e7eb; margin-bottom: 20px; overflow: hidden; }
        .section-header { padding: 14px 20px; border-bottom: 1px solid #e5e7eb; }
        .section-header h2 { font-size: 15px; font-weight: 600; }
        .section-body { padding: 16px 20px; }
        .field { margin-bottom: 14px; }
        .field-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; margin-bottom: 3px; }
        .field-value { font-size: 14px; color: #1f2937; }
        .field-row { display: flex; gap: 24px; flex-wrap: wrap; }
        .field-row .field { flex: 1; min-width: 140px; }
        .badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; }
        .badge-active { background: #d1fae5; color: #065f46; }
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-warn { background: #fee2e2; color: #991b1b; }
        .badge-tier { background: #e0e7ff; color: #3730a3; }
        .badge-ai { background: #f3e8ff; color: #6b21a8; }
        .key-display { font-family: 'Cascadia Code', 'Fira Code', Consolas, monospace; font-size: 15px; letter-spacing: 1px; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 8px 12px; display: inline-flex; align-items: center; gap: 8px; }
        .key-toggle { background: none; border: none; color: #2563eb; cursor: pointer; font-size: 12px; font-weight: 600; }
        .key-toggle:hover { text-decoration: underline; }
        .btn { font-family: inherit; font-size: 13px; padding: 8px 20px; border-radius: 6px; border: none; cursor: pointer; font-weight: 600; transition: all 0.15s; }
        .btn-primary { background: #2563eb; color: #fff; }
        .btn-primary:hover { background: #1d4ed8; }
        .btn-primary:disabled { background: #93c5fd; cursor: not-allowed; }
        .btn-secondary { background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; }
        .btn-secondary:hover { background: #e5e7eb; }
        .btn-link { background: none; border: none; color: #2563eb; cursor: pointer; font-size: 13px; font-weight: 600; padding: 0; }
        .btn-link:hover { text-decoration: underline; }
        .actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
        .activate-form { display: flex; gap: 10px; align-items: end; flex-wrap: wrap; }
        .activate-form input { font-family: 'Cascadia Code', Consolas, monospace; font-size: 14px; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; width: 340px; letter-spacing: 1px; }
        .activate-form input:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 2px rgba(37,99,235,0.15); }
        .usage-bar { margin-top: 6px; }
        .usage-bar .bar { height: 6px; background: #e5e7eb; border-radius: 3px; overflow: hidden; width: 200px; }
        .usage-bar .fill { height: 100%; border-radius: 3px; transition: width 0.3s; }
        .usage-bar .text { font-size: 11px; color: #6b7280; margin-top: 2px; }
        .error { background: #fef2f2; color: #991b1b; padding: 12px 20px; border-radius: 6px; margin-bottom: 16px; font-size: 13px; display: none; }
        .success { background: #f0fdf4; color: #166534; padding: 12px 20px; border-radius: 6px; margin-bottom: 16px; font-size: 13px; display: none; }
        .spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid #d1d5db; border-top-color: #2563eb; border-radius: 50%; animation: spin 0.6s linear infinite; vertical-align: middle; margin-right: 6px; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .divider { border-top: 1px solid #f3f4f6; margin: 16px 0; }
        @media (max-width: 640px) { .activate-form input { width: 100%; } .field-row { flex-direction: column; gap: 0; } }
    </style>
</head>
<body>
    <div class="header">
        <h1>License &amp; Billing</h1>
        <p>Manage your VerseBlocks license and subscription.</p>
    </div>

    <div class="content">
        <div id="errorMsg" class="error"></div>
        <div id="successMsg" class="success"></div>

        <!-- License Status -->
        <div class="section">
            <div class="section-header"><h2>License</h2></div>
            <div class="section-body" id="licenseBody">
                <div style="text-align:center;padding:20px;color:#6b7280;"><span class="spinner"></span> Loading...</div>
            </div>
        </div>

        <!-- Activate (shown only when not activated) -->
        <div class="section" id="activateSection" style="display:none;">
            <div class="section-header"><h2>Activate License</h2></div>
            <div class="section-body">
                <p style="font-size:13px;color:#6b7280;margin-bottom:12px;">Enter your license key to activate this environment.</p>
                <div class="activate-form">
                    <input type="text" id="keyInput" placeholder="CARTO-XXXXX-XXXXX-XXXXX-XXXXX" maxlength="29" spellcheck="false" autocomplete="off">
                    <button class="btn btn-primary" id="activateBtn">Activate</button>
                </div>
            </div>
        </div>

        <!-- Usage (shown when active) -->
        <div class="section" id="usageSection" style="display:none;">
            <div class="section-header"><h2>Usage</h2></div>
            <div class="section-body" id="usageBody"></div>
        </div>

        <!-- AI Configuration (shown when active) -->
        <div class="section" id="aiSection" style="display:none;">
            <div class="section-header"><h2>AI Configuration</h2></div>
            <div class="section-body" id="aiBody">
                <p style="font-size:13px;color:#6b7280;margin-bottom:12px;">Configure your AI provider for generating component summaries and user guides.</p>
                <div style="display:flex;flex-direction:column;gap:10px;max-width:480px;">
                    <div>
                        <label style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Provider</label>
                        <select id="aiProvider" style="margin-top:4px;width:100%;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;background:#fff;">
                            <option value="openai">OpenAI</option>
                            <option value="azure">Azure OpenAI</option>
                        </select>
                    </div>
                    <div>
                        <label style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">API Key</label>
                        <div style="display:flex;gap:6px;margin-top:4px;">
                            <input id="aiKey" type="password" placeholder="sk-... or Azure key" style="flex:1;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;font-family:monospace;">
                            <button onclick="toggleAiKeyVisibility()" id="aiKeyToggle" style="padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;background:#f9fafb;font-size:12px;cursor:pointer;">Show</button>
                        </div>
                    </div>
                    <div id="aiEndpointRow">
                        <label style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Endpoint</label>
                        <input id="aiEndpoint" type="text" placeholder="https://your-resource.openai.azure.com/openai/deployments/gpt-4o-mini" style="margin-top:4px;width:100%;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;font-family:monospace;">
                        <p style="font-size:11px;color:#9ca3af;margin-top:2px;">For Azure OpenAI: include the full deployment path. For OpenAI: leave blank (uses default).</p>
                    </div>
                    <div>
                        <label style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Model</label>
                        <input id="aiModel" type="text" placeholder="gpt-4o-mini" value="gpt-4o-mini" style="margin-top:4px;width:100%;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;">
                    </div>
                    <div style="display:flex;gap:8px;margin-top:4px;">
                        <button class="btn btn-primary" onclick="saveAiConfig()" id="aiSaveBtn">Save AI Configuration</button>
                        <button class="btn btn-secondary" onclick="testAiConfig()" id="aiTestBtn">Test Connection</button>
                    </div>
                    <div id="aiStatus" style="display:none;padding:8px 12px;border-radius:6px;font-size:13px;margin-top:4px;"></div>
                </div>
            </div>
        </div>

        <!-- Plan Actions (shown when active) -->
        <div class="section" id="planSection" style="display:none;">
            <div class="section-header"><h2>Plan &amp; Billing</h2></div>
            <div class="section-body">
                <p style="font-size:13px;color:#6b7280;margin-bottom:16px;">Manage your subscription, upgrade, or view invoices on our website.</p>
                <div class="actions">
                    <button class="btn btn-primary" onclick="window.open('https://www.verseblocks.com/pricing', '_blank')">View Plans &amp; Upgrade</button>
                    <button class="btn btn-secondary" id="manageBillingBtn" style="display:none;">Manage Billing</button>
                </div>
                <p style="font-size:12px;color:#9ca3af;margin-top:12px;">You can cancel anytime from the billing portal. Access continues until the end of your billing period.</p>
            </div>
        </div>
    </div>

    <script>
        // Analytics - fire and forget
        function vbAnalytics(eventType, details) {
            try {
                fetch('/api/data/v9.2/vb_configurations?$select=vb_license_key,vb_org_id&$top=1', {
                    headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                    credentials: 'include'
                }).then(function(r) { return r.json(); }).then(function(d) {
                    if (!d.value || !d.value[0]) return;
                    var c = d.value[0];
                    fetch('https://cartographer-api.azurewebsites.net/api/analytics/event', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            licenseKey: c.vb_license_key,
                            orgId: c.vb_org_id || '',
                            eventType: eventType,
                            details: JSON.stringify(details || {}),
                            timestamp: new Date().toISOString()
                        })
                    });
                });
            } catch(e) { /* silent */ }
        }
        vbAnalytics('page_view', {page: 'license_billing'});

        var API_BASE = '/api/data/v9.2/';
        var BACKEND_API = 'https://cartographer-api.azurewebsites.net/api/';

        var STATUS_LABELS = { 10001000: 'Not Activated', 10001001: 'Active', 10001002: 'Payment Failed', 10001003: 'Suspended', 10001004: 'Expired', 10001005: 'Invalid' };
        var STATUS_CLASSES = { 10001000: 'badge-pending', 10001001: 'badge-active', 10001002: 'badge-warn', 10001003: 'badge-warn', 10001004: 'badge-warn', 10001005: 'badge-warn' };
        var TIER_LABELS = { 10001000: 'Free', 10001001: 'Professional', 10001002: 'Enterprise' };
        var AI_LABELS = { 10001000: 'Hosted AI', 10001001: 'Bring Your Own Key' };

        var licenseKey = null;
        var keyVisible = false;

        function showError(msg) { var el = document.getElementById('errorMsg'); el.textContent = msg; el.style.display = 'block'; setTimeout(function () { el.style.display = 'none'; }, 8000); }
        function showSuccess(msg) { var el = document.getElementById('successMsg'); el.textContent = msg; el.style.display = 'block'; setTimeout(function () { el.style.display = 'none'; }, 5000); }

        function maskKey(key) {
            if (!key) return '—';
            var parts = key.split('-');
            if (parts.length < 5) return key;
            return parts[0] + '-' + parts[1].substring(0, 2) + '***-****-****-****';
        }

        function toggleKeyVisibility() {
            keyVisible = !keyVisible;
            var el = document.getElementById('keyDisplay');
            var btn = document.getElementById('keyToggle');
            if (keyVisible) { el.textContent = licenseKey; btn.textContent = 'Hide'; }
            else { el.textContent = maskKey(licenseKey); btn.textContent = 'Show'; }
        }

        function apiGet(url) {
            return fetch(API_BASE + url, {
                headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Prefer': 'odata.include-annotations="*"' },
                credentials: 'include'
            }).then(function (r) { if (!r.ok) return r.text().then(function (t) { throw new Error(t); }); return r.json(); });
        }

        function formatDate(d) { return d ? new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '—'; }

        function loadLicense() {
            apiGet("vb_configurations?$select=vb_configurationid,vb_license_key,vb_license_status,vb_license_tier,vb_license_expires_on,vb_license_validated_on,vb_ai_mode,vb_org_id,vb_hosted_ai_calls_used,vb_hosted_ai_calls_limit,vb_openai_api_key,vb_openai_endpoint,vb_openai_model&$top=1")
            .then(function (data) {
                if (!data.value || data.value.length === 0) {
                    document.getElementById('licenseBody').innerHTML =
                        '<div style="padding:16px 0;">' +
                        '<p style="color:#1f2937;font-size:15px;font-weight:600;margin-bottom:4px;">Welcome to Cartographer</p>' +
                        '<p style="color:#6b7280;font-size:13px;margin-bottom:16px;">Get started with the Free plan or activate a license key.</p>' +
                        '<div style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;padding:16px;margin-bottom:16px;">' +
                        '<p style="font-size:13px;font-weight:600;color:#1f2937;margin-bottom:10px;">Start Free Plan</p>' +
                        '<div style="display:flex;flex-direction:column;gap:8px;max-width:360px;">' +
                        '<input id="freeEmail" type="email" placeholder="Email address (required)" style="padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;">' +
                        '<input id="freeName" type="text" placeholder="Your name" style="padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;" required>' +
                        '<input id="freeCompany" type="text" placeholder="Company" style="padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;" required>' +
                        '<button id="freeBtn" onclick="startFreePlan()" style="padding:9px 20px;background:#2563eb;color:white;border:none;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer;align-self:flex-start;">Start Free Plan</button>' +
                        '</div>' +
                        '<p style="color:#9ca3af;font-size:11px;margin-top:8px;">Free: 20 components, AI summaries (BYOK), Component Dashboard</p>' +
                        '</div>' +
                        '<p style="color:#6b7280;font-size:13px;">Have a paid license key? Activate it below. Need one? <a href="https://www.verseblocks.com/pricing" target="_blank" style="color:#2563eb;text-decoration:underline;font-weight:600;">View plans</a></p>' +
                        '</div>';
                    document.getElementById('activateSection').style.display = 'block';
                    return;
                }

                var c = data.value[0];
                licenseKey = c.vb_license_key;
                var status = c.vb_license_status;
                var tier = c.vb_license_tier;
                var statusLabel = STATUS_LABELS[status] || 'Unknown';
                var statusClass = STATUS_CLASSES[status] || 'badge-pending';
                var tierLabel = TIER_LABELS[tier] || '—';
                var aiLabel = AI_LABELS[c.vb_ai_mode] || '—';

                var html = '';

                // Key row
                html += '<div class="field">';
                html += '<div class="field-label">License Key</div>';
                html += '<div class="key-display"><span id="keyDisplay">' + maskKey(licenseKey) + '</span>';
                html += '<button class="key-toggle" id="keyToggle" onclick="toggleKeyVisibility()">Show</button></div>';
                html += '</div>';

                // Status row
                html += '<div class="field-row">';
                html += '<div class="field"><div class="field-label">Status</div><div class="field-value"><span class="badge ' + statusClass + '">' + statusLabel + '</span></div></div>';
                html += '<div class="field"><div class="field-label">Tier</div><div class="field-value"><span class="badge badge-tier">' + tierLabel + '</span></div></div>';
                html += '<div class="field"><div class="field-label">AI Mode</div><div class="field-value"><span class="badge badge-ai">' + aiLabel + '</span></div></div>';
                html += '</div>';

                // Dates row
                html += '<div class="field-row">';
                html += '<div class="field"><div class="field-label">Expires On</div><div class="field-value">' + formatDate(c.vb_license_expires_on) + '</div></div>';
                html += '<div class="field"><div class="field-label">Last Validated</div><div class="field-value">' + formatDate(c.vb_license_validated_on) + '</div></div>';
                html += '<div class="field"><div class="field-label">Org ID</div><div class="field-value" style="font-family:monospace;font-size:12px;">' + (c.vb_org_id || '—') + '</div></div>';
                html += '</div>';

                // Add refresh button
                html += '<div style="margin-top:12px;"><button class="btn btn-secondary" onclick="refreshLicense()" id="refreshBtn" style="font-size:12px;padding:6px 14px;">Refresh License</button></div>';

                document.getElementById('licenseBody').innerHTML = html;

                // Show/hide sections based on status
                if (status === 10001000) { // Not Activated
                    document.getElementById('activateSection').style.display = 'block';
                } else {
                    document.getElementById('activateSection').style.display = 'none';
                    document.getElementById('planSection').style.display = 'block';

                    // Load AI configuration
                    loadAiConfig(c);

                    // Usage section — count components and solutions
                    var usageHtml = '';

                    // Count components
                    fetch(API_BASE + 'vb_components/$count', {
                        headers: {'Accept':'text/plain','OData-MaxVersion':'4.0','OData-Version':'4.0'},
                        credentials: 'include'
                    }).then(function(r) { return r.text(); }).then(function(count) {
                        var compCount = parseInt(count) || 0;

                        // Count solutions
                        return fetch(API_BASE + 'vb_crawlconfigurations/$count', {
                            headers: {'Accept':'text/plain','OData-MaxVersion':'4.0','OData-Version':'4.0'},
                            credentials: 'include'
                        }).then(function(r2) { return r2.text(); }).then(function(solCount) {
                            var solutions = parseInt(solCount) || 0;

                            // Count AI summaries
                            return fetch(API_BASE + 'vb_components/$count?$filter=vb_crawl_status eq 10001002', {
                                headers: {'Accept':'text/plain','OData-MaxVersion':'4.0','OData-Version':'4.0'},
                                credentials: 'include'
                            }).then(function(r3) { return r3.text(); }).then(function(aiCount) {
                                var aiSummaries = parseInt(aiCount) || 0;

                                usageHtml += '<div class="field-row">';
                                usageHtml += '<div class="field"><div class="field-label">Solutions Crawled</div><div class="field-value">' + solutions + '</div></div>';
                                usageHtml += '<div class="field"><div class="field-label">Components</div><div class="field-value">' + compCount.toLocaleString() + '</div></div>';
                                usageHtml += '<div class="field"><div class="field-label">AI Summaries</div><div class="field-value">' + aiSummaries.toLocaleString() + '</div></div>';
                                usageHtml += '</div>';

                                if (c.vb_ai_mode === 10001000 && c.vb_hosted_ai_calls_limit > 0) {
                                    var used = c.vb_hosted_ai_calls_used || 0;
                                    var limit = c.vb_hosted_ai_calls_limit || 10000;
                                    var pct = Math.min(100, (used / limit) * 100);
                                    usageHtml += '<div class="field" style="margin-top:12px;"><div class="field-label">Hosted AI Calls</div><div class="field-value">' + used.toLocaleString() + ' / ' + limit.toLocaleString() + '</div>';
                                    usageHtml += '<div class="usage-bar"><div class="bar"><div class="fill" style="width:' + pct + '%;background:' + (pct > 80 ? '#dc2626' : '#2563eb') + ';"></div></div></div></div>';
                                }

                                document.getElementById('usageBody').innerHTML = usageHtml;
                            });
                        });
                    }).catch(function() {
                        document.getElementById('usageBody').innerHTML = '<p style="color:#6b7280;font-size:13px;">Unable to load usage data.</p>';
                    });

                    document.getElementById('usageSection').style.display = 'block';

                    // Backend billing status for Stripe portal
                    if (licenseKey) {
                        fetch(BACKEND_API + 'billing/status', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ licenseKey: licenseKey })
                        }).then(function (r) { return r.json(); })
                        .then(function (d) {
                            if (d.success && d.customer && d.customer.hasStripe) {
                                document.getElementById('manageBillingBtn').style.display = 'inline-block';
                            }
                        }).catch(function () {});
                    }
                }
            }).catch(function (err) {
                document.getElementById('licenseBody').innerHTML = '<p style="color:#991b1b;">Error loading license: ' + err.message + '</p>';
            });
        }

        // Activate
        document.getElementById('activateBtn').addEventListener('click', function () {
            var key = document.getElementById('keyInput').value.trim().toUpperCase();
            if (!key || !key.startsWith('CARTO-') || key.length < 29) {
                showError('Please enter a valid license key (format: CARTO-XXXXX-XXXXX-XXXXX-XXXXX)');
                return;
            }

            var btn = document.getElementById('activateBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner"></span>Activating...';

            fetch(API_BASE + 'vb_ValidateLicense', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                credentials: 'include',
                body: JSON.stringify({ LicenseKey: key })
            }).then(function (r) { return r.json(); })
            .then(function (result) {
                btn.disabled = false;
                btn.textContent = 'Activate';
                if (result.Valid) {
                    showSuccess('License activated! Tier: ' + (result.Tier || 'Unknown'));
                    loadLicense();
                } else {
                    showError(result.Message || 'Activation failed.');
                }
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Activate';
                showError('Error: ' + err.message);
            });
        });

        // Manage Billing
        document.getElementById('manageBillingBtn').addEventListener('click', function () {
            var btn = document.getElementById('manageBillingBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner"></span>Opening...';

            fetch(BACKEND_API + 'billing/portal', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ licenseKey: licenseKey, returnUrl: window.location.href })
            }).then(function (r) { return r.json(); })
            .then(function (d) {
                btn.disabled = false;
                btn.textContent = 'Manage Billing';
                if (d.success && d.url) {
                    window.open(d.url, '_blank');
                } else {
                    showError(d.message || 'Could not open billing portal.');
                }
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Manage Billing';
                showError('Error: ' + err.message);
            });
        });

        // --- AI Configuration ---
        var configId = null;

        function loadAiConfig(config) {
            configId = config.vb_configurationid;
            var key = config.vb_openai_api_key || '';
            var endpoint = config.vb_openai_endpoint || '';
            var model = config.vb_openai_model || 'gpt-4o-mini';
            var aiMode = config.vb_ai_mode;

            // Only show AI section if BYOK mode
            if (aiMode === 10001001) { // BYOK
                document.getElementById('aiSection').style.display = 'block';
                document.getElementById('aiKey').value = key;
                document.getElementById('aiEndpoint').value = endpoint;
                document.getElementById('aiModel').value = model;

                // Auto-detect provider
                if (endpoint && (endpoint.includes('openai.azure.com') || endpoint.includes('cognitiveservices.azure.com'))) {
                    document.getElementById('aiProvider').value = 'azure';
                } else {
                    document.getElementById('aiProvider').value = 'openai';
                }
                updateEndpointVisibility();
            }
        }

        function updateEndpointVisibility() {
            var provider = document.getElementById('aiProvider').value;
            document.getElementById('aiEndpointRow').style.display = provider === 'azure' ? 'block' : 'block';
            if (provider === 'openai') {
                document.getElementById('aiEndpoint').placeholder = 'https://api.openai.com/v1 (leave blank for default)';
            } else {
                document.getElementById('aiEndpoint').placeholder = 'https://your-resource.openai.azure.com/openai/deployments/gpt-4o-mini';
            }
        }

        function toggleAiKeyVisibility() {
            var input = document.getElementById('aiKey');
            var btn = document.getElementById('aiKeyToggle');
            if (input.type === 'password') { input.type = 'text'; btn.textContent = 'Hide'; }
            else { input.type = 'password'; btn.textContent = 'Show'; }
        }

        function saveAiConfig() {
            if (!configId) { showError('No configuration record found.'); return; }
            var key = document.getElementById('aiKey').value.trim();
            var endpoint = document.getElementById('aiEndpoint').value.trim();
            var model = document.getElementById('aiModel').value.trim() || 'gpt-4o-mini';

            if (!key) { showError('API key is required.'); return; }

            var btn = document.getElementById('aiSaveBtn');
            btn.disabled = true;
            btn.textContent = 'Saving...';

            fetch(API_BASE + 'vb_configurations(' + configId + ')', {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json',
                           'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                credentials: 'include',
                body: JSON.stringify({
                    vb_openai_api_key: key,
                    vb_openai_endpoint: endpoint,
                    vb_openai_model: model
                })
            }).then(function (r) {
                btn.disabled = false;
                btn.textContent = 'Save AI Configuration';
                if (r.ok) {
                    showSuccess('AI configuration saved.');
                } else {
                    return r.text().then(function (t) { throw new Error(t); });
                }
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Save AI Configuration';
                showError('Failed to save: ' + err.message);
            });
        }

        function testAiConfig() {
            if (!configId) { showError('Save your configuration first.'); return; }

            var btn = document.getElementById('aiTestBtn');
            var status = document.getElementById('aiStatus');
            btn.disabled = true;
            btn.textContent = 'Testing...';
            status.style.display = 'none';

            // Pick a simple component to test with
            fetch(API_BASE + 'vb_components?$select=vb_componentid&$top=1', {
                headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                credentials: 'include'
            }).then(function (r) { return r.json(); }).then(function (data) {
                if (!data.value || data.value.length === 0) {
                    throw new Error('No components found. Crawl a solution first.');
                }
                return fetch(API_BASE + 'vb_GenerateAISummary', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json',
                               'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                    credentials: 'include',
                    body: JSON.stringify({ ComponentId: data.value[0].vb_componentid })
                });
            }).then(function (r) { return r.json(); }).then(function (result) {
                btn.disabled = false;
                btn.textContent = 'Test Connection';
                if (result.Success) {
                    status.style.display = 'block';
                    status.style.background = '#f0fdf4';
                    status.style.color = '#166534';
                    status.style.border = '1px solid #bbf7d0';
                    status.textContent = 'Connection successful! AI summary generated.';
                } else {
                    throw new Error(result.error ? result.error.message : 'AI generation failed');
                }
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Test Connection';
                status.style.display = 'block';
                status.style.background = '#fef2f2';
                status.style.color = '#991b1b';
                status.style.border = '1px solid #fecaca';
                status.textContent = 'Connection failed: ' + err.message;
            });
        }

        // Provider change handler
        if (document.getElementById('aiProvider')) {
            document.getElementById('aiProvider').addEventListener('change', updateEndpointVisibility);
        }

        // Start Free Plan — register with backend, get license key, create config
        function startFreePlan() {
            var email = document.getElementById('freeEmail').value.trim();
            var name = document.getElementById('freeName').value.trim();
            var company = document.getElementById('freeCompany').value.trim();
            if (!email || !email.includes('@')) {
                showError('Please enter a valid email address.');
                return;
            }
            if (!name) {
                showError('Please enter your name.');
                return;
            }
            if (!company) {
                showError('Please enter your company name.');
                return;
            }
            var btn = document.getElementById('freeBtn');
            btn.disabled = true;
            btn.textContent = 'Setting up...';

            // Get org info from Dataverse
            var orgId = '';
            var orgUrl = window.location.origin;
            fetch(API_BASE + 'WhoAmI', {
                headers: { 'Accept': 'application/json' },
                credentials: 'include'
            }).then(function (r) { return r.json(); }).then(function (d) {
                orgId = d.OrganizationId || '';
            }).catch(function () {}).then(function () {
                // Register with backend
                return fetch('https://cartographer-api.azurewebsites.net/api/license/register-free', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ email: email, name: name, company: company, orgId: orgId, orgUrl: orgUrl })
                });
            }).then(function (r) { return r.json(); }).then(function (result) {
                if (!result.success) {
                    btn.disabled = false;
                    btn.textContent = 'Start Free Plan';
                    showError(result.message);
                    return;
                }

                // Create Dataverse config record with the license key
                return fetch(API_BASE + 'vb_configurations', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json',
                               'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                    credentials: 'include',
                    body: JSON.stringify({
                        vb_name: 'VerseBlocks Configuration',
                        vb_license_key: result.licenseKey,
                        vb_license_status: 10001001, // Active
                        vb_license_tier: 10001000, // Free
                        vb_ai_mode: 10001001, // BYOK
                        vb_org_id: orgId
                    })
                }).then(function (r) {
                    if (r.ok) {
                        showSuccess('Free plan activated! License key: ' + result.licenseKey);
                        loadLicense();
                    } else {
                        throw new Error('Failed to create configuration');
                    }
                });
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Start Free Plan';
                showError('Registration failed: ' + err.message);
            });
        }

        // Refresh License — re-validates against backend API to pull latest tier/status
        function refreshLicense() {
            if (!licenseKey) { showError('No license key found.'); return; }

            var btn = document.getElementById('refreshBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner"></span>Refreshing...';

            fetch(API_BASE + 'vb_ValidateLicense', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json',
                           'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },
                credentials: 'include',
                body: JSON.stringify({ LicenseKey: licenseKey })
            }).then(function (r) { return r.json(); })
            .then(function (result) {
                btn.disabled = false;
                btn.textContent = 'Refresh License';
                if (result.Valid) {
                    showSuccess('License refreshed. Tier: ' + (result.Tier || 'Unknown'));
                    loadLicense(); // Reload all sections with updated data
                } else {
                    showError(result.Message || 'License validation failed.');
                    loadLicense();
                }
            }).catch(function (err) {
                btn.disabled = false;
                btn.textContent = 'Refresh License';
                showError('Refresh failed: ' + err.message);
            });
        }

        // Init
        loadLicense();
    </script>
</body>
</html>
