/**
 * wa_popup_license.js — WebAssets Lock Screen Controller
 * Runs in the popup context (index.html).
 * NEVER makes auth decisions — only asks background.js and renders UI.
 */
(function () {
    'use strict';

    const overlay    = document.getElementById('wa-lock-overlay');
    const codeInput  = document.getElementById('wa-code-input');
    const activateBtn= document.getElementById('wa-activate-btn');
    const msgEl      = document.getElementById('wa-lock-msg');
    const expiryBanner = document.getElementById('wa-expiry-banner');
    const mainApp      = document.getElementById('wa-main-app');

    // ── Helpers ───────────────────────────────────────────────────────────────
    function showMsg(text, type) {
        msgEl.textContent = text;
        msgEl.className   = type || 'info';
    }

    function showLock() {
        if (mainApp) mainApp.style.display = 'none';
        overlay.classList.add('wa-visible');
        showMsg('Enter your access code below.', 'info');
        expiryBanner.style.display = 'none';
    }

    function hideLock(expiresAt) {
        overlay.classList.remove('wa-visible');
        if (mainApp) mainApp.style.display = 'block';
        
        if (expiresAt) {
            const d = new Date(expiresAt);
            expiryBanner.textContent =
                '🔑 WebAssets Licensed — Access expires: ' + d.toLocaleString();
            expiryBanner.style.display = 'block';
            // Adjust top padding of main content so banner doesn't overlap
            document.body.style.paddingTop = '30px';
        }
    }

    // ── Boot: ask background if license is valid ──────────────────────────────
    chrome.runtime.sendMessage({ type: 'CHECK_LICENSE' }, (response) => {
        if (chrome.runtime.lastError) {
            // Background not ready yet — show lock as safe fallback
            showLock();
            return;
        }
        if (response && response.licensed) {
            hideLock(response.expiresAt);
        } else {
            showLock();
        }
    });

    // ── Activate button click ─────────────────────────────────────────────────
    activateBtn.addEventListener('click', handleActivate);
    codeInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') handleActivate();
    });

    function handleActivate() {
        const code = codeInput.value.trim();
        if (!code) {
            showMsg('Please enter your access code.', 'err');
            codeInput.focus();
            return;
        }

        activateBtn.disabled = true;
        activateBtn.textContent = 'Verifying…';
        showMsg('Checking your code…', 'info');

        chrome.runtime.sendMessage({ type: 'ACTIVATE_LICENSE', code }, (result) => {
            activateBtn.disabled = false;
            activateBtn.textContent = 'Activate';

            if (chrome.runtime.lastError || !result) {
                showMsg('Communication error. Please reload and try again.', 'err');
                return;
            }

            if (result.success) {
                showMsg('✅ ' + (result.message || 'Access granted!'), 'ok');
                setTimeout(() => hideLock(result.expiresAt), 800);
            } else {
                showMsg('❌ ' + (result.message || 'Invalid code.'), 'err');
                codeInput.value = '';
                codeInput.focus();
            }
        });
    }

    // ── Periodic re-check every 5 minutes while popup is open ─────────────────
    // If the license expires while the user is actively using the popup,
    // the lock screen will reappear automatically.
    setInterval(() => {
        chrome.runtime.sendMessage({ type: 'CHECK_LICENSE' }, (response) => {
            if (!response || !response.licensed) {
                showLock();
            }
        });
    }, 5 * 60 * 1000);

})();
