function checkForUpdates() {
    const currentVersion = chrome.runtime.getManifest().version; 
    const URL_DO_SEU_JSON = 'https://gabriel.jaques.in/autofiller_version.json'; 

    fetch(URL_DO_SEU_JSON, { cache: "no-store" })
        .then(response => response.json())
        .then(data => {
            if (isNewerVersion(currentVersion, data.latestVersion)) {
                document.getElementById('txt-new-version').innerText = 'v' + data.latestVersion;
                document.getElementById('txt-update-notes').innerText = data.releaseNotes;
                document.getElementById('btn-download-update').href = data.downloadUrl;
                document.getElementById('update-banner').style.display = 'flex';
                
                document.getElementById('btn-close-update').addEventListener('click', () => {
                    document.getElementById('update-banner').style.display = 'none';
                });
            }
        }).catch(err => console.log("AutoFiller: Servidor de atualização indisponível no momento."));
}

function isNewerVersion(current, latest) {
    const cParts = current.split('.').map(Number);
    const lParts = latest.split('.').map(Number);
    for (let i = 0; i < Math.max(cParts.length, lParts.length); i++) {
        let c = cParts[i] || 0; let l = lParts[i] || 0;
        if (l > c) return true; if (c > l) return false;
    }
    return false;
}

function generatePixPayload(key, name, city) {
    let payload = "000201";
    let merchantAcc = "0014br.gov.bcb.pix01" + key.length.toString().padStart(2, '0') + key;
    payload += "26" + merchantAcc.length.toString().padStart(2, '0') + merchantAcc;
    payload += "5204000053039865802BR";
    payload += "59" + name.length.toString().padStart(2, '0') + name;
    payload += "60" + city.length.toString().padStart(2, '0') + city;
    payload += "62070503***6304";
    let crc = 0xFFFF;
    for (let i = 0; i < payload.length; i++) {
        crc ^= payload.charCodeAt(i) << 8;
        for (let j = 0; j < 8; j++) { if ((crc & 0x8000) !== 0) crc = (crc << 1) ^ 0x1021; else crc = crc << 1; }
    }
    crc = (crc & 0xFFFF).toString(16).toUpperCase().padStart(4, '0');
    return payload + crc;
}

function getGroupColor(groupStr) {
    const colors = ['#38bdf8', '#10b981', '#a855f7', '#f59e0b', '#ec4899', '#06b6d4', '#ef4444'];
    if (!groupStr) return '#64748b';
    let hash = 0;
    for (let i = 0; i < groupStr.length; i++) hash = groupStr.charCodeAt(i) + ((hash << 5) - hash);
    return colors[Math.abs(hash) % colors.length];
}

document.getElementById('btn-config').addEventListener('click', () => chrome.runtime.openOptionsPage());

const fbModal = document.getElementById('feedback-modal');
const donateModal = document.getElementById('donate-modal');

document.getElementById('btn-sugestoes').addEventListener('click', () => fbModal.style.display = 'flex');
document.getElementById('close-feedback').addEventListener('click', () => fbModal.style.display = 'none');

document.getElementById('btn-apoiar').addEventListener('click', () => {
    document.getElementById('popup-pix-qr').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + encodeURIComponent(generatePixPayload("f280da6b-4495-45aa-9ab5-c573118b3cf7", "Gabriel Jaques", "SAO PAULO"));
    donateModal.style.display = 'flex';
});
document.getElementById('close-donate').addEventListener('click', () => donateModal.style.display = 'none');

window.addEventListener('click', (e) => {
    if (e.target == fbModal) fbModal.style.display = 'none';
    if (e.target == donateModal) donateModal.style.display = 'none';
});

document.getElementById('pix-copy-box').addEventListener('click', () => {
    const keyText = document.getElementById('pix-key-text');
    navigator.clipboard.writeText("f280da6b-4495-45aa-9ab5-c573118b3cf7");
    const original = keyText.innerText;
    keyText.innerText = "✅ COPIADO COM SUCESSO!";
    keyText.style.color = "#10b981";
    setTimeout(() => { keyText.innerText = original; keyText.style.color = "#e2e8f0"; }, 2000);
});

