/**
 * Theme management for GraphTalker
 *
 * Supports URL parameter for easy demo links:
 *   https://demo.example.com/?theme=sib
 *
 * Theme is saved to localStorage and persists across navigation.
 *
 * Console API:
 *   __setTheme('sib')     - Switch to SIB theme
 *   __setTheme('default') - Switch to default theme
 *   __getTheme()          - Get current theme
 *   __themes              - List available themes
 */
(function() {
    'use strict';

    const STORAGE_KEY = 'graphtalker-theme';
    const URL_PARAM = 'theme';
    const DEFAULT_THEME = 'default';

    // Available themes
    const THEMES = ['default', 'sib'];

    /**
     * Apply theme to document body
     */
    const applyTheme = (theme, save = true) => {
        const normalized = String(theme || '').toLowerCase().trim();

        if (!THEMES.includes(normalized)) {
            console.warn('[Theme] Unknown theme:', theme, '| Available:', THEMES.join(', '));
            return false;
        }

        if (normalized === 'default') {
            document.body.removeAttribute('data-theme');
        } else {
            document.body.setAttribute('data-theme', normalized);
        }

        if (save) {
            try {
                localStorage.setItem(STORAGE_KEY, normalized);
            } catch (e) {
                // localStorage may be unavailable in some contexts
            }
        }

        return true;
    };

    /**
     * Get theme from URL parameter
     */
    const getThemeFromURL = () => {
        try {
            const params = new URLSearchParams(window.location.search);
            return params.get(URL_PARAM);
        } catch (e) {
            return null;
        }
    };

    /**
     * Get theme from localStorage
     */
    const getThemeFromStorage = () => {
        try {
            return localStorage.getItem(STORAGE_KEY);
        } catch (e) {
            return null;
        }
    };

    /**
     * Get current active theme
     */
    const getTheme = () => {
        const bodyTheme = document.body?.getAttribute('data-theme');
        return bodyTheme || getThemeFromStorage() || DEFAULT_THEME;
    };

    /**
     * Initialize theme on page load
     * Priority: URL param > localStorage > default
     */
    const initTheme = () => {
        // 1. Check URL parameter (highest priority - for demo links)
        const urlTheme = getThemeFromURL();
        if (urlTheme && THEMES.includes(urlTheme.toLowerCase())) {
            applyTheme(urlTheme);
            return;
        }

        // 2. Check localStorage
        const storedTheme = getThemeFromStorage();
        if (storedTheme && THEMES.includes(storedTheme)) {
            applyTheme(storedTheme, false); // Don't re-save
            return;
        }

        // 3. Use default (no attribute needed)
    };

    // Initialize immediately (before DOMContentLoaded to prevent FOUC)
    // But we need body to exist, so use this approach:
    if (document.body) {
        initTheme();
    } else {
        // Body doesn't exist yet - wait for it
        document.addEventListener('DOMContentLoaded', initTheme);
    }

    // Public API
    window.__setTheme = applyTheme;
    window.__getTheme = getTheme;
    window.__themes = THEMES;
})();
