chrome.storage.local.get({ zt_models: [] }, (data) => {
    const models = data.zt_models;
    if (!models || models.length === 0) return;

    // Filtra os atalhos apenas de modelos que estão ativos
    const activeModels = models.filter(m => m.enabled !== false && location.href.includes(m.url) && m.shortcut);

    if (activeModels.length > 0) {
        document.addEventListener('keydown', (e) => {
            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' && e.key.trim() !== '') {
                keys.push(e.key.toUpperCase());
            }

            const pressedCombo = keys.join(' + ');
            const matchedModel = activeModels.find(m => m.shortcut && m.shortcut.toUpperCase() === pressedCombo);
            
            if (matchedModel) {
                e.preventDefault();
                e.stopPropagation();
                
                // Cola o texto combinando apenas as linhas ativas e de texto (Ignora cliques/Waits)
                const textToPaste = matchedModel.fields.filter(f => f.enabled !== false && f.type !== 'wait' && f.type !== 'click' && f.value).map(f => f.value).join('\n\n');
                const activeEl = document.activeElement;
                
                if (activeEl && (activeEl.isContentEditable || activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'INPUT')) {
                    if (activeEl.isContentEditable) {
                        document.execCommand('insertText', false, textToPaste);
                    } else {
                        const start = activeEl.selectionStart;
                        const end = activeEl.selectionEnd;
                        const text = activeEl.value;
                        
                        const nativeSetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(activeEl), "value")?.set;
                        const newText = text.substring(0, start) + textToPaste + text.substring(end);

                        if (nativeSetter) nativeSetter.call(activeEl, newText); else activeEl.value = newText;
                        
                        activeEl.selectionStart = activeEl.selectionEnd = start + textToPaste.length;
                        activeEl.dispatchEvent(new Event('input', { bubbles: true }));
                        activeEl.dispatchEvent(new Event('change', { bubbles: true }));
                    }
                } else {
                    chrome.runtime.sendMessage({ action: "runModel", model: matchedModel });
                }
            }
        }, true);
    }
});