// Language/Culture management functions
window.blazorCulture = {
    get: () => {
        try {
            // Try to get from cookie first (server-side compatible)
            const cookieValue = getCookie('BlazorCulture');
            if (cookieValue) {
                // Extract culture from ASP.NET Core cookie format: c=en|uic=en
                const match = cookieValue.match(/c=([^|]+)/);
                if (match) {
                    return match[1];
                }
                // Fallback: if it's just the culture code directly
                return cookieValue;
            }
            
            // Fallback to localStorage, then default
            return window.localStorage.getItem('BlazorCulture') || 'en';
        } catch (error) {
            console.error('Error getting culture:', error);
            return 'en';
        }
    },
    set: (value) => {
        try {
            // Set cookie in ASP.NET Core expected format: c=en|uic=en
            const aspNetCoreFormat = `c=${value}|uic=${value}`;
            setCookie('BlazorCulture', aspNetCoreFormat, 365);
            
            // Also set localStorage as backup (simple format)
            window.localStorage.setItem('BlazorCulture', value);
            
            console.log(`Culture set to: ${value} (ASP.NET Core format: ${aspNetCoreFormat})`);
            return true;
        } catch (error) {
            console.error('Error setting culture:', error);
            return false;
        }
    },
    getBrowserLanguage: () => {
        try {
            // Get browser language from navigator
            const language = navigator.language || navigator.languages[0] || 'en';
            console.log(`Browser language detected: ${language}`);
            return language;
        } catch (error) {
            console.error('Error getting browser language:', error);
            return 'en';
        }
    }
};

// Cookie helper functions
function getCookie(name) {
    try {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) {
            const cookieValue = decodeURIComponent(parts.pop().split(';').shift());
            console.log(`Cookie ${name} retrieved: ${cookieValue}`);
            return cookieValue;
        }
        console.log(`Cookie ${name} not found`);
        return null;
    } catch (error) {
        console.error(`Error getting cookie ${name}:`, error);
        return null;
    }
}

function setCookie(name, value, days = 365) {
    try {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        const encodedValue = encodeURIComponent(value);
        const cookieString = `${name}=${encodedValue};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
        document.cookie = cookieString;
        console.log(`Cookie ${name} set: ${value} (encoded: ${encodedValue}, expires: ${expires.toUTCString()})`);
        return true;
    } catch (error) {
        console.error(`Error setting cookie ${name}:`, error);
        return false;
    }
}

// Theme management functions using cookies
window.applyTheme = function (themeName, cssVariables) {
    try {
        const root = document.documentElement;
        
        // Apply CSS custom properties
        for (const [property, value] of Object.entries(cssVariables)) {
            root.style.setProperty(property, value);
        }
        
        // Add theme class to body
        document.body.classList.remove('theme-light', 'theme-dark');
        document.body.classList.add(`theme-${themeName}`);
        
        // Store theme preference in cookie (365 days expiry)
        setCookie('BlazorTheme', themeName, 365);
        
        console.log(`Applied ${themeName} theme with custom properties and saved to cookie`);
        return true;
    } catch (error) {
        console.error('Error applying theme:', error);
        return false;
    }
};

window.getStoredTheme = function () {
    try {
        return getCookie('BlazorTheme') || 'light';
    } catch (error) {
        console.error('Error getting stored theme from cookie:', error);
        return 'light';
    }
};

window.setStoredTheme = function (theme) {
    try {
        setCookie('BlazorTheme', theme, 365);
        return true;
    } catch (error) {
        console.error('Error setting stored theme in cookie:', error);
        return false;
    }
};

// Initialize theme on page load from cookie
window.initializeThemeFromStorage = function () {
    try {
        const storedTheme = window.getStoredTheme();
        if (storedTheme) {
            document.body.classList.remove('theme-light', 'theme-dark');
            document.body.classList.add(`theme-${storedTheme}`);
            console.log(`Initialized theme from cookie: ${storedTheme}`);
        }
        return storedTheme;
    } catch (error) {
        console.error('Error initializing theme from cookie:', error);
        return 'light';
    }
};

// Enhanced theme initialization that persists across page navigation
window.initializeAndPersistTheme = function () {
    try {
        // Apply stored theme immediately
        const theme = window.initializeThemeFromStorage();
        
        // Listen for page navigation to reapply theme
        if (window.Blazor) {
            // Blazor Server: Listen for circuit reconnection
            window.Blazor.reconnect = (function (originalReconnect) {
                return function () {
                    const result = originalReconnect.apply(this, arguments);
                    setTimeout(() => window.initializeThemeFromStorage(), 100);
                    return result;
                };
            })(window.Blazor.reconnect || function () { });
        }
        
        // Listen for Blazor component updates
        document.addEventListener('DOMContentLoaded', window.initializeThemeFromStorage);
        
        return theme;
    } catch (error) {
        console.error('Error in theme initialization:', error);
        return 'light';
    }
};

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

// Reapply theme when page visibility changes (handles tab switching)
document.addEventListener('visibilitychange', function () {
    if (!document.hidden) {
        setTimeout(() => window.initializeThemeFromStorage(), 50);
    }
});

// Handle Blazor navigation events
window.addEventListener('enhancedload', window.initializeThemeFromStorage);
window.addEventListener('pageshow', window.initializeThemeFromStorage);