// popup.js

const TEMPLATE_STORAGE_KEY = 'message_templates';

async function getTemplates() {
    try {
        const result = await browser.storage.local.get(TEMPLATE_STORAGE_KEY);
        return result[TEMPLATE_STORAGE_KEY] || [];
    } catch (error) {
        console.error("Error retrieving templates in popup:", error);
        return [];
    }
}

function insertTemplateAndClose(templateText) {
    // Check if a prefix template is selected
    const prefixSelect = document.getElementById('prefix-select');
    const prefixContent = prefixSelect ? prefixSelect.value : '';

    const combinedText = prefixContent
        ? prefixContent + '<br>' + templateText
        : templateText;

    browser.runtime.sendMessage({
        action: 'insertTemplate',
        text: combinedText
    }).catch(e => console.error("Error sending message to background:", e));
    window.close();
}

async function renderPopupButtons() {
    const templates = await getTemplates();
    const templateList = document.getElementById('template-list');
    templateList.innerHTML = '';

    if (templates.length === 0) {
        templateList.innerHTML = `
            <div class="empty-state">
                Keine Vorlagen vorhanden.<br>
                <a href="#" id="open-options">Jetzt einrichten</a>
            </div>`;
        document.getElementById('open-options').addEventListener('click', (e) => {
            e.preventDefault();
            browser.runtime.openOptionsPage();
            window.close();
        });
        return;
    }

    // Populate prefix dropdown
    const prefixSection = document.getElementById('prefix-section');
    const prefixSelect = document.getElementById('prefix-select');
    if (templates.length > 1) {
        prefixSection.style.display = '';
        templates.forEach(template => {
            const option = document.createElement('option');
            option.value = template.content;
            option.textContent = template.name;
            option.dataset.name = template.name;
            prefixSelect.appendChild(option);
        });

        // Restore last selection
        const saved = await browser.storage.local.get('last_prefix');
        if (saved.last_prefix) {
            const match = [...prefixSelect.options].find(o => o.dataset.name === saved.last_prefix);
            if (match) prefixSelect.value = match.value;
        }

        // Save selection on change
        prefixSelect.addEventListener('change', () => {
            const selected = prefixSelect.selectedOptions[0];
            const name = selected?.dataset?.name || '';
            browser.storage.local.set({ last_prefix: name });
        });
    }

    templates.forEach(template => {
        const button = document.createElement('button');
        button.textContent = template.name;
        button.addEventListener('click', () => {
            insertTemplateAndClose(template.content);
        });
        templateList.appendChild(button);
    });

    // Footer with manage link
    const footer = document.createElement('div');
    footer.className = 'footer';
    const manageLink = document.createElement('a');
    manageLink.href = "#";
    manageLink.textContent = 'Vorlagen verwalten';
    manageLink.addEventListener('click', (e) => {
        e.preventDefault();
        browser.runtime.openOptionsPage();
        window.close();
    });
    footer.appendChild(manageLink);
    templateList.parentNode.appendChild(footer);
}

document.addEventListener('DOMContentLoaded', renderPopupButtons);
