// ==========================================================
// 1. CONSTANTES E VARIÁVEIS GLOBAIS
// ==========================================================
const VFS_DOMAIN = "lift-api.vfsglobal.com";
const COOKIE_URL = `https://visa.vfsglobal.com`;
const CLIENTSOURCE_HEADER_NAME = 'clientsource';
const MAX_POOL_SIZE = 30;
const URL_LOGIN_VFS = "https://visa.vfsglobal.com/ago/en/prt/login";

// Licenciamento e API
const ALARM_LICENSE = 'licenseCheckAlarm';
const LICENSE_API_URL = 'https://advence.com.ao/api/check_license.php'; 
const EXTENSION_ID = 20;
const APPLICANTS_STORAGE_KEY = "vfs_applicants_v2";
const ACCOUNT_STORAGE_KEY = 'saved_accounts';
const DEVICE_ID_KEY = 'device_uuid';

let clientsourcePool = []; 
let idPopupRenovacao = null;
const confirmacoesAtivas = new Map();

const VFS_SECURITY_COOKIES = [
    '_cfuvid', '_fbp', '_ga', 'dtCookie', 'rxVisitor', 'rxvt',
    '_sz_3eb770', '_sz_739498', 'OptanonAlertBoxClosed', 'dtPC',
    '__cf_bm', 'OptanonConsent', '_sz_8fda62', 'cf_clearance',
    '_sz_c57861', 'lt_sn', '_ga_Z8LKRKHHG4', '_gcl_au'
];

// Configuração de acesso ao storage.session
chrome.storage.session.setAccessLevel({ 
    accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS' 
});

// ==========================================================
// 2. FUNÇÕES AUXILIARES E LOGS
// ==========================================================

function swLog(message, isError = false) {
    const prefix = isError ? "❌ SW ERRO" : "✅ SW INFO";
    console.log(`[${prefix}]: ${message}`);
}

async function getOrCreateDeviceId() {
    const data = await chrome.storage.local.get(DEVICE_ID_KEY);
    let deviceId = data[DEVICE_ID_KEY];
    if (!deviceId) {
        deviceId = crypto.randomUUID(); 
        await chrome.storage.local.set({ [DEVICE_ID_KEY]: deviceId });
    }
    return deviceId;
}

async function getAllVfsSecurityCookies() {
    const cookiesResult = {};
    for (const name of VFS_SECURITY_COOKIES) {
        try {
            const cookie = await chrome.cookies.get({ url: COOKIE_URL, name: name });
            if (cookie?.value) cookiesResult[name] = cookie.value;
        } catch (error) {
            swLog(`Falha ao ler o cookie ${name}: ${error.message}`, true);
        }
    }
    return cookiesResult;
}

async function updateCSPool(newValue) {
    if (clientsourcePool.includes(newValue)) return;
    clientsourcePool.push(newValue);
    if (clientsourcePool.length > MAX_POOL_SIZE) clientsourcePool.shift();
    await chrome.storage.session.set({ 'cs_pool': clientsourcePool });
    swLog(`📦 Pool de ClientSource: ${clientsourcePool.length}/${MAX_POOL_SIZE}`);
}

// ==========================================================
// 3. LÓGICA DE LICENCIAMENTO
// ==========================================================

async function fetchLicenseStatus(key) {
    const deviceId = await getOrCreateDeviceId();
    
    if (!key) {
        await chrome.storage.local.set({ licenseStatus: 'INACTIVE', lastCheck: Date.now() });
        await chrome.storage.session.clear();
        return { status: 'INACTIVE' };
    }

    try {
        const response = await fetch(LICENSE_API_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ key, extensao_id: EXTENSION_ID, device_id: deviceId })
        });

        const data = await response.json();
        const status = data.status || 'ERROR';

        if (status === 'VALID') {
            // REMOVIDO: [ACCOUNT_STORAGE_KEY] e [APPLICANTS_STORAGE_KEY]
            // Agora salvamos apenas o status da licença e metadados
            await chrome.storage.local.set({
                licenseStatus: 'VALID',
                lastCheck: Date.now(),
                expiryDate: data.data_expiracao
            });

            await chrome.storage.session.set({
                access_token: data.access_token,
                user_id: data.user_id,
                licenseKey_sessao: key
            });
            
            swLog("VFS ADVENCE: Licença validada (Dados locais preservados).");
        } else {
            await chrome.storage.local.set({ licenseStatus: status, lastCheck: Date.now() });
            await chrome.storage.session.clear();
        }

        return { status: status, token: data.access_token };

    } catch (error) {
        swLog(`VFS ADVENCE: Erro API: ${error.message}`, true);
        return { status: 'ERROR' };
    }
}

