// 主题切换功能
(function() {
    // 获取存储的主题或系统偏好
    const getStoredTheme = () => localStorage.getItem('theme');
    const getSystemTheme = () => window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    
    // 设置主题
    const setTheme = (theme) => {
        if (theme === 'dark') {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
        } else {
            document.documentElement.removeAttribute('data-theme');
            localStorage.setItem('theme', 'light');
        }
    };
    
    // 初始化主题
    const initTheme = () => {
        const stored = getStoredTheme();
        if (stored) {
            setTheme(stored);
        } else {
            setTheme(getSystemTheme());
        }
    };
    
    // 创建主题切换按钮
    const createThemeToggle = () => {
        const button = document.createElement('button');
        button.className = 'btn btn-outline btn-sm';
        button.id = 'themeToggle';
        button.innerHTML = getStoredTheme() === 'dark' ? '☀️' : '🌙';
        
        button.addEventListener('click', () => {
            const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
            setTheme(isDark ? 'light' : 'dark');
            button.innerHTML = isDark ? '🌙' : '☀️';
        });
        
        return button;
    };
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            setTheme(e.matches ? 'dark' : 'light');
        }
    });
    
    initTheme();
    
    // 等待DOM加载完成后添加按钮
    document.addEventListener('DOMContentLoaded', () => {
        const userMenu = document.querySelector('.user-menu');
        if (userMenu) {
            const toggleBtn = createThemeToggle();
            userMenu.appendChild(toggleBtn);
        }
    });
})();