/**
 * 深色主题切换功能
 * 支持自动检测系统主题、手动切换、本地存储
 * 优化版本：防止FOUC、更好的动画、完整的适配
 */

(function() {
    'use strict';

    // 主题管理器类
    class ThemeManager {
        constructor() {
            this.THEME_KEY = 'blog-theme';
            this.THEMES = {
                LIGHT: 'light',
                DARK: 'dark',
                AUTO: 'auto'
            };

            this.currentTheme = null;
            this.systemTheme = null;
            this.isInitialized = false;

            this.init();
        }

        init() {
            if (this.isInitialized) return;
            this.isInitialized = true;

            // 检测系统主题偏好
            this.detectSystemTheme();

            // 加载保存的主题
            this.loadTheme();

            // 立即应用主题（无动画，防止闪烁）
            this.applyTheme(false);

            // 等待DOM加载完成后创建按钮
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => {
                    this.createToggleButton();
                    this.watchSystemTheme();
                });
            } else {
                this.createToggleButton();
                this.watchSystemTheme();
            }
        }

        /**
         * 检测系统主题偏好
         */
        detectSystemTheme() {
            if (window.matchMedia) {
                const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                this.systemTheme = isDark ? this.THEMES.DARK : this.THEMES.LIGHT;
            } else {
                this.systemTheme = this.THEMES.LIGHT;
            }
        }

        /**
         * 监听系统主题变化
         */
        watchSystemTheme() {
            if (window.matchMedia) {
                const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

                const handleChange = (e) => {
                    this.systemTheme = e.matches ? this.THEMES.DARK : this.THEMES.LIGHT;

                    // 如果当前是自动模式，更新主题
                    const savedTheme = localStorage.getItem(this.THEME_KEY);
                    if (!savedTheme || savedTheme === this.THEMES.AUTO) {
                        this.applyTheme(true);
                    }
                };

                // 使用新的addEventListener方法（如果支持）
                if (mediaQuery.addEventListener) {
                    mediaQuery.addEventListener('change', handleChange);
                } else if (mediaQuery.addListener) {
                    // 兼容旧版浏览器
                    mediaQuery.addListener(handleChange);
                }
            }
        }

        /**
         * 从本地存储加载主题
         */
        loadTheme() {
            const savedTheme = localStorage.getItem(this.THEME_KEY);

            if (savedTheme && Object.values(this.THEMES).includes(savedTheme)) {
                this.currentTheme = savedTheme;
            } else {
                // 默认使用系统主题
                this.currentTheme = this.THEMES.AUTO;
            }
        }

        /**
         * 保存主题到本地存储
         */
        saveTheme(theme) {
            localStorage.setItem(this.THEME_KEY, theme);
            this.currentTheme = theme;
        }

        /**
         * 获取实际应用的主题
         */
        getEffectiveTheme() {
            if (this.currentTheme === this.THEMES.AUTO) {
                return this.systemTheme;
            }
            return this.currentTheme;
        }

        /**
         * 应用主题
         */
        applyTheme(animate = false) {
            const effectiveTheme = this.getEffectiveTheme();
            const root = document.documentElement;

            // 添加过渡类
            if (animate) {
                root.classList.add('theme-transitioning');
            }

            // 设置主题
            if (effectiveTheme === this.THEMES.DARK) {
                root.setAttribute('data-theme', 'dark');
                root.style.colorScheme = 'dark'; // 提示浏览器使用深色滚动条等
            } else {
                root.removeAttribute('data-theme');
                root.style.colorScheme = 'light';
            }

            // 更新切换按钮
            this.updateToggleButton();

            // 移除过渡类
            if (animate) {
                setTimeout(() => {
                    root.classList.remove('theme-transitioning');
                }, 400);
            }

            // 触发自定义事件
            window.dispatchEvent(new CustomEvent('themeChanged', {
                detail: {
                    theme: effectiveTheme,
                    isDark: effectiveTheme === this.THEMES.DARK
                }
            }));
        }

        /**
         * 切换主题（三态循环）
         */
        toggle() {
            // 三态循环：light -> dark -> auto -> light
            if (this.currentTheme === this.THEMES.LIGHT) {
                this.saveTheme(this.THEMES.DARK);
            } else if (this.currentTheme === this.THEMES.DARK) {
                this.saveTheme(this.THEMES.AUTO);
            } else {
                this.saveTheme(this.THEMES.LIGHT);
            }

            this.applyTheme(true);
        }

        /**
         * 设置特定主题
         */
        setTheme(theme) {
            if (!Object.values(this.THEMES).includes(theme)) {
                console.error('Invalid theme:', theme);
                return;
            }

            this.saveTheme(theme);
            this.applyTheme(true);
        }

        /**
         * 创建主题切换按钮
         */
        createToggleButton() {
            // 检查是否已存在按钮
            if (document.querySelector('.theme-toggle')) {
                return;
            }

            const button = document.createElement('button');
            button.className = 'theme-toggle';
            button.setAttribute('aria-label', '切换主题');
            button.setAttribute('title', '切换深色/浅色主题');
            button.type = 'button';

            // 添加图标（使用SVG图标代替emoji，更清晰）
            button.innerHTML = `
                <svg class="icon-sun" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="5"/>
                    <line x1="12" y1="1" x2="12" y2="3"/>
                    <line x1="12" y1="21" x2="12" y2="23"/>
                    <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
                    <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
                    <line x1="1" y1="12" x2="3" y2="12"/>
                    <line x1="21" y1="12" x2="23" y2="12"/>
                    <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
                    <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
                </svg>
                <svg class="icon-moon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
                </svg>
            `;

            // 绑定点击事件
            button.addEventListener('click', (e) => {
                e.preventDefault();
                this.toggle();

                // 添加点击动画
                button.classList.add('theme-toggle-clicked');
                setTimeout(() => {
                    button.classList.remove('theme-toggle-clicked');
                }, 400);
            });

            // 添加键盘支持
            button.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.toggle();
                }
            });

            // 添加到页面
            document.body.appendChild(button);
        }

        /**
         * 更新切换按钮状态
         */
        updateToggleButton() {
            const button = document.querySelector('.theme-toggle');
            if (!button) return;

            const effectiveTheme = this.getEffectiveTheme();
            let titleText = '';
            let ariaLabel = '';

            // 根据当前主题设置提示文本
            if (this.currentTheme === this.THEMES.LIGHT) {
                titleText = '当前：浅色主题\n点击切换到：深色主题';
                ariaLabel = '切换到深色主题';
            } else if (this.currentTheme === this.THEMES.DARK) {
                titleText = '当前：深色主题\n点击切换到：自动跟随系统';
                ariaLabel = '切换到自动跟随系统';
            } else {
                // AUTO 模式
                const systemModeText = this.systemTheme === this.THEMES.DARK ? '深色' : '浅色';
                titleText = `当前：自动跟随系统（${systemModeText}）\n点击切换到：浅色主题`;
                ariaLabel = '切换到浅色主题';
            }

            button.setAttribute('title', titleText);
            button.setAttribute('aria-label', ariaLabel);

            // 添加当前模式类名
            button.classList.remove('theme-light', 'theme-dark', 'theme-auto');
            if (this.currentTheme === this.THEMES.AUTO) {
                button.classList.add('theme-auto');
            } else if (this.currentTheme === this.THEMES.DARK) {
                button.classList.add('theme-dark');
            } else {
                button.classList.add('theme-light');
            }
        }

        /**
         * 获取当前主题
         */
        getCurrentTheme() {
            return this.currentTheme;
        }

        /**
         * 获取实际主题（考虑auto模式）
         */
        getActualTheme() {
            return this.getEffectiveTheme();
        }
    }

    // 创建全局实例
    const themeManager = new ThemeManager();

    // 暴露到全局
    window.themeManager = themeManager;

    // 提供便捷方法
    window.toggleTheme = () => themeManager.toggle();
    window.setTheme = (theme) => themeManager.setTheme(theme);
    window.getTheme = () => themeManager.getCurrentTheme();

    // 监听主题变化事件（供其他脚本使用）
    // 使用示例：
    // window.addEventListener('themeChanged', (e) => {
    //     console.log('Theme changed to:', e.detail.theme);
    //     console.log('Is dark:', e.detail.isDark);
    // });

})();
