/**
 * Theme helper utilities
 * Centralizes interactions with document.documentElement CSS variables and related localStorage keys.
 * This ensures all callers use the same behavior for setting/removing CSS variables and persisting sidebar colors.
 */
export const SIDEBAR_COLOR_KEY = 'sidebar-dark-color';
export const PRIMARY_FOREGROUND_KEY = 'primary-foreground-color';
// Indicates whether the stored sidebar color is an explicit sidebar-only override
// values: 'explicit' = user chose the "Dark Sidebar" option, 'follow' = sidebar follows theme (or not set)
export const SIDEBAR_OVERRIDE_KEY = 'sidebar-override';
export const MENU_ACTIVE_KEY = 'menu-active-color';

/**
 * Set a CSS variable on the root element (document.documentElement).
 * This wraps document.documentElement.style.setProperty so callers don't repeat the DOM check.
 *
 * Example: setCssVar('--color-primary', '#ff0000')
 */
export function setCssVar(varName: string, value: string) {
    if (typeof document !== 'undefined') {
        document.documentElement.style.setProperty(varName, value);
    }
}

/**
 * Remove a CSS variable from the root element.
 */
export function removeCssVar(varName: string) {
    if (typeof document !== 'undefined') {
        document.documentElement.style.removeProperty(varName);
    }
}

/**
 * Convenience function to set sidebar-related colors and persist them to localStorage.
 */
export function setSidebarColors(sidebarColor: string, primaryForeground: string, menuActive?: string) {
    setCssVar('--color-sidebar-dark', sidebarColor);
    setCssVar('--color-text-primary', '#ffffff');
    setCssVar('--color-primary-foreground', primaryForeground);
    if (typeof localStorage !== 'undefined') {
        localStorage.setItem(SIDEBAR_COLOR_KEY, sidebarColor);
        localStorage.setItem(PRIMARY_FOREGROUND_KEY, primaryForeground);
    }

    // Only set --menu-active when explicitly provided (used for the dark-sidebar override).
    if (menuActive) {
        setCssVar('--menu-active', menuActive);
        if (typeof localStorage !== 'undefined') {
            localStorage.setItem(MENU_ACTIVE_KEY, menuActive);
            // If a menuActive color is provided, treat this as an explicit sidebar-only override
            // so the UI can preserve the dark-sidebar selection across reloads.
            try {
                localStorage.setItem(SIDEBAR_OVERRIDE_KEY, 'explicit');
            } catch (e) {
                // ignore
            }
        }
    } else {
        // Remove any previously set menu-active so it doesn't persist unintentionally.
        removeCssVar('--menu-active');
        if (typeof localStorage !== 'undefined') {
            localStorage.removeItem(MENU_ACTIVE_KEY);
        }
    }
}

/**
 * Clear persisted sidebar colors and remove the CSS variables.
 */
export function clearSidebarColors() {
    removeCssVar('--color-sidebar-dark');
    removeCssVar('--color-primary-foreground');
    if (typeof localStorage !== 'undefined') {
        localStorage.removeItem(SIDEBAR_COLOR_KEY);
        localStorage.removeItem(PRIMARY_FOREGROUND_KEY);
        localStorage.removeItem(SIDEBAR_OVERRIDE_KEY);
    }
}

/**
 * Initialize sidebar related CSS variables on page load based on persisted values
 * and the provided appearance. This ensures --menu-active and sidebar colors are
 * applied correctly after a reload.
 *
 * @param appearance optional appearance value ('light'|'dark'|'system') used to
 *                   derive defaults when persisted values are not present.
 */
export function initializeSidebarColors(appearance?: 'light' | 'dark' | 'system') {
    try {
        const persistedSidebar = typeof localStorage !== 'undefined' ? localStorage.getItem(SIDEBAR_COLOR_KEY) : null;
        const persistedPrimary = typeof localStorage !== 'undefined' ? localStorage.getItem(PRIMARY_FOREGROUND_KEY) : null;
        const persistedMenuActive = typeof localStorage !== 'undefined' ? localStorage.getItem(MENU_ACTIVE_KEY) : null;
        const sidebarOverride = typeof localStorage !== 'undefined' ? localStorage.getItem(SIDEBAR_OVERRIDE_KEY) : null;

        // Resolve appearance -> isDark when needed
        let isDark = false;
        if (appearance === 'dark') isDark = true;
        else if (appearance === 'light') isDark = false;
        else if (appearance === 'system') {
            if (typeof window !== 'undefined') {
                isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            }
        } else {
            // If appearance not provided, fall back to saved appearance in localStorage
            const saved = typeof localStorage !== 'undefined' ? (localStorage.getItem('appearance') as 'light' | 'dark' | 'system' | null) : null;
            if (saved === 'dark') isDark = true;
            else if (saved === 'light') isDark = false;
            else if (saved === 'system' && typeof window !== 'undefined') {
                isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            }
        }

        // If there is an explicit sidebar-only override, prefer persisted values for sidebar
        // and menu-active so the dark-sidebar selection is preserved across reloads.
        if (sidebarOverride === 'explicit') {
            const sidebarColorToUse = persistedSidebar || '#12162d';
            const primaryForegroundToUse = persistedPrimary || '#FFFFFF';
            const menuActive = persistedMenuActive || '#020617';
            setSidebarColors(sidebarColorToUse, primaryForegroundToUse, menuActive);
            return;
        }

        // No explicit override — sidebar should follow the current appearance (isDark)
        const sidebarColor = isDark ? '#12162d' : '#ffffff';
        const primaryForeground = isDark ? '#FFFFFF' : '#3F3F46';
        setSidebarColors(sidebarColor, primaryForeground);
    } catch (e) {
        // ignore errors during init
    }
}
