const defaultModels = [
    {
        id: "prompt_gpt_tradutor", 
        name: "Tradutor Especialista", 
        group: "Prompts IA", 
        url: "chatgpt.com", 
        fullUrl: "https://chatgpt.com", 
        shortcut: "Alt + T",
        enabled: true,
        fields: [
            { type: 'fill', selector: "#prompt-textarea", value: `Atue como um tradutor nativo sênior.\nPor favor, traduza o texto abaixo para {{ask:Qual o idioma de destino? (Ex: Inglês, Espanhol)}} mantendo o tom e a fluidez natural.\n\nTexto original:\n{{ask:Cole o texto a ser traduzido aqui:}}`, enabled: true }
        ]
    },
    {
        id: "prompt_gemini_revisor", 
        name: "Revisor de Código/Texto", 
        group: "Prompts IA", 
        url: "gemini.google.com", 
        fullUrl: "https://gemini.google.com", 
        shortcut: "Alt + R",
        enabled: true,
        fields: [
            { type: 'fill', selector: ".ql-editor", value: `Analise o conteúdo abaixo e aponte:\n1. Erros gramaticais ou lógicos.\n2. Sugestões de melhoria de clareza.\n3. Uma versão reescrita otimizada.\n\nConteúdo para revisão:\n{{ask:Cole o texto ou código aqui:}}`, enabled: true }
        ]
    }
];

let models = [];
let currentTargetInput = null;

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;
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btnExport').addEventListener('click', exportModels);
    document.getElementById('btnImportClick').addEventListener('click', () => document.getElementById('importFile').click());
    document.getElementById('importFile').addEventListener('change', importModels);
    document.getElementById('btnToggleCreate').addEventListener('click', toggleCreateNew);
    
    document.getElementById('btn-apoiar-opt').addEventListener('click', () => { document.getElementById('sec-donation').scrollIntoView({behavior: 'smooth'}); });
    
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            e.target.classList.add('active');
            document.getElementById(e.target.dataset.target).classList.add('active');
        });
    });

    const fbModal = document.getElementById('feedback-modal');
    document.getElementById('btn-sugestoes-opt').addEventListener('click', () => fbModal.style.display = 'flex');
    document.getElementById('close-feedback').addEventListener('click', () => fbModal.style.display = 'none');
    window.addEventListener('click', (e) => { if (e.target == fbModal) fbModal.style.display = 'none'; });

    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 = "🚀 Enviar Mensagem"; 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 = "🚀 Enviar Mensagem"; }, 1500);
        });
    });

    document.getElementById('pix-qr-img').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + encodeURIComponent(generatePixPayload("f280da6b-4495-45aa-9ab5-c573118b3cf7", "Gabriel Jaques", "SAO PAULO"));
    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 = "#fff"; }, 2000);
    });

    load();
});

function updateGroupSuggestions() {
    const list = document.getElementById('groupSuggestions');
    list.innerHTML = "";
    const uniqueGroups = [...new Set(models.map(m => m.group).filter(g => g && g.trim() !== ""))];
    uniqueGroups.forEach(g => { const opt = document.createElement('option'); opt.value = g; list.appendChild(opt); });
}

function load() {
    chrome.storage.local.get({ zt_models: null }, (res) => {
        if (!res.zt_models || res.zt_models.length === 0) { models = defaultModels; chrome.storage.local.set({ zt_models: models }); } 
        else { models = res.zt_models; }
        updateGroupSuggestions();
        renderList();
        renderCreateNewForm();
    });
}

