(function () {
    const DEFAULT_THEME = 'aurora';
    const DEFAULT_WIDTH = 'expanded';

    const root = document.documentElement;

    const applyTheme = (key) => {
        const value = key && key.trim() ? key : DEFAULT_THEME;

        console.log('[ThemeManager.js] applyTheme called:', {
            key,
            value,
            currentTheme: getTheme(),
            stackTrace: new Error().stack
        });

        clearCustomThemeStyles();

        root.setAttribute('data-theme', value);
    };

    const clearCustomThemeStyles = () => {
        const customProps = [
            '--theme-background',
            '--theme-surface',
            '--theme-surface-alt',
            '--theme-surface-muted',
            '--theme-surface-pop',
            '--theme-border',
            '--theme-border-strong',
            '--theme-shadow-soft',
            '--theme-shadow-pop',
            '--theme-overlay',
            '--theme-text-primary',
            '--theme-text-secondary',
            '--theme-text-muted',
            '--theme-text-inverse',
            '--theme-accent',
            '--theme-accent-active',
            '--theme-accent-soft',
            '--theme-accent-strong',
            '--pane-background',
            '--pane-border',
            '--surface-card',
            '--surface-card-alt',
            '--surface-elevated',
            '--theme-content-surface',
            '--theme-content-surface-alt',
            '--control-border',
            '--control-border-hover',
            '--control-background'
        ];

        customProps.forEach(prop => {
            root.style.removeProperty(prop);
        });
    };

    const getTheme = () => root.getAttribute('data-theme');

    const applyContentWidth = (mode) => {
        const value = mode && mode.trim() ? mode : DEFAULT_WIDTH;
        root.setAttribute('data-content-width', value);
    };

    const getContentWidth = () => root.getAttribute('data-content-width');

    const applyCustomTheme = (themeKey, accentColor, isDark) => {
        console.log('[ThemeManager.js] applyCustomTheme called:', {
            themeKey,
            accentColor,
            isDark,
            currentTheme: getTheme(),
            stackTrace: new Error().stack
        });

        root.setAttribute('data-theme', themeKey);

        const hsl = hexToHsl(accentColor);
        const h = hsl.h;
        const s = hsl.s;
        const l = hsl.l;

        if (isDark) {
            root.style.setProperty('--theme-background', `hsl(${h}, ${Math.max(s - 20, 20)}%, 8%)`);
            root.style.setProperty('--theme-surface', `hsla(${h}, ${Math.max(s - 30, 15)}%, 14%, 0.94)`);
            root.style.setProperty('--theme-surface-alt', `hsla(${h}, ${Math.max(s - 25, 18)}%, 18%, 0.88)`);
            root.style.setProperty('--theme-surface-muted', `hsla(${h}, ${Math.max(s - 15, 25)}%, 22%, 0.5)`);
            root.style.setProperty('--theme-surface-pop', `hsla(${h}, ${Math.max(s - 28, 12)}%, 12%, 0.95)`);
            root.style.setProperty('--theme-border', `hsla(${h}, ${s}%, ${Math.min(l + 15, 65)}%, 0.32)`);
            root.style.setProperty('--theme-border-strong', `hsla(${h}, ${s}%, ${Math.min(l + 20, 70)}%, 0.42)`);
            root.style.setProperty('--theme-shadow-soft', `0 22px 46px hsla(${h}, ${s - 10}%, 4%, 0.46)`);
            root.style.setProperty('--theme-shadow-pop', `0 26px 56px hsla(${h}, ${s - 10}%, 4%, 0.54)`);
            root.style.setProperty('--theme-overlay', `hsla(${h}, ${s - 8}%, 6%, 0.32)`);

            root.style.setProperty('--theme-text-primary', '#f8f5ff');
            root.style.setProperty('--theme-text-secondary', 'rgba(226, 208, 255, 0.8)');
            root.style.setProperty('--theme-text-muted', 'rgba(222, 205, 255, 0.78)');
            root.style.setProperty('--theme-text-inverse', '#fdf8ff');

            root.style.setProperty('--theme-accent', accentColor);
            root.style.setProperty('--theme-accent-active', shadeColor(accentColor, 0.85));
            root.style.setProperty('--theme-accent-soft', `${accentColor}3d`);
            root.style.setProperty('--theme-accent-strong', `${accentColor}52`);

            root.style.setProperty('--pane-background', `linear-gradient(165deg, hsla(${h}, ${s}%, 12%, 0.96) 0%, hsla(${h}, ${s - 5}%, 16%, 0.92) 55%, hsla(${h}, ${s + 5}%, 8%, 0.96) 100%)`);
            root.style.setProperty('--pane-border', `hsla(${h}, ${s}%, ${Math.min(l + 20, 70)}%, 0.28)`);
        } else {
            root.style.setProperty('--theme-background', `hsl(${h}, ${Math.max(s - 30, 15)}%, 97%)`);
            root.style.setProperty('--theme-surface', `hsla(${h}, ${Math.max(s - 35, 10)}%, 99%, 0.94)`);
            root.style.setProperty('--theme-surface-alt', `hsla(${h}, ${Math.max(s - 30, 12)}%, 95%, 0.82)`);
            root.style.setProperty('--theme-surface-muted', `hsla(${h}, ${Math.max(s - 25, 15)}%, 92%, 0.7)`);
            root.style.setProperty('--theme-surface-pop', `hsla(${h}, ${Math.max(s - 32, 8)}%, 98%, 0.98)`);
            root.style.setProperty('--theme-border', `hsla(${h}, ${s - 10}%, ${l - 15}%, 0.14)`);
            root.style.setProperty('--theme-border-strong', `hsla(${h}, ${s - 8}%, ${l - 20}%, 0.28)`);
            root.style.setProperty('--theme-shadow-soft', `0 18px 32px hsla(${h}, ${s}%, ${l - 35}%, 0.12)`);
            root.style.setProperty('--theme-shadow-pop', `0 22px 44px hsla(${h}, ${s}%, ${l - 35}%, 0.18)`);
            root.style.setProperty('--theme-overlay', `hsla(${h}, ${s}%, ${l - 30}%, 0.22)`);

            root.style.setProperty('--theme-text-primary', '#101828');
            root.style.setProperty('--theme-text-secondary', '#334155');
            root.style.setProperty('--theme-text-muted', '#38475b');
            root.style.setProperty('--theme-text-inverse', '#ffffff');

            root.style.setProperty('--theme-accent', accentColor);
            root.style.setProperty('--theme-accent-active', shadeColor(accentColor, 0.85));
            root.style.setProperty('--theme-accent-soft', `${accentColor}2e`);
            root.style.setProperty('--theme-accent-strong', `${accentColor}52`);

            root.style.setProperty('--pane-background', `linear-gradient(160deg, hsla(${h}, ${s}%, ${l - 25}%, 0.96) 0%, hsla(${h}, ${s - 5}%, ${l - 20}%, 0.94) 50%, hsla(${h}, ${s + 5}%, ${l - 30}%, 0.97) 100%)`);
            root.style.setProperty('--pane-border', `hsla(${h}, ${s}%, ${l + 10}%, 0.22)`);
        }

        root.style.setProperty('--surface-card', 'var(--theme-surface)');
        root.style.setProperty('--surface-card-alt', 'var(--theme-surface-alt)');
        root.style.setProperty('--surface-elevated', 'var(--theme-surface-pop)');
        root.style.setProperty('--theme-content-surface', 'color-mix(in srgb, var(--theme-surface) 94%, transparent 6%)');
        root.style.setProperty('--theme-content-surface-alt', 'color-mix(in srgb, var(--theme-surface-alt) 92%, transparent 8%)');
        root.style.setProperty('--control-border', 'color-mix(in srgb, var(--theme-border-strong) 65%, transparent 35%)');
        root.style.setProperty('--control-border-hover', 'color-mix(in srgb, var(--theme-accent) 40%, var(--control-border) 60%)');
        root.style.setProperty('--control-background', 'color-mix(in srgb, var(--theme-surface) 90%, transparent 10%)');
    };

    const hexToHsl = (hex) => {
        hex = hex.replace('#', '');
        const r = parseInt(hex.substring(0, 2), 16) / 255;
        const g = parseInt(hex.substring(2, 4), 16) / 255;
        const b = parseInt(hex.substring(4, 6), 16) / 255;

        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;

        if (max === min) {
            h = s = 0;
        } else {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }

        return {
            h: Math.round(h * 360),
            s: Math.round(s * 100),
            l: Math.round(l * 100)
        };
    };

    const shadeColor = (color, factor) => {
        const hsl = hexToHsl(color);
        const newL = Math.min(100, Math.max(0, Math.round(hsl.l * factor)));
        return hslToHex(hsl.h, hsl.s, newL);
    };

    const hslToHex = (h, s, l) => {
        h = h / 360;
        s = s / 100;
        l = l / 100;

        let r, g, b;

        if (s === 0) {
            r = g = b = l;
        } else {
            const hue2rgb = (p, q, t) => {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1 / 6) return p + (q - p) * 6 * t;
                if (t < 1 / 2) return q;
                if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                return p;
            };

            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;

            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }

        const toHex = (x) => {
            const hex = Math.round(x * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        };

        return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    };

    // 不再主动设置默认值，完全由 Blazor 控制主题初始化
    // 这样避免了 JS 和 Blazor 之间的竞态条件

    window.MiracleTheme = window.MiracleTheme || {};
    window.MiracleTheme.applyTheme = applyTheme;
    window.MiracleTheme.getTheme = getTheme;
    window.MiracleTheme.applyContentWidth = applyContentWidth;
    window.MiracleTheme.getContentWidth = getContentWidth;
    window.MiracleTheme.applyCustomTheme = applyCustomTheme;
})();
