document.addEventListener('DOMContentLoaded', async () => {
    const listContainer = document.getElementById('list');
    const searchInput = document.querySelector('.search-box');
    
    // Check if we have a session or need to login
    // For simplicity in this version, we'll ask for the master password if not stored
    let masterPassword = await getStoredMasterPassword();
    
    if (!masterPassword) {
        masterPassword = prompt("Digite sua Senha Mestra PIKEY:");
        if (masterPassword) {
            saveMasterPassword(masterPassword);
        }
    }

    if (masterPassword) {
        loadPasswords(masterPassword);
    }

    async function loadPasswords(mp) {
        listContainer.innerHTML = '<div style="padding:20px; text-align:center;">Carregando...</div>';
        try {
            const passwords = await extensionDB.getPasswords(mp);
            renderList(passwords);
        } catch (error) {
            listContainer.innerHTML = `<div style="color:red; padding:10px;">Erro: ${error.message}</div>`;
        }
    }

    function renderList(passwords) {
        listContainer.innerHTML = '';
        if (passwords.length === 0) {
            listContainer.innerHTML = '<div style="padding:20px; text-align:center; color:#94a3b8;">Nenhuma senha encontrada.</div>';
            return;
        }

        passwords.forEach(pw => {
            const item = document.createElement('div');
            item.className = 'pw-item';
            item.innerHTML = `
                <button class="btn-fill" data-user="${pw.username}" data-pass="${pw.password}">Preencher</button>
                <div class="pw-name">${pw.siteName}</div>
                <div class="pw-user">${pw.username}</div>
            `;

            item.querySelector('.btn-fill').addEventListener('click', (e) => {
                const user = e.target.getAttribute('data-user');
                const pass = e.target.getAttribute('data-pass');
                fillForm(user, pass);
            });

            listContainer.appendChild(item);
        });
    }

    function fillForm(user, pass) {
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            chrome.tabs.sendMessage(tabs[0].id, {
                action: "autofill",
                data: { username: user, password: pass }
            }, (response) => {
                if (chrome.runtime.lastError) {
                    console.error("Erro ao enviar mensagem:", chrome.runtime.lastError);
                    alert("Por favor, atualize a página para ativar a extensão.");
                } else if (response && response.status === "success") {
                    window.close(); // Fecha o popup após preencher
                }
            });
        });
    }

    // Storage Utils
    async function getStoredMasterPassword() {
        return new Promise(resolve => {
            chrome.storage.local.get(['masterPassword'], (result) => {
                resolve(result.masterPassword);
            });
        });
    }

    function saveMasterPassword(mp) {
        chrome.storage.local.set({masterPassword: mp});
    }

    // Search logic
    searchInput.addEventListener('input', (e) => {
        const term = e.target.value.toLowerCase();
        const items = listContainer.querySelectorAll('.pw-item');
        items.forEach(item => {
            const name = item.querySelector('.pw-name').innerText.toLowerCase();
            const user = item.querySelector('.pw-user').innerText.toLowerCase();
            if (name.includes(term) || user.includes(term)) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
});