function buildFormInnerHtml(m = null) {
    const isEditing = m !== null;
    return `
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; margin-bottom: 12px;">
            <div class="form-group"><label>Nome do Modelo <span class="info-icon" title="Nome para identificar na lista">ⓘ</span></label><input type="text" class="inp-name" value="${isEditing ? m.name : ''}" placeholder="Ex: Revisor Ortográfico"></div>
            <div class="form-group"><label>Grupo (Categoria) <span class="info-icon" title="Agrupa os itens no Menu de Contexto">ⓘ</span></label><input type="text" class="inp-group" list="groupSuggestions" value="${isEditing ? (m.group || '') : ''}" placeholder="Ex: Prompts"></div>
            <div class="form-group"><label>Atalho de Teclado <span class="info-icon" title="Combinação para disparar na página">ⓘ</span></label><input type="text" class="inp-shortcut" value="${isEditing ? (m.shortcut || '') : ''}" placeholder="Clique e aperte as teclas" readonly style="cursor: pointer; background: #000; border-color: #a855f7; text-align: center; color: #a855f7; font-weight: bold;"></div>
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <div class="form-group"><label>Trecho da URL <span class="info-icon" title="Habilita a injeção ao reconhecer este trecho na URL da aba">ⓘ</span></label><input type="text" class="inp-url" value="${isEditing ? m.url : ''}" placeholder="Ex: chatgpt.com"></div>
            <div class="form-group"><label>URL Completa <span class="info-icon" title="Abre uma nova aba caso a página ainda não esteja aberta">ⓘ</span></label><input type="text" class="inp-full" value="${isEditing ? (m.fullUrl || '') : ''}" placeholder="Ex: https://chatgpt.com"></div>
        </div>
        <hr style="border: 1px solid var(--border); margin: 15px 0;"><h4 style="margin-top:0; font-size:14px; color:var(--text);">Ações da Automação (Arraste para Reordenar)</h4>
        
        <div class="fields-container"></div>
        
        <div style="display: flex; gap: 8px; margin-top: 12px;">
            <button class="btn btn-add-field" style="background: transparent; border: 1px dashed var(--accent); color: var(--accent); flex: 1;">+ Adicionar Texto</button>
            <button class="btn btn-add-click" style="background: transparent; border: 1px dashed var(--purple); color: var(--purple); flex: 1;">🖱️ Auto-Click</button>
            <button class="btn btn-add-wait" style="background: transparent; border: 1px dashed var(--orange); color: var(--orange); flex: 1;">⏱️ Atraso (Wait)</button>
        </div>
        
        <div style="margin-top: 20px; display: flex; gap: 8px; justify-content: flex-end;">
            <button class="btn btn-red btn-cancel">✖ Cancelar</button>
            <button class="btn btn-green btn-save">💾 Salvar ${isEditing ? 'Edição' : 'Modelo'}</button>
        </div>
    `;
}

function autoResizeTextarea(textarea) { textarea.style.height = '40px'; textarea.style.height = (textarea.scrollHeight + 2) + 'px'; }

function moveRow(row, direction) {
    if (direction === 'up' && row.previousElementSibling) { row.parentNode.insertBefore(row, row.previousElementSibling); } 
    else if (direction === 'down' && row.nextElementSibling) { row.parentNode.insertBefore(row.nextElementSibling, row); }
}

function getDragAfterElement(container, y, classSelector) {
    const draggableElements = [...container.querySelectorAll(`${classSelector}:not(.dragging)`)];
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect(); const offset = y - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) return { offset: offset, element: child }; else return closest;
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

function insertAtCursor(myField, myValue) {
    if (document.selection) { myField.focus(); document.selection.createRange().text = myValue; } 
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart; var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
        myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length;
    } else { myField.value += myValue; }
    autoResizeTextarea(myField);
}

function formatText(textarea, type, mode) {
    const start = textarea.selectionStart; const end = textarea.selectionEnd;
    const selected = textarea.value.substring(start, end);
    let injection = "";
    if (mode === "html") {
        if(type==='bold') injection = `<b>${selected || 'negrito'}</b>`;
        if(type==='italic') injection = `<i>${selected || 'itálico'}</i>`;
        if(type==='list') injection = `<ul><li>${selected || 'item'}</li></ul>`;
    } else {
        if(type==='bold') injection = `**${selected || 'negrito'}**`;
        if(type==='italic') injection = `*${selected || 'itálico'}*`;
        if(type==='list') injection = `\n- ${selected || 'item'}`;
    }
    textarea.value = textarea.value.substring(0, start) + injection + textarea.value.substring(end);
    textarea.selectionStart = start; textarea.selectionEnd = start + injection.length;
    textarea.focus();
}