document.getElementById('btn-send-feedback').addEventListener('click', () => {
    const email = document.getElementById('fb-email').value.trim();
    const msg = document.getElementById('fb-msg').value.trim();
    const btn = document.getElementById('btn-send-feedback');
    if(!email || !msg || !email.includes('@')) { alert('Preencha os dados corretamente.'); return; }
    
    btn.innerText = "A enviar...";
    fetch('https://n8n.jaques.in/webhook/sugestoes-apps', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ app: "AutoFiller", remetente: email, mensagem: msg })
    }).then(res => {
        btn.innerText = "Entregue! 🚀";
        setTimeout(() => { fbModal.style.display = 'none'; btn.innerText = "🚀 Transmitir Dados"; document.getElementById('fb-msg').value = "";}, 2000);
    }).catch(err => {
        btn.innerText = "Erro. Abrindo e-mail...";
        setTimeout(() => { window.open(`mailto:sugestoes@jaques.in?subject=AutoFiller&body=${encodeURIComponent(msg)}`); fbModal.style.display='none'; btn.innerText = "🚀 Transmitir Dados"; }, 1500);
    });
});

chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
    checkForUpdates(); 
    
    const currentUrl = tabs[0]?.url || "";
    const data = await chrome.storage.local.get({ zt_models: null });
    
    const models = data.zt_models || [];
    const enabledModels = models.filter(m => m.enabled !== false);
    const container = document.getElementById('content-area');

    if (enabledModels.length === 0) {
        container.innerHTML = `
            <div style="text-align:center; padding: 10px; position:relative; z-index:10;">
                <b style="color: #f8fafc; font-size: 15px; text-shadow: 0 2px 5px rgba(0,0,0,0.5);">Tudo limpo por aqui!</b>
                <p style="color:#94a3b8; font-size: 13px; margin: 15px 0 20px 0; line-height: 1.5;">
                    Comece criando o seu primeiro modelo de injeção de dados automatizado.<br><br>
                    <span style="color:#38bdf8; font-weight:bold;">💡 Dica de Ouro:</span> Em sites bloqueados, clique com o <b>Botão Direito</b> no campo de texto para usar o <i>AutoFiller GJ</i>.
                </p>
                <button class="btn-create" id="btn-onboard">✨ Construir Modelo</button>
            </div>
        `;
        document.getElementById('btn-onboard').addEventListener('click', () => chrome.runtime.openOptionsPage());
        return;
    }

    let currentTabModels = enabledModels.filter(m => currentUrl.includes(m.url));
    let otherModels = enabledModels.filter(m => !currentUrl.includes(m.url));
    let html = "";

    if (currentTabModels.length > 0) {
        html += `<div class="section-title active-page">📍 Injetar nesta página</div>`;
        currentTabModels.forEach(m => {
            const color = getGroupColor(m.group);
            html += `
                <div class="model-card current" data-id="${m.id}" style="--theme-color: ${color};">
                    <div class="m-header">
                        <span class="m-name">${m.name}</span>
                        <span class="m-group" style="color: ${color}; border-color: ${color}40;">${m.group || 'Gerais'}</span>
                    </div>
                    <div class="m-action">
                        <span>⚡ Executar automação</span>
                        ${m.shortcut ? `<span class="m-shortcut">${m.shortcut}</span>` : ''}
                    </div>
                </div>`;
        });
    }

    if (otherModels.length > 0) {
        html += `<div class="section-title" style="margin-top:20px;">🌐 Abrir em outros sites</div>`;
        otherModels.forEach(m => {
            const color = getGroupColor(m.group);
            html += `
                <div class="model-card external" data-id="${m.id}" style="--theme-color: ${color};">
                    <div class="m-header">
                        <span class="m-name">${m.name}</span>
                        <span class="m-group" style="color: ${color}; border-color: ${color}40;">${m.group || 'Gerais'}</span>
                    </div>
                    <div class="m-action">
                        <span>↗️ Abre nova aba: ${m.url.split('/')[0]}</span>
                    </div>
                </div>`;
        });
    }

    container.innerHTML = html;

    document.querySelectorAll('.model-card').forEach(card => {
        card.addEventListener('click', () => {
            const model = enabledModels.find(x => x.id === card.dataset.id);
            chrome.runtime.sendMessage({ action: "runModel", model: model });
            window.close();
        });
    });
});