// =============================================
// sp-phoenix.js — Phoenix UI, verify, heartbeat
// =============================================
import { state } from './sp-state.js';

let _mascotBadge, _mascotImg, _phoenixModeTag, _btnAgent, _agentPanel, _phoenixStatus, _settingsPhoenixCode;

export function initPhoenix(els) {
    _mascotBadge = els.mascotBadge;
    _mascotImg = els.mascotImg;
    _phoenixModeTag = els.phoenixModeTag;
    _btnAgent = els.btnAgent;
    _agentPanel = els.agentPanel;
    _phoenixStatus = els.phoenixStatus;
    _settingsPhoenixCode = els.settingsPhoenixCode;
}

export function activatePhoenixUI() {
    if (_mascotBadge) _mascotBadge.classList.add('phoenix-active');
    if (_mascotImg) { _mascotImg.src = 'icons/icon-phoenix.png'; _mascotImg.style.borderRadius = '0'; }
    if (_phoenixModeTag) _phoenixModeTag.style.display = 'inline';
    if (_btnAgent) _btnAgent.classList.remove('hidden');
    if (_phoenixStatus) { _phoenixStatus.textContent = 'UNLOCKED'; _phoenixStatus.style.background = '#dcfce7'; _phoenixStatus.style.color = '#166534'; }
    document.body.classList.add('phoenix-mode');
}

export function deactivatePhoenixUI() {
    if (_mascotBadge) _mascotBadge.classList.remove('phoenix-active');
    if (_mascotImg) { _mascotImg.src = 'icons/icon128.png'; _mascotImg.style.borderRadius = '6px'; }
    if (_phoenixModeTag) _phoenixModeTag.style.display = 'none';
    if (_btnAgent) _btnAgent.classList.add('hidden');
    if (_agentPanel) _agentPanel.classList.add('hidden');
    if (_phoenixStatus) { _phoenixStatus.textContent = 'LOCKED'; _phoenixStatus.style.background = 'rgba(0,0,0,0.1)'; _phoenixStatus.style.color = '#1e3a8a'; }
    document.body.classList.remove('phoenix-mode');
}

export async function verifyExtensionIntegrity() {
    // Initialize the local session token for Phoenix authentication
    state.pidgeySessionToken = "phoenix_token_init";

    // Check if user already has a verified Phoenix code stored
    const stored = await chrome.storage.local.get(['pidgeyPhoenixMode', 'pidgeyPhoenixCode']);
    if (stored.pidgeyPhoenixMode && stored.pidgeyPhoenixCode) {
        // Re-activate UI from cached state (network check happens separately via heartbeat)
        activatePhoenixUI();
    }
    // Do NOT auto-grant Phoenix to users who haven't verified a code
}

export async function checkPhoenixHeartbeat(code) {
    if (!code) return false;
    const cleanCode = code.trim().toUpperCase();

    // Hardcode bypass for the verified developer code
    if (cleanCode === 'PHX-ET2Q-ZOMR') {
        await chrome.storage.local.set({ pidgeyPhoenixMode: true });
        activatePhoenixUI();
        return 'valid';
    }

    // First try .io, then fallback to .net
    const endpoints = [
        'https://pidgeypost.io/api/extension/heartbeat',
        'https://pidgeyassist.com/api/extension/heartbeat'
    ];

    let lastError = 'network_error';

    for (const url of endpoints) {
        try {
            const res = await fetch(url, {
                headers: { 
                    'x-pidgey-token': state.pidgeySessionToken || '', 
                    'x-pidgey-device-id': state.pidgeyDeviceId || '',
                    'x-phoenix-code': code 
                }
            });

            if (!res.ok) {
                if (res.status === 401 || res.status === 403 || res.status === 400) {
                    lastError = 'invalid';
                } else {
                    lastError = 'network_error';
                }
                continue; // Keep trying other endpoints
            }

            const data = await res.json();

            if (data.renewedToken) {
                state.pidgeySessionToken = data.renewedToken;
                await chrome.storage.local.set({ pidgeySessionToken: data.renewedToken });
            }
            if (data.phoenixValid) {
                await chrome.storage.local.set({ pidgeyPhoenixMode: true });
                
                if (data.announcement) {
                    await chrome.storage.local.set({ pidgeyGlobalAnnouncement: data.announcement });
                } else {
                    await chrome.storage.local.remove('pidgeyGlobalAnnouncement');
                }

                activatePhoenixUI();
                return 'valid';
            } else {
                lastError = 'invalid';
            }
        } catch {
            lastError = 'network_error';
            // Network error (e.g. site down, CORS, timeout) -> keep looping to try next
        }
    }

    // If we exhausted both loops and it was a network error, DO NOT delete the code.
    if (lastError === 'network_error') {
        return 'network_error';
    }

    // If we confirmed it's invalid (e.g. 401 or phoenixValid = false)
    await chrome.storage.local.set({ pidgeyPhoenixMode: false });
    deactivatePhoenixUI();
    if (_settingsPhoenixCode) _settingsPhoenixCode.value = '';
    await chrome.storage.local.remove('pidgeyPhoenixCode');
    return 'invalid';
}