function addActionRow(fieldsContainer, action = { type: 'fill', selector: "", value: "", enabled: true }) {
    const div = document.createElement('div'); div.className = "row-field"; div.draggable = true;
    const type = action.type || 'fill';
    const isEnabled = action.enabled !== false; // true by default
    
    if (!isEnabled) div.classList.add('disabled-row');

    let contentHtml = "";

    if (type === 'wait') {
        div.classList.add('wait-action');
        let delayValue = 1; let delayUnit = "s";
        if (action.delay) {
            if (action.delay >= 3600000) { delayValue = action.delay / 3600000; delayUnit = "h"; }
            else if (action.delay >= 60000) { delayValue = action.delay / 60000; delayUnit = "m"; }
            else if (action.delay >= 1000) { delayValue = action.delay / 1000; delayUnit = "s"; }
            else { delayValue = action.delay; delayUnit = "ms"; }
        }
        contentHtml = `
            <div style="flex: 1; display: flex; align-items: center; gap: 8px;">
                <span style="font-size: 18px;">⏱️</span>
                <div style="flex: 1; display: flex; align-items: center; gap: 8px;">
                    <div style="flex: 1;">
                        <label style="font-size: 10px; color: var(--orange); font-weight: bold;">Tempo</label>
                        <input type="number" class="f-delay-val" value="${delayValue}" min="0.1" step="0.1" style="border-color: var(--orange);">
                    </div>
                    <div style="width: auto;">
                        <label style="font-size: 10px; color: var(--orange); font-weight: bold;">Unidade</label>
                        <select class="f-time-unit" style="border-color: var(--orange);">
                            <option value="ms" ${delayUnit === 'ms' ? 'selected' : ''}>Milissegundos (ms)</option>
                            <option value="s" ${delayUnit === 's' ? 'selected' : ''}>Segundos (s)</option>
                            <option value="m" ${delayUnit === 'm' ? 'selected' : ''}>Minutos (m)</option>
                            <option value="h" ${delayUnit === 'h' ? 'selected' : ''}>Horas (h)</option>
                        </select>
                    </div>
                </div>
            </div>
        `;
    } else if (type === 'click') {
        div.classList.add('click-action');
        contentHtml = `
            <div style="flex: 1; display: flex; align-items: center; gap: 8px;">
                <span style="font-size: 18px;">🖱️</span>
                <div style="flex: 1;"><label style="font-size: 10px; color: var(--purple); font-weight: bold;">Botão a ser Clicado (Auto-Submit)</label>
                    <div style="display:flex; gap:6px;">
                        <input type="text" class="f-sel" placeholder="Seletor (ID, Name)" value="${action.selector || ''}" style="border-color: var(--purple); flex:1; margin:0;">
                        <button class="btn btn-purple btn-capture-row" title="Capturar botão" style="margin: 0; padding: 0 12px; width: auto;">🎯</button>
                    </div>
                </div>
            </div>
        `;
    } else {
        contentHtml = `
            <div style="flex: 1; display: flex; flex-direction: column; gap: 6px;">
                <div style="display: flex; gap: 6px; width: 100%;">
                    <input type="text" class="f-sel" placeholder="Seletor do Campo (ID, Name)" value='${action.selector || ""}' style="flex: 1; margin: 0;">
                    <button class="btn btn-purple btn-capture-row" title="Capturar elemento" style="margin: 0; padding: 0 12px; width: auto;">🎯</button>
                </div>
                <div class="rich-toolbar">
                    <select class="f-format-mode"><option value="html">Format HTML</option><option value="md">Format MD</option></select>
                    <button type="button" class="fmt-btn" data-fmt="bold">B</button><button type="button" class="fmt-btn" data-fmt="italic">I</button><button type="button" class="fmt-btn" data-fmt="list">Lista</button>
                    <div class="var-dropdown"><button type="button" class="fmt-btn" style="color:var(--accent);">✨ Variáveis ▾</button>
                        <div class="var-menu">
                            <button type="button" data-var="{{data_hoje}}">📅 Hoje (DD/MM/AAAA)</button>
                            <button type="button" data-var="{{hora_atual}}">⏰ Hora (HH:MM)</button>
                            <button type="button" data-var="{{data_ontem}}">📅 Ontem</button>
                            <button type="button" data-var="{{url_atual}}">🔗 URL Atual</button>
                            <button type="button" data-var="{{clipboard}}">📋 Clipboard (Ctrl+C)</button>
                            <button type="button" data-var="{{ask:Sua Pergunta?}}">❓ Pergunta Dinâmica (Ask)</button>
                        </div>
                    </div>
                </div>
                <textarea class="f-val rich-textarea" placeholder="Valor a Injetar..." style="min-height: 50px;">${action.value || ''}</textarea>
            </div>
        `;
    }

    const toggleHtml = `
        <label class="toggle-switch" title="Ativar/Desativar Linha">
            <input type="checkbox" class="f-enabled" ${isEnabled ? 'checked' : ''}>
            <span class="toggle-slider"></span>
        </label>
    `;

    div.innerHTML = `
        <div class="order-controls"><button class="btn-order btn-up">⏶</button><button class="btn-order btn-down">⏷</button></div>
        <span class="drag-handle">☰</span>
        ${contentHtml}
        <div style="display:flex; flex-direction:column; gap:10px; align-items:center; justify-content:center;">
            ${toggleHtml}
            <button class="btn btn-red btn-remove-field" style="padding: 4px 8px;">✖</button>
        </div>
    `;
    
    div.querySelector('.btn-up').addEventListener('click', () => moveRow(div, 'up'));
    div.querySelector('.btn-down').addEventListener('click', () => moveRow(div, 'down'));
    div.querySelector('.btn-remove-field').addEventListener('click', (e) => e.target.closest('.row-field').remove());

    div.querySelector('.f-enabled').addEventListener('change', function() {
        div.classList.toggle('disabled-row', !this.checked);
    });

    div.addEventListener('dragstart', () => { setTimeout(() => div.classList.add('dragging'), 0); });
    div.addEventListener('dragend', () => { div.classList.remove('dragging'); });
    
    fieldsContainer.addEventListener('dragover', e => {
        e.preventDefault();
        const draggedRow = fieldsContainer.querySelector('.row-field.dragging');
        if (!draggedRow) return;
        const afterElement = getDragAfterElement(fieldsContainer, e.clientY, '.row-field');
        if (afterElement == null) fieldsContainer.appendChild(draggedRow); else fieldsContainer.insertBefore(draggedRow, afterElement);
    });

    if (type === 'fill') {
        const ta = div.querySelector('.f-val');
        ta.addEventListener('input', function() { autoResizeTextarea(this); }); setTimeout(() => autoResizeTextarea(ta), 0);
        div.querySelectorAll('.fmt-btn[data-fmt]').forEach(b => b.addEventListener('click', (e) => formatText(ta, e.target.dataset.fmt, div.querySelector('.f-format-mode').value)));
        div.querySelectorAll('.var-menu button').forEach(b => b.addEventListener('click', (e) => insertAtCursor(ta, e.target.dataset.var)));
    }
    if (type === 'fill' || type === 'click') {
        div.querySelector('.btn-capture-row').addEventListener('click', (e) => { e.preventDefault(); currentTargetInput = div.querySelector('.f-sel'); activateInspector(); });
    }

    fieldsContainer.appendChild(div);
}

