import { state } from './state.js';
import { config } from './config.js';
import { initDB, getFromDB } from './db.js';
import { MusicPlayer } from './musicPlayer.js';
import { ActivityViewer } from './activityViewer.js';
import { setupEventListeners } from './eventListeners.js';
import { loadInitialContent, initializeFavorites, initializeUserData, loadLocalContent, applyTheme, applyHeroVisibility } from './ui.js';
import { showNotification, _ } from './utils.js';

async function loadSettings() {
    try {
        const settingsData = await getFromDB('settings');
        if (settingsData && settingsData.length > 0) {
            state.settings = { ...state.settings, ...settingsData[0] };
        } else {
            state.settings.language = chrome.i18n.getUILanguage().split('-')[0];
        }

        if (!state.settings.apiKey) {
            state.settings.apiKey = config.defaultApiKey;
        }

        const jellyfinSettingsData = await getFromDB('jellyfin_settings');
        if (jellyfinSettingsData && jellyfinSettingsData.length > 0) {
            state.jellyfinSettings = { ...state.jellyfinSettings, ...jellyfinSettingsData[0] };
        }

    } catch (error) {
        console.error("Could not load settings from DB, using defaults.", error);
        state.settings.language = chrome.i18n.getUILanguage().split('-')[0];
    }
}

document.addEventListener('DOMContentLoaded', async () => {
    try {
        await initDB();
        await loadSettings();
        
        applyTheme(state.settings.theme);
        applyHeroVisibility(state.settings.showHero);

        gsap.registerPlugin(ScrollTrigger);
        
        state.musicPlayer = new MusicPlayer();
        state.musicPlayer.setDB(state.db);
        state.activityViewer = new ActivityViewer(document.getElementById('activityViewerModal'));


        initializeFavorites();
        initializeUserData();
        
        await loadLocalContent();
        await loadInitialContent();

        setupEventListeners();
        initializeThirdPartyLibs();

    } catch (error) {
        console.error("Fatal Initialization failed:", error);
        showNotification(_("fatalInitError"), "error");
        document.getElementById('main-container').innerHTML = `<div class="container text-center mt-5 pt-5"><h1 class="text-danger">${_("fatalInitError")}</h1><p>${_("fatalInitErrorSub")}</p></div>`;
    }
});

function initializeThirdPartyLibs() {
    if (typeof particlesJS !== 'undefined') {
        particlesJS('particles-js', {
            "particles": { "number": { "value": 45 }, "color": { "value": "#0072ff" }, "shape": { "type": "circle" }, "opacity": { "value": 0.25, "random": true }, "size": { "value": 2.5, "random": true }, "line_linked": { "enable": true, "distance": 150, "color": "#00e0ff", "opacity": 0.1 }, "move": { "enable": true, "speed": 1.2, "direction": "none", "random": true, "out_mode": "out" } },
            "interactivity": { "events": { "onhover": { "enable": true, "mode": "grab" } }, "modes": { "grab": { "distance": 120, "line_linked": { "opacity": 0.3 } } } },
            "retina_detect": true
        });
    }

    if (typeof ace !== 'undefined') {
        try {
            state.aceEditor = ace.edit("editor");
            state.aceEditor.setTheme("ace/theme/monokai");
            state.aceEditor.session.setMode("ace/mode/json");
            state.aceEditor.setOptions({ fontSize: "14px", useWorker: false });
        } catch(e) {
            state.aceEditor = null;
        }
    }
}