/**
 * FocusFeed Options Logic
 * Supports Chrome Storage and LocalStorage fallback for web preview.
 */

const storage = (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) ? chrome.storage.local : {
    get: (keys, cb) => {
        const res = {};
        keys.forEach(k => {
            const val = localStorage.getItem(k);
            res[k] = val ? JSON.parse(val) : null;
        });
        cb(res);
    },
    set: (obj, cb) => {
        Object.keys(obj).forEach(k => localStorage.setItem(k, JSON.stringify(obj[k])));
        if (cb) cb();
    }
};

// Elements
const keywordsContainer = document.getElementById('keywordsContainer');
const newKeywordInput = document.getElementById('newKeyword');
const addBtn = document.getElementById('addBtn');
const listCount = document.getElementById('listCount');
const saveIndicator = document.getElementById('saveIndicator');

// Navigation Elements
const navItems = {
    'navSperrliste': 'viewSperrliste',
    'navStatistiken': 'viewStatistiken',
    'navCommunity': 'viewCommunity',
    'navKI': 'viewKI'
};

let userKeywords = [];

// Initialize
function init() {
    // Load existing keywords
    storage.get(['customKeywords'], (result) => {
        userKeywords = result.customKeywords || [];
        renderKeywords();
    });

    // Setup Navigation
    Object.keys(navItems).forEach(id => {
        const navEl = document.getElementById(id);
        if (navEl) {
            navEl.addEventListener('click', (e) => {
                e.preventDefault();
                switchView(id);
            });
        }
    });

    // Setup Add Keyword
    // Export/Import Logic
    const exportBtn = document.getElementById('exportBtn');
    const importBtn = document.getElementById('importBtn');
    const importFile = document.getElementById('importFile');

    exportBtn.addEventListener('click', () => {
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(userKeywords));
        const downloadAnchorNode = document.createElement('a');
        downloadAnchorNode.setAttribute("href",     dataStr);
        downloadAnchorNode.setAttribute("download", "focusfeed_blocklist.json");
        document.body.appendChild(downloadAnchorNode);
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
    });

    importBtn.addEventListener('click', () => {
        importFile.click();
    });

    importFile.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const imported = JSON.parse(e.target.result);
                if (Array.isArray(imported)) {
                    userKeywords = [...new Set([...userKeywords, ...imported])];
                    saveKeywords();
                    alert('Liste erfolgreich importiert!');
                }
            } catch (err) {
                alert('Fehler beim Importieren der Datei.');
            }
        };
        reader.readAsText(file);
    });

    addBtn.addEventListener('click', () => {
        const kw = newKeywordInput.value.trim().toLowerCase();
        if (kw && !userKeywords.includes(kw)) {
            userKeywords.push(kw);
            newKeywordInput.value = '';
            saveKeywords();
        }
    });

    newKeywordInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addBtn.click();
    });
}

function switchView(activeNavId) {
    // Update Nav UI
    Object.keys(navItems).forEach(id => {
        document.getElementById(id).classList.remove('active');
        document.getElementById(navItems[id]).style.display = 'none';
    });

    document.getElementById(activeNavId).classList.add('active');
    document.getElementById(navItems[activeNavId]).style.display = 'block';

    // Special logic for stats
    if (activeNavId === 'navStatistiken') {
        renderStats();
    }
}

function renderKeywords() {
    keywordsContainer.innerHTML = '';
    userKeywords.forEach((kw, index) => {
        const tag = document.createElement('div');
        tag.className = 'keyword-tag';
        tag.innerHTML = `
            <span>${kw}</span>
            <button data-index="${index}">&times;</button>
        `;
        keywordsContainer.appendChild(tag);
    });
    
    listCount.innerText = `${userKeywords.length} Begriffe`;

    // Add delete listeners
    document.querySelectorAll('.keyword-tag button').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const index = e.target.dataset.index;
            userKeywords.splice(index, 1);
            saveKeywords();
        });
    });
}

function saveKeywords() {
    storage.set({ customKeywords: userKeywords }, () => {
        renderKeywords();
        showSaveIndicator();
    });
}

function renderStats() {
    storage.get(['stats'], (result) => {
        const stats = result.stats || { total: 0, keywords: 0, ai: 0, shorts: 0 };
        
        // Time Calculation (Weighted)
        const totalMinutes = Math.round(((stats.keywords * 15) + (stats.ai * 15) + (stats.shorts * 45)) / 60);
        
        document.getElementById('statTime').innerText = `${totalMinutes} min`;
        document.getElementById('statTotal').innerText = stats.total || 0;
        document.getElementById('statKeywords').innerText = stats.keywords || 0;
        document.getElementById('statAI').innerText = stats.ai || 0;
        document.getElementById('statShorts').innerText = stats.shorts || 0;

        // Determine Top Trigger
        const triggerMap = { 'Keywords': stats.keywords, 'KI-Muster': stats.ai, 'Shorts': stats.shorts };
        const topTrigger = Object.keys(triggerMap).reduce((a, b) => triggerMap[a] > triggerMap[b] ? a : b);
        document.getElementById('statTopTrigger').innerText = stats.total > 0 ? topTrigger : '-';

        // Render Bar Chart
        const chart = document.getElementById('barChart');
        chart.innerHTML = '';
        
        const categories = [
            { label: 'Keywords', value: stats.keywords || 0 },
            { label: 'KI-Muster', value: stats.ai || 0 },
            { label: 'Shorts', value: stats.shorts || 0 }
        ];

        const max = Math.max(...categories.map(c => c.value), 1);

        categories.forEach(cat => {
            const height = (cat.value / max) * 100;
            const wrapper = document.createElement('div');
            wrapper.className = 'bar-wrapper';
            wrapper.innerHTML = `
                <div class="bar" style="height: ${height}%" data-value="${cat.value}"></div>
                <span class="bar-label">${cat.label}</span>
            `;
            chart.appendChild(wrapper);
        });
    });
}

function showSaveIndicator() {
    saveIndicator.classList.add('visible');
    setTimeout(() => {
        saveIndicator.classList.remove('visible');
    }, 2000);
}

// Start
init();