function attachFormEvents(container, modelId) {
    const shortcutInput = container.querySelector('.inp-shortcut');
    shortcutInput.addEventListener('keydown', (e) => {
        e.preventDefault(); if (e.key === "Backspace" || e.key === "Delete") { e.target.value = ""; return; }
        let keys = []; if (e.ctrlKey) keys.push('Ctrl'); if (e.altKey) keys.push('Alt'); if (e.shiftKey) keys.push('Shift');
        if (e.key !== 'Control' && e.key !== 'Alt' && e.key !== 'Shift') keys.push(e.key.toUpperCase());
        if (keys.length > 0) e.target.value = keys.join(' + ');
    });

    const fieldsDiv = container.querySelector('.fields-container');
    container.querySelector('.btn-add-field').addEventListener('click', () => addActionRow(fieldsDiv, {type: 'fill'}));
    container.querySelector('.btn-add-click').addEventListener('click', () => addActionRow(fieldsDiv, {type: 'click'}));
    container.querySelector('.btn-add-wait').addEventListener('click', () => addActionRow(fieldsDiv, {type: 'wait'}));
    container.querySelector('.btn-cancel').addEventListener('click', () => { if(modelId) toggleEdit(modelId); else toggleCreateNew(); });
    container.querySelector('.btn-save').addEventListener('click', () => saveModel(modelId, container));
}