function startInitialCheck() {
    chrome.storage.local.get('licenseKey', (data) => {
        if (data.licenseKey) fetchLicenseStatus(data.licenseKey);
    });
}

// ==========================================================
// 4. CAPTURA DINÂMICA DE HEADERS (WebRequest)
// ==========================================================

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        for (const header of details.requestHeaders) {
            if (header.name.toLowerCase() === CLIENTSOURCE_HEADER_NAME) { 
                updateCSPool(header.value);
                return;
            }
        }
    },
    { urls: [`https://${VFS_DOMAIN}/*`] }, 
    ["requestHeaders"] 
);

// ==========================================================
// 5. LISTENER DE MENSAGENS (CONSOLIDADO)
// ==========================================================

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    (async () => {
        try {
            const acaoReal = request.action || request.acao;

            switch (acaoReal) {
                case "requestLicenseCheck":
                    chrome.storage.local.get(['licenseKey'], async (data) => {
                        const result = await fetchLicenseStatus(data.licenseKey);
                        sendResponse(result);
                    });
                    return; // Retorno antecipado pois o sendResponse está no callback do storage

           case "ABRIR_MINI_POPUP":
    const isAndroid = /Android/i.test(navigator.userAgent);

    if (isAndroid) {
        swLog("📱 Iniciando renovação silenciosa no Android...");
        
        // Em vez de criar uma aba que fica aberta, vamos tentar carregar o contexto
        // apenas para disparar a atualização de cookies/headers.
        chrome.tabs.create({
            url: URL_LOGIN_VFS,
            active: false,
            pinned: true // Fixar a aba ajuda a torná-la menos intrusiva no mobile
        }, (tab) => {
            // Monitora o status da aba para injetar o clique o mais rápido possível
            const listener = (tabId, changeInfo) => {
                if (tabId === tab.id && changeInfo.status === 'complete') {
                    chrome.scripting.executeScript({
                        target: { tabId: tab.id },
                        files: ["click_cloudflare.js"]
                    }).catch(() => {});
                    
                    // Remove o listener após a execução
                    chrome.tabs.onUpdated.removeListener(listener);
                }
            };
            chrome.tabs.onUpdated.addListener(listener);

            // FECHAMENTO AGRESSIVO: No Android, 15 segundos é o bastante para renovar o cookie.
            // Isso evita que o usuário veja a aba se ele mudar de aplicativo e voltar.
            setTimeout(() => {
                chrome.tabs.remove(tab.id).catch(() => {});
            }, 15000);
        });
    } else {
        // DESKTOP (Código original que você já tem)
        if (idPopupRenovacao) {
            chrome.windows.remove(idPopupRenovacao).catch(() => {});
        }
        chrome.windows.create({
            url: URL_LOGIN_VFS, 
            type: 'popup',
            width: 400, height: 500,
            focused: false 
        }, (win) => {
            if (!win?.id) return;
            idPopupRenovacao = win.id;
            setTimeout(() => {
                chrome.scripting.executeScript({
                    target: { tabId: win.tabs[0].id },
                    files: ["click_cloudflare.js"]
                }).catch(() => {});
            }, 4000);
            chrome.alarms.create(`fechar_popup_${win.id}`, { delayInMinutes: 35/60 }); 
        });
    }
    sendResponse({ success: true });
    break;
                case "EXECUTAR_CONFIRMACAO_FINAL":
                    const requestKey = request.stepName || request.url;
                    if (confirmacoesAtivas.has(requestKey)) {
                        const result = await confirmacoesAtivas.get(requestKey);
                        sendResponse({ success: true, data: result });
                        return; 
                    }

                    const confirmacaoPromise = (async () => {
                        const regras = [{
                            id: 1, priority: 1,
                            action: {
                                type: 'modifyHeaders',
                                requestHeaders: [
                                    { header: 'origin', operation: 'set', value: 'https://visa.vfsglobal.com' },
                                    { header: 'referer', operation: 'set', value: 'https://visa.vfsglobal.com/' },
                                    { header: 'sec-fetch-site', operation: 'set', value: 'same-site' }
                                ]
                            },
                            condition: { urlFilter: 'payments/confirmappointment', resourceTypes: ['xmlhttprequest'] }
                        }];
                        await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [1], addRules: regras });

                        const sessionData = await chrome.storage.session.get('cs_pool');
                        let pool = sessionData.cs_pool || [];
                        let clientSourceToken = null;
                        if (pool.length > 0) {
                            let rawToken = pool.shift(); 
                            clientSourceToken = rawToken.replace(/^[\s,]+/, '').trim();
                            pool.push(rawToken); 
                            await chrome.storage.session.set({ 'cs_pool': pool });
                        }

                        const headersFinal = {};
                        for (let key in request.headers) { headersFinal[key.toLowerCase()] = request.headers[key]; }
                        if (clientSourceToken) headersFinal['clientsource'] = clientSourceToken;

                        const response = await fetch(request.url, {
                            method: 'POST',
                            headers: headersFinal,
                            body: request.payload
                        });

                        if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);

                        const data = await response.json();
                        await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [1] });
                        return data;
                    })();

                    confirmacoesAtivas.set(requestKey, confirmacaoPromise);
                    try {
                        const finalData = await confirmacaoPromise;
                        sendResponse({ success: true, data: finalData });
                    } finally {
                        confirmacoesAtivas.delete(requestKey);
                    }
                    break;

                case "GET_CLIENTSOURCE":
                    const sessionDataCS = await chrome.storage.session.get('cs_pool');
                    let poolCS = sessionDataCS.cs_pool || [];
                    if (poolCS.length > 0) {
                        const token = poolCS.shift();
                        poolCS.push(token); 
                        await chrome.storage.session.set({ 'cs_pool': poolCS });
                        sendResponse({ clientsource: token });
                    } else {
                        const stored = await chrome.storage.local.get(CLIENTSOURCE_HEADER_NAME);
                        sendResponse({ clientsource: stored[CLIENTSOURCE_HEADER_NAME] || null });
                    }
                    break;

                case "GET_ALL_VFS_COOKIES":
                    const allCookies = await getAllVfsSecurityCookies(); 
                    sendResponse({ allCookies: allCookies }); 
                    break;

                case "loadVfsContext":
                    await chrome.storage.local.set({ 
                        'vfs_token': request.data.token, 
                        'vfs_email': request.data.email
                    });
                    sendResponse({ success: true });
                    break;

                case "notifyUser":
                    chrome.notifications.create({
                        type: 'basic',
                        iconUrl: 'icons/icon48.png',
                        title: request.title,
                        message: request.message,
                        priority: 2
                    });
                    sendResponse({ success: true });
                    break;

                case "CLOSE_CURRENT_TAB":
                    if (sender.tab) {
                        swLog(`🏁 Finalizando aba ${sender.tab.id}.`);
                        chrome.tabs.remove(sender.tab.id);
                        sendResponse({ success: true });
                    } else {
                        sendResponse({ success: false });
                    }
                    break;

                default:
                    sendResponse({ success: false, error: "Ação não mapeada" });
            }
        } catch (error) {
            swLog(`Erro ao processar mensagem: ${error.message}`, true);
            sendResponse({ success: false, error: error.message });
        }
    })();
    return true; 
});

// ==========================================================
// 6. CICLO DE VIDA E ALARMES
// ==========================================================

chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name.startsWith("fechar_popup_")) {
        const winId = parseInt(alarm.name.split("_")[2]);
        chrome.windows.remove(winId).catch(() => {});
        if (idPopupRenovacao === winId) idPopupRenovacao = null;
    }
    
    if (alarm.name === ALARM_LICENSE) {
        startInitialCheck();
    }
});

chrome.runtime.onInstalled.addListener(() => {
    chrome.alarms.create(ALARM_LICENSE, { periodInMinutes: 60 });
    startInitialCheck();
    swLog("Extensão instalada e ciclo de vida iniciado.");
});

chrome.runtime.onStartup.addListener(startInitialCheck);

// Execução imediata
startInitialCheck();
swLog("Service Worker Consolidado e Completo.");