// Theme management JavaScript functions for Blazor

console.log("theme.js loaded");

// Apply theme to the document
window.applyTheme = function (theme, cssVariables) {
    console.log("Applying theme:", theme, "with variables:", cssVariables);
    
    // Remove existing theme classes
    document.body.classList.remove('theme-light', 'theme-dark');
    
    // Add the new theme class
    document.body.classList.add(`theme-${theme}`);
    
    // Apply CSS custom properties to root
    const root = document.documentElement;
    if (cssVariables) {
        Object.entries(cssVariables).forEach(([property, value]) => {
            root.style.setProperty(property, value);
        });
    }
    
    console.log("Theme applied successfully");
};

// Store theme preference in cookie
window.setStoredTheme = function (theme) {
    console.log("Storing theme:", theme);
    
    // Set cookie with 1 year expiration
    const expires = new Date();
    expires.setFullYear(expires.getFullYear() + 1);
    
    document.cookie = `BlazorTheme=${theme}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
    
    console.log("Theme stored in cookie");
};

// Get theme preference from cookie
window.getStoredTheme = function () {
    console.log("Getting stored theme");
    
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
        const [name, value] = cookie.trim().split('=');
        if (name === 'BlazorTheme') {
            console.log("Found stored theme:", value);
            return value;
        }
    }
    
    console.log("No stored theme found, using default");
    return 'light'; // Default theme
};

// Initialize theme on page load
window.initializeTheme = function () {
    console.log("Initializing theme");
    
    const storedTheme = window.getStoredTheme();
    
    // Remove existing theme classes
    document.body.classList.remove('theme-light', 'theme-dark');
    
    // Add the stored theme class
    document.body.classList.add(`theme-${storedTheme}`);
    
    console.log("Theme initialized with:", storedTheme);
    return storedTheme;
};

// Auto-initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', window.initializeTheme);
} else {
    window.initializeTheme();
}