function renderCreateNewForm() { const container = document.getElementById('new-model-form'); container.innerHTML = buildFormInnerHtml(null); addActionRow(container.querySelector('.fields-container'), {type: 'fill'}); attachFormEvents(container, null); }
function toggleCreateNew() { const c = document.getElementById('create-new-container'); if (c.classList.contains('open')) c.classList.remove('open'); else { renderCreateNewForm(); c.classList.add('open'); } }

function renderList() {
    const list = document.getElementById('list-container'); 
    list.innerHTML = "";
    
    models.forEach(m => {
        const div = document.createElement('div'); 
        div.className = "model-item";
        const isEnabled = m.enabled !== false;
        if (!isEnabled) div.classList.add('disabled-model');
        div.draggable = true; 
        div.dataset.id = m.id;
        
        div.innerHTML = `
            <div class="model-header" data-id="${m.id}">
                <div style="display:flex; align-items:center; gap: 10px;">
                    <span class="drag-handle" title="Arraste para reordenar o modelo">☰</span>
                    <label class="toggle-switch" title="Ativar/Desativar Modelo" style="margin: 0 5px;">
                        <input type="checkbox" class="m-enabled-toggle" ${isEnabled ? 'checked' : ''}>
                        <span class="toggle-slider"></span>
                    </label>
                    <div>
                        <span style="font-size:9px; background:#334155; padding:2px 6px; border-radius:4px;">${m.group || 'Gerais'}</span><br>
                        <b style="color: var(--accent); font-size: 14px;">${m.name}</b> ${m.shortcut ? ` <kbd style="color:#a855f7; font-family: monospace; background:#000; padding: 2px 5px; border-radius:3px;">[${m.shortcut}]</kbd>` : ''}<br>
                        <small style="color: var(--text-dim); font-size: 11px;">${m.url}</small>
                    </div>
                </div>
                <div class="model-actions"><button class="btn btn-edit" style="background: #eab308; color: #000;" data-id="${m.id}">✏️ Editar</button><button class="btn btn-red btn-del" data-id="${m.id}">🗑️ Excluir</button></div>
            </div>
            <div class="model-editor" id="edit_${m.id}"></div>
        `;
        
        div.querySelector('.model-header').addEventListener('click', (e) => { 
            if (!e.target.closest('button') && !e.target.closest('.drag-handle') && !e.target.closest('.toggle-switch')) toggleEdit(m.id); 
        });

        div.querySelector('.m-enabled-toggle').addEventListener('change', function(e) {
            e.stopPropagation(); 
            const isChecked = this.checked;
            div.classList.toggle('disabled-model', !isChecked);
            const model = models.find(x => x.id === m.id);
            if (model) {
                model.enabled = isChecked;
                chrome.storage.local.set({ zt_models: models });
            }
        });

        div.querySelector('.btn-edit').addEventListener('click', () => toggleEdit(m.id)); 
        div.querySelector('.btn-del').addEventListener('click', () => deleteModel(m.id));
        
        div.addEventListener('dragstart', (e) => { if (e.target.classList.contains('model-item')) { setTimeout(() => div.classList.add('dragging'), 0); } });
        div.addEventListener('dragend', () => { div.classList.remove('dragging'); saveModelOrder(); });

        list.appendChild(div);
    });

    list.addEventListener('dragover', e => {
        e.preventDefault(); 
        const draggedModel = list.querySelector('.model-item.dragging');
        if (!draggedModel) return;
        const afterElement = getDragAfterElement(list, e.clientY, '.model-item');
        if (afterElement == null) list.appendChild(draggedModel); else list.insertBefore(draggedModel, afterElement);
    });
}

