document.addEventListener('DOMContentLoaded', () => {
    const saveView = document.getElementById('saveView');
    const settingsView = document.getElementById('settingsView');
    const showSettings = document.getElementById('showSettings');
    const showSave = document.getElementById('showSave');

    const saveBtn = document.getElementById('saveBtn');
    const saveSettingsBtn = document.getElementById('saveSettingsBtn');

    const apiBaseInput = document.getElementById('apiBase');
    const apiTokenInput = document.getElementById('apiToken');
    const messageEl = document.getElementById('message');

    // Load saved settings
    chrome.storage.sync.get(['apiBase', 'apiToken'], (result) => {
        if (result.apiBase) apiBaseInput.value = result.apiBase;
        if (result.apiToken) apiTokenInput.value = result.apiToken;

        if (!result.apiBase || !result.apiToken) {
            settingsView.classList.add('active');
        } else {
            saveView.classList.add('active');
        }
    });

    showSettings.addEventListener('click', () => {
        saveView.classList.remove('active');
        settingsView.classList.add('active');
    });

    showSave.addEventListener('click', () => {
        settingsView.classList.remove('active');
        saveView.classList.add('active');
    });

    saveSettingsBtn.addEventListener('click', () => {
        let apiBase = apiBaseInput.value.trim().replace(/\/$/, '');
        const apiToken = apiTokenInput.value.trim();

        if (!apiBase || !apiToken) {
            alert('Please fill in both fields');
            return;
        }

        // Add default protocol if missing
        if (!apiBase.startsWith('http://') && !apiBase.startsWith('https://')) {
            apiBase = 'http://' + apiBase;
        }

        chrome.storage.sync.set({ apiBase, apiToken }, () => {
            settingsView.classList.remove('active');
            saveView.classList.add('active');
        });
    });

    saveBtn.addEventListener('click', async () => {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (!tab) return;

        const { apiBase, apiToken } = await chrome.storage.sync.get(['apiBase', 'apiToken']);

        if (!apiBase || !apiToken) {
            showMessage('Settings missing', 'error');
            return;
        }

        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';

        try {
            const response = await fetch(`${apiBase}/api/articles`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiToken}`
                },
                body: JSON.stringify({ url: tab.url })
            });

            const data = await response.json();
            if (data.success) {
                showMessage('Saved successfully!', 'success');
                setTimeout(() => window.close(), 1500);
            } else {
                showMessage('Error: ' + (data.error || 'Unknown error'), 'error');
            }
        } catch (error) {
            showMessage('Network error: ' + error.message, 'error');
        } finally {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save to ArticleBin';
        }
    });

    function showMessage(text, type) {
        messageEl.textContent = text;
        messageEl.className = type;
        messageEl.style.display = 'block';
    }
});
