// Theme switcher functionality
document.addEventListener('DOMContentLoaded', () => {
    const THEME_COOKIE = 'eventmie_theme';
    const THEMES = ['light', 'dark', 'auto'];
    
    // Get default theme from admin panel settings
    const DEFAULT_THEME = defaultTheme || 'auto';

    // Cookie helper functions with better security and error handling
    const setCookie = (name, value, days = 365) => {
        try {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            const expires = `; expires=${date.toUTCString()}`;
            const secure = window.location.protocol === 'https:' ? '; secure' : '';
            document.cookie = `${name}=${encodeURIComponent(value)}${expires}; path=/; SameSite=Strict${secure}`;
            return true;
        } catch (error) {
            console.error('Error setting theme cookie:', error);
            return false;
        }
    };

    const getCookie = (name) => {
        try {
            const nameEQ = `${name}=`;
            const cookies = document.cookie.split(';');
            for (let cookie of cookies) {
                cookie = cookie.trim();
                if (cookie.indexOf(nameEQ) === 0) {
                    return decodeURIComponent(cookie.substring(nameEQ.length));
                }
            }
            return null;
        } catch (error) {
            console.error('Error reading theme cookie:', error);
            return null;
        }
    };

    // Theme management
    const getSystemTheme = () => {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };

    const applyTheme = (theme) => {
        const effectiveTheme = theme === 'auto' ? getSystemTheme() : theme;
        document.documentElement.setAttribute('data-bs-theme', effectiveTheme);
        
        // Update theme icon in button
        const themeIcon = document.querySelector('#themeToggle i');
        if (themeIcon) {
            themeIcon.className = theme === 'auto' 
                ? 'fas fa-circle-half-stroke' 
                : theme === 'dark' 
                    ? 'fas fa-moon' 
                    : 'fas fa-sun';
        }

        // Update active states in dropdown
        document.querySelectorAll('[data-theme]').forEach(button => {
            button.classList.toggle('text-primary', button.getAttribute('data-theme') === theme);
        });
    };

    const setTheme = (newTheme) => {
        if (!THEMES.includes(newTheme)) {
            console.error('Invalid theme:', newTheme);
            newTheme = DEFAULT_THEME;
        }

        // Save theme preference
        if (setCookie(THEME_COOKIE, newTheme)) {
            applyTheme(newTheme);
        }
    };

    // Initialize theme
    const initTheme = () => {
        // Get stored theme or default to admin panel setting
        const storedTheme = getCookie(THEME_COOKIE);
        const initialTheme = THEMES.includes(storedTheme) ? storedTheme : DEFAULT_THEME;
        
        // Apply initial theme
        applyTheme(initialTheme);

        // Set up theme toggle listeners
        document.querySelectorAll('[data-theme]').forEach(button => {
            button.addEventListener('click', () => {
                const theme = button.getAttribute('data-theme');
                setTheme(theme);
            });
        });

        // Listen for system theme changes
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
            const currentTheme = getCookie(THEME_COOKIE) || DEFAULT_THEME;
            if (currentTheme === 'auto') {
                applyTheme('auto');
            }
        });
    };

    // Start the theme system
    initTheme();
}); 