function saveModelOrder() {
    const list = document.getElementById('list-container');
    const newOrderIds = Array.from(list.querySelectorAll('.model-item')).map(item => item.dataset.id);
    const reorderedModels = [];
    newOrderIds.forEach(id => { const model = models.find(m => m.id === id); if (model) reorderedModels.push(model); });
    models = reorderedModels;
    chrome.storage.local.set({ zt_models: models });
}

function toggleEdit(id) {
    const editor = document.getElementById(`edit_${id}`);
    if (editor.classList.contains('open')) { editor.classList.remove('open'); editor.innerHTML = ''; } 
    else {
        document.querySelectorAll('.model-editor.open').forEach(el => { el.classList.remove('open'); el.innerHTML = ''; });
        document.getElementById('create-new-container').classList.remove('open');
        const m = models.find(x => x.id === id); editor.innerHTML = buildFormInnerHtml(m);
        const fieldsDiv = editor.querySelector('.fields-container');
        if (m.fields.length === 0) addActionRow(fieldsDiv, {type: 'fill'}); else m.fields.forEach(f => addActionRow(fieldsDiv, f));
        attachFormEvents(editor, m.id); editor.classList.add('open');
    }
}

function saveModel(id, formContainer) {
    const name = formContainer.querySelector('.inp-name').value.trim(); const group = formContainer.querySelector('.inp-group').value.trim() || 'Gerais';
    const shortcut = formContainer.querySelector('.inp-shortcut').value.trim(); const url = formContainer.querySelector('.inp-url').value.trim(); const fullUrl = formContainer.querySelector('.inp-full').value.trim();
    if(!name || !url) return alert("Preencha o Nome e o Trecho da URL.");

    const fieldsContainer = formContainer.querySelector('.fields-container');
    const fields = Array.from(fieldsContainer.querySelectorAll('.row-field')).map(r => {
        const isEnabled = r.querySelector('.f-enabled').checked;
        if (r.classList.contains('wait-action')) {
            const val = parseFloat(r.querySelector('.f-delay-val').value) || 1;
            const unit = r.querySelector('.f-time-unit').value;
            let msDelay = val;
            if (unit === 's') msDelay = val * 1000;
            else if (unit === 'm') msDelay = val * 60000;
            else if (unit === 'h') msDelay = val * 3600000;
            return { type: 'wait', delay: msDelay, enabled: isEnabled };
        }
        else if (r.classList.contains('click-action')) return { type: 'click', selector: r.querySelector('.f-sel').value.trim(), enabled: isEnabled };
        else return { type: 'fill', selector: r.querySelector('.f-sel').value.trim(), value: r.querySelector('.f-val').value, enabled: isEnabled };
    }).filter(f => (f.type === 'wait' && f.delay) || (f.type === 'click' && f.selector !== "") || (f.type === 'fill' && f.selector !== ""));

    // Preserva o status do modelo caso já exista
    const existingModel = models.find(m => m.id === id);
    const mEnabled = existingModel ? existingModel.enabled : true;

    const mData = { id: id || Date.now().toString(), name, group, shortcut, url, fullUrl, fields, enabled: mEnabled };
    if (id) { models = models.map(x => x.id === id ? mData : x); } else { models.push(mData); }

    chrome.storage.local.set({ zt_models: models }, () => { if (!id) toggleCreateNew(); updateGroupSuggestions(); load(); });
}

function deleteModel(id) { if(confirm("Deseja excluir este modelo?")) { models = models.filter(x => x.id !== id); chrome.storage.local.set({ zt_models: models }, load); } }

async function activateInspector() {
    const windows = await chrome.windows.getAll({ populate: true, windowTypes: ['normal'] });
    let targetTab = null; for (let w of windows) { const activeTab = w.tabs.find(t => t.active); if (activeTab && !activeTab.url.includes(chrome.runtime.id)) { targetTab = activeTab; break; } }
    if (!targetTab) return alert("Abra a guia do sistema alvo antes de capturar.");

    chrome.scripting.executeScript({
        target: { tabId: targetTab.id },
        func: () => {
            if (document.getElementById('autofiller-inspector')) return;
            const style = document.createElement('style'); style.id = 'autofiller-style'; style.innerHTML = `* { cursor: crosshair !important; }`; document.head.appendChild(style);
            const overlay = document.createElement('div'); overlay.id = 'autofiller-inspector'; Object.assign(overlay.style, { position: 'fixed', top: '0', left: '0', width: '100vw', height: '100vh', zIndex: '9999999' }); document.body.appendChild(overlay);

            let lastTarget = null; const outlines = new Map();
            const onMove = (e) => {
                overlay.style.pointerEvents = 'none'; const el = document.elementFromPoint(e.clientX, e.clientY); overlay.style.pointerEvents = 'auto'; 
                if (!el || el === overlay || el === lastTarget) return;
                if (lastTarget && outlines.has(lastTarget)) lastTarget.style.outline = outlines.get(lastTarget);
                lastTarget = el; outlines.set(el, el.style.outline); el.style.outline = '3px solid #a855f7';
            };
            const onClick = (e) => {
                e.preventDefault(); e.stopPropagation(); const el = lastTarget;
                document.removeEventListener('mousemove', onMove, true); document.removeEventListener('click', onClick, true);
                if (lastTarget && outlines.has(lastTarget)) lastTarget.style.outline = outlines.get(lastTarget);
                overlay.remove(); document.getElementById('autofiller-style').remove(); 
                let selector = ""; if (el.id) { selector = `#${el.id}`; } else if (el.name) { selector = `[name="${el.name}"]`; } else if (el.className && typeof el.className === 'string' && el.className.trim() !== '') {
                    const classes = el.className.trim().split(/\s+/).filter(c => c); selector = `${el.tagName.toLowerCase()}.${classes.join('.')}`;
                } else {
                    let path = []; let current = el;
                    while (current && current.nodeType === Node.ELEMENT_NODE) {
                        let sel = current.nodeName.toLowerCase();
                        if (current.id) { sel += `#${current.id}`; path.unshift(sel); break; } else {
                            let sib = current, nth = 1; while (sib = sib.previousElementSibling) { if (sib.nodeName.toLowerCase() == sel) nth++; }
                            if (nth != 1) sel += `:nth-of-type(${nth})`;
                        } path.unshift(sel); current = current.parentNode;
                    } selector = path.join(' > ');
                }
                chrome.runtime.sendMessage({ action: "capturedSelector", selector: selector });
            };
            document.addEventListener('mousemove', onMove, true); document.addEventListener('click', onClick, true);
        }
    });
    chrome.windows.update(targetTab.windowId, { focused: true });
}

chrome.runtime.onMessage.addListener((req) => {
    if (req.action === "capturedSelector" && currentTargetInput) {
        currentTargetInput.value = req.selector;
        const valueField = currentTargetInput.closest('.row-field').querySelector('.f-val'); if (valueField) valueField.focus();
        chrome.tabs.getCurrent((tab) => { chrome.windows.update(tab.windowId, { focused: true }); });
        currentTargetInput = null; 
    }
});

function exportModels() { const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(models, null, 2)); const a = document.createElement('a'); a.href = dataStr; a.download = "autofiller_modelos.json"; a.click(); }
function importModels(e) {
    const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
    reader.onload = (event) => { try { const imported = JSON.parse(event.target.result); if (Array.isArray(imported)) { models = imported; chrome.storage.local.set({ zt_models: models }, load); alert("Modelos importados!"); } } catch (err) { alert("Arquivo JSON inválido!"); } };
    reader.readAsText(file); e.target.value = ""; 
}