// 背景设置模块
class BackgroundSettings {
    constructor() {
        this.isEnabled = false;
        this.interval = 30; // 默认30秒
        this.currentPage = 1;
        this.itemsPerPage = 6;
        this.backgrounds = [];
        this.intervalTimer = null;
        this.themeMode = localStorage.getItem('themeMode') || 'light'; // 主题模式：light, dark
        this.backgroundType = localStorage.getItem('backgroundType') || 'image'; // 背景类型：image, color
        this.selectedColor = localStorage.getItem('selectedColor') || '#f5f5f5'; // 选择的主题颜色
        this.isAnimating = false; // 动画播放标志位
    }

    // 初始化
    initialize() {
        // 从localStorage恢复设置
        this.isEnabled = localStorage.getItem('bgSwitchEnabled') === 'true';
        this.interval = parseInt(localStorage.getItem('bgInterval')) || 30;
        this.backgroundType = localStorage.getItem('backgroundType') || 'image';
        this.themeMode = localStorage.getItem('themeMode') || 'light';

        // 创建背景设置UI
        this.createUI();

        // 更新UI状态
        this.updateUI();

        // 应用背景类型
        this.applyBackgroundType();

        // 初始化缓存状态UI - 延迟执行，确保backgroundCacheManager已经初始化
        setTimeout(() => {
            if (window.backgroundCacheManager) {
                window.backgroundCacheManager.checkCacheStatus().then(() => {
                    window.backgroundCacheManager.updateCacheStatusUI();
                });
            }

            // 确保背景设置区域完全展开
            const backgroundContent = document.getElementById('background-content');
            if (backgroundContent) {
                backgroundContent.style.maxHeight = backgroundContent.scrollHeight + 'px';
                const icon = document.querySelector('[data-setting="background"] .toggle-icon');
                if (icon) icon.textContent = '−';
            }
        }, 500);

        // 加载背景列表
        this.loadBackgrounds().then(() => {
            // 背景加载完成后，如果自动切换已启用，则启动定时器
            if (this.isEnabled) {
                this.startAutoSwitch();
            }
        });

        console.log('背景设置模块初始化完成');
    }

    // 创建UI
    createUI() {
        const backgroundContent = document.getElementById('background-content');
        if (!backgroundContent) return;

        backgroundContent.innerHTML = `
            <div style="margin-bottom: 15px;">
                <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                    <span>背景类型</span>
                    <div style="display: flex; gap: 10px;">
                        <button class="mode-btn ${this.backgroundType === 'image' ? 'active' : ''}" 
                                onclick="window.backgroundSettings.setBackgroundType('image')"
                                style="min-width: 80px;">
                            图片
                        </button>
                        <button class="mode-btn ${this.backgroundType === 'color' ? 'active' : ''}" 
                                onclick="window.backgroundSettings.setBackgroundType('color')"
                                style="min-width: 80px;">
                            纯色
                        </button>
                    </div>
                </div>
            </div>

            <div id="colorSettings" style="display: ${this.backgroundType === 'color' ? 'block' : 'none'};">
                <div style="margin-bottom: 15px;">
                    <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                        <span>主题模式</span>
                        <div style="display: flex; gap: 10px;">
                            <button class="mode-btn ${this.themeMode === 'light' ? 'active' : ''}" 
                                    onclick="window.backgroundSettings.setThemeMode('light')"
                                    style="min-width: 80px;">
                                亮色
                            </button>
                            <button class="mode-btn ${this.themeMode === 'dark' ? 'active' : ''}" 
                                    onclick="window.backgroundSettings.setThemeMode('dark')"
                                    style="min-width: 80px;">
                                暗色
                            </button>
                        </div>
                    </div>
                </div>

                <div>
                    <label style="margin-bottom: 10px; display: block; font-size: 14px;">主题颜色</label>
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; padding: 16px; background: rgba(0, 0, 0, 0.2); border-radius: 12px;">
                        <div class="theme-color-item ${this.themeMode === 'light' && this.selectedColor === '#f5f5f5' ? 'active' : ''}" 
                             style="background: #f5f5f5; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#f5f5f5')"></div>
                        <div class="theme-color-item ${this.themeMode === 'light' && this.selectedColor === '#e3f2fd' ? 'active' : ''}" 
                             style="background: #e3f2fd; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#e3f2fd')"></div>
                        <div class="theme-color-item ${this.themeMode === 'light' && this.selectedColor === '#fff3e0' ? 'active' : ''}" 
                             style="background: #fff3e0; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#fff3e0')"></div>
                        <div class="theme-color-item ${this.themeMode === 'light' && this.selectedColor === '#e8f5e9' ? 'active' : ''}" 
                             style="background: #e8f5e9; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#e8f5e9')"></div>
                        <div class="theme-color-item ${this.themeMode === 'dark' && this.selectedColor === '#1a1a1a' ? 'active' : ''}" 
                             style="background: #1a1a1a; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#1a1a1a')"></div>
                        <div class="theme-color-item ${this.themeMode === 'dark' && this.selectedColor === '#2d2d2d' ? 'active' : ''}" 
                             style="background: #2d2d2d; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#2d2d2d')"></div>
                        <div class="theme-color-item ${this.themeMode === 'dark' && this.selectedColor === '#1e1e1e' ? 'active' : ''}" 
                             style="background: #1e1e1e; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#1e1e1e')"></div>
                        <div class="theme-color-item ${this.themeMode === 'dark' && this.selectedColor === '#0d0d0d' ? 'active' : ''}" 
                             style="background: #0d0d0d; width: 100%; padding-bottom: 100%; position: relative;" 
                             onclick="window.backgroundSettings.setThemeColor('#0d0d0d')"></div>
                    </div>
                </div>
            </div>

            <div id="imageSettings" style="display: ${this.backgroundType === 'image' ? 'block' : 'none'};">
                <div style="margin-bottom: 15px;">
                    <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                        <span>自动切换</span>
                    <button class="mode-btn" id="bgToggle" onclick="window.backgroundSettings.toggleAutoSwitch()" style="min-width: 100px;">
                        已关闭(∞s)
                    </button>
                </div>
                <div id="bgIntervalContainer" style="display: none; margin-top: 10px;">
                    <input type="number" id="bgInterval" min="1" value="${this.interval}"
                        onchange="window.backgroundSettings.updateInterval(this.value)"
                        class="settings-input">
                </div>

                <div>
                    <label style="margin-bottom: 10px; display: block; font-size: 14px;">背景选择</label>
                    <div class="bg-grid-container bg-grid-fixed" id="bgGrid"></div>
                    <div class="bg-pagination-container" id="bgPagination"></div>
                </div>

                <!-- 背景缓存功能 -->
                <div style="margin-top: 20px;">
                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
                        <span style="font-size: 14px;">背景缓存</span>
                        <span id="bgCacheStatus" class="bg-cache-status cache-status-idle">未缓存</span>
                    </div>

                    <div class="bg-cache-buttons">
                        <button id="cacheAllBtn" class="mode-btn" onclick="window.cacheAllBackgrounds()" style="min-width: 100px;">
                            缓存所有背景
                        </button>
                        <button id="clearCacheBtn" class="mode-btn" onclick="window.clearAllCache()" style="min-width: 100px;">
                            清除缓存
                        </button>
                    </div>

                    <div id="bgCacheProgressContainer" class="bg-cache-progress-container" style="display: none;">
                        <div id="bgCacheProgress" class="bg-cache-progress"></div>
                    </div>
                    <div id="bgCacheProgressText" class="bg-cache-progress-text" style="display: none;"></div>

                    <div class="bg-cache-info">
                        <p>缓存背景图片可加快加载速度，但将占用设备存储空间。</p>
                        <p class="tip">提示：缓存完成后，即使离线也能显示已缓存的背景。</p>
                    </div>
                </div>
            </div>
        `;
    }

    // 更新UI状态
    updateUI() {
        const toggle = document.getElementById('bgToggle');
        const intervalContainer = document.getElementById('bgIntervalContainer');
        const intervalInput = document.getElementById('bgInterval');

        if (!toggle || !intervalContainer || !intervalInput) return;

        if (this.isEnabled) {
            // 开启状态
            toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
            toggle.style.color = 'white';
            toggle.style.borderColor = 'transparent';
            toggle.textContent = `已开启(${this.interval}s)`;
            intervalContainer.style.display = 'block';
            intervalInput.value = this.interval;
        } else {
            // 关闭状态
            toggle.style.background = 'rgba(40, 40, 40, 0.8)';
            toggle.style.color = 'rgba(255, 255, 255, 0.7)';
            toggle.style.borderColor = 'rgba(255, 255, 255, 0.2)';
            toggle.textContent = '已关闭(∞s)';
            intervalContainer.style.display = 'none';
        }
    }

    // 切换自动开关
    toggleAutoSwitch() {
        this.isEnabled = !this.isEnabled;
        localStorage.setItem('bgSwitchEnabled', this.isEnabled.toString());

        if (this.isEnabled) {
            this.startAutoSwitch();
        } else {
            this.stopAutoSwitch();
        }

        this.updateUI();
    }

    // 更新间隔时间
    updateInterval(value) {
        this.interval = parseInt(value) || 30;
        localStorage.setItem('bgInterval', this.interval.toString());

        if (this.isEnabled) {
            this.stopAutoSwitch();
            this.startAutoSwitch();
        }

        this.updateUI();
    }

    // 开始自动切换
    startAutoSwitch() {
        // 确保背景管理器已加载背景列表
        if (!window.backgroundManager || !window.backgroundManager.backgrounds || window.backgroundManager.backgrounds.length === 0) {
            console.error('背景管理器未初始化或背景列表为空，无法开启自动切换');
            const toggle = document.getElementById('bgToggle');
            if (toggle) {
                toggle.textContent = '初始化失败';
                toggle.style.background = 'rgba(200, 50, 50, 0.8)';
            }
            this.isEnabled = false;
            localStorage.setItem('bgSwitchEnabled', 'false');
            return;
        }

        // 清除之前的定时器
        this.stopAutoSwitch();

        // 启动新的定时器
        this.intervalTimer = setInterval(() => {
            console.log('定时器触发，准备切换背景...');
            if (window.backgroundManager && window.backgroundManager.backgrounds && window.backgroundManager.backgrounds.length > 0) {
                console.log('backgroundManager 存在，背景列表长度', window.backgroundManager.backgrounds.length);
                window.backgroundManager.setRandomBackground();
            } else {
                console.error('backgroundManager 不存在或背景列表为空');
            }
        }, this.interval * 1000);

        console.log(`背景自动切换已开启，间隔: ${this.interval} 秒`);
    }

    // 停止自动切换
    stopAutoSwitch() {
        if (this.intervalTimer) {
            clearInterval(this.intervalTimer);
            this.intervalTimer = null;
        }
        console.log('背景自动切换已关闭');
    }

    // 加载背景列表
    async loadBackgrounds() {
        try {
            if (!window.backgroundManager) {
                console.error('背景管理器未初始化');
                return Promise.reject('背景管理器未初始化');
            }

            // 等待背景管理器加载背景列表
            if (!window.backgroundManager.backgrounds || window.backgroundManager.backgrounds.length === 0) {
                await new Promise(resolve => {
                    const checkInterval = setInterval(() => {
                        if (window.backgroundManager.backgrounds && window.backgroundManager.backgrounds.length > 0) {
                            clearInterval(checkInterval);
                            resolve();
                        }
                    }, 100);
                });
            }

            this.backgrounds = window.backgroundManager.backgrounds;
            this.renderBackgroundGrid();
            return Promise.resolve();
        } catch (error) {
            console.error('加载背景列表失败:', error);
            return Promise.reject(error);
        }
    }

    // 渲染背景网格
    renderBackgroundGrid() {
        const bgGrid = document.getElementById('bgGrid');
        const bgPagination = document.getElementById('bgPagination');

        if (!bgGrid || !bgPagination || this.backgrounds.length === 0) return;

        // 计算当前页的背景
        const startIndex = (this.currentPage - 1) * this.itemsPerPage;
        const endIndex = Math.min(startIndex + this.itemsPerPage, this.backgrounds.length);
        const currentPageBackgrounds = this.backgrounds.slice(startIndex, endIndex);

        // 清空网格
        bgGrid.innerHTML = '';

        // 添加背景项
        currentPageBackgrounds.forEach(bg => {
            const bgItem = document.createElement('div');
            bgItem.className = 'bg-item';
            
            // 创建内部容器
            const bgItemInner = document.createElement('div');
            bgItemInner.className = 'bg-item-inner';

            // 直接使用WebP格式
            const bgFile = bg.webp || bg.file;
            bgItemInner.style.backgroundImage = `url(${getApiUrl('/resource/backgrounds/' + bgFile)})`;
            bgItemInner.style.backgroundSize = 'contain';
            bgItemInner.style.backgroundPosition = 'center';
            bgItemInner.style.backgroundRepeat = 'no-repeat';
            
            // 添加图片名称标签
            const bgName = document.createElement('div');
            bgName.className = 'bg-name';
            bgName.textContent = bg.name || bg.file;
            bgItemInner.appendChild(bgName);
            
            bgItem.title = bg.name || bg.file;
            bgItem.onclick = async () => await this.selectBackground(bg.file);
            bgItem.appendChild(bgItemInner);
            bgGrid.appendChild(bgItem);
        });

        // 渲染分页
        this.renderPagination();
    }

    // 渲染分页
    renderPagination() {
        const bgPagination = document.getElementById('bgPagination');
        if (!bgPagination || this.backgrounds.length === 0) return;

        const totalPages = Math.ceil(this.backgrounds.length / this.itemsPerPage);
        if (totalPages <= 1) {
            bgPagination.innerHTML = '';
            return;
        }

        let paginationHTML = '';

        // 上一页按钮（总是显示）
        const prevDisabled = this.currentPage <= 1 ? 'disabled' : '';
        paginationHTML += `<button class="bg-page-btn" ${prevDisabled} onclick="window.backgroundSettings.goToPage(${this.currentPage - 1})">←</button>`;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (i === this.currentPage) {
                paginationHTML += `<span class="pagination-current">${i}</span>`;
            } else {
                paginationHTML += `<button class="bg-page-btn" onclick="window.backgroundSettings.goToPage(${i})">${i}</button>`;
            }
        }

        // 下一页按钮（总是显示）
        const nextDisabled = this.currentPage >= totalPages ? 'disabled' : '';
        paginationHTML += `<button class="bg-page-btn" ${nextDisabled} onclick="window.backgroundSettings.goToPage(${this.currentPage + 1})">→</button>`;

        bgPagination.innerHTML = paginationHTML;
    }

    // 跳转到指定页
    goToPage(page) {
        const totalPages = Math.ceil(this.backgrounds.length / this.itemsPerPage);
        if (page < 1 || page > totalPages) return;

        this.currentPage = page;
        this.renderBackgroundGrid();
    }

    // 选择背景，带动画效果
    async selectBackgroundWithAnimation(filename) {
        // 如果正在播放动画，则不执行
        if (this.isAnimating) {
            return;
        }

        // 设置动画标志位
        this.isAnimating = true;

        if (!window.backgroundManager) {
            console.error('背景管理器未初始化');
            this.isAnimating = false;
            return;
        }

        // 如果没有指定背景，使用随机背景
        if (!filename) {
            window.backgroundManager.setRandomBackground();
            this.isAnimating = false;
            return;
        }

        // 检查背景列表是否已经加载
        if (!this.backgrounds || this.backgrounds.length === 0) {
            console.log('背景列表为空，尝试加载背景列表...');
            try {
                await this.loadBackgrounds();
                console.log('背景列表加载完成，数量:', this.backgrounds.length);
            } catch (error) {
                console.error('加载背景列表失败:', error);
                // 使用随机背景作为回退
                window.backgroundManager.setRandomBackground();
                this.isAnimating = false;
                return;
            }
        }

        // 查找背景在列表中的位置
        const baseFilename = filename.replace(/\.(webp|png|jpg|jpeg)$/i, '');
        console.log('查找背景，基础文件名', baseFilename, '背景列表数量:', this.backgrounds.length);
        
        const bg = this.backgrounds.find(b => {
            const bgFile = b.webp || b.file || b;
            const bgBaseFilename = bgFile.replace(/\.(webp|png|jpg|jpeg)$/i, '');
            const match = bgBaseFilename === baseFilename;
            if (match) {
                console.log('找到匹配的背景', bgFile, '基础文件名', bgBaseFilename);
            }
            return match;
        });

        if (!bg) {
            console.error('未找到背景', filename, '，使用随机背景作为回退');
            console.log('当前背景列表:', this.backgrounds.map(b => ({
                file: b.file,
                webp: b.webp,
                name: b.name
            })));
            window.backgroundManager.setRandomBackground();
            this.isAnimating = false;
            return;
        }

        // 设置背景
        const bgFile = bg.file || bg;
        const actualBgFile = bg.webp || bgFile;
        const bgUrl = `${window.location.origin}/resource/backgrounds/${actualBgFile}`;

        // 创建颜色遮罩层元素
        let overlay = document.getElementById('color-transition-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'color-transition-overlay';
            overlay.style.position = 'fixed';
            overlay.style.top = '0';
            overlay.style.left = '0';
            overlay.style.width = '100%';
            overlay.style.height = '100vh';
            overlay.style.backgroundColor = this.selectedColor;
            overlay.style.zIndex = '-1';
            overlay.style.transition = 'height 0.8s cubic-bezier(0.4, 0, 0.2, 1)';
            document.body.appendChild(overlay);
        } else {
            overlay.style.height = '100vh';
            overlay.style.backgroundColor = this.selectedColor;
        }

        // 预加载背景图片
        const img = new Image();
        img.onload = () => {
            // 设置背景图片
            document.body.style.setProperty('--bg-image', `url(${bgUrl})`);
            document.body.style.backgroundColor = '';
            document.body.style.setProperty('--bg-color', '');

            // 设置文字颜色
            if (this.themeMode === 'light') {
                document.body.style.setProperty('--text-color', '#333');
            } else {
                document.body.style.setProperty('--text-color', '#fff');
            }

            // 更新标题样式
            const headerTitle = document.querySelector('header h1');
            if (headerTitle) {
                headerTitle.style.color = this.themeMode === 'light' ? '#333' : '#fff';
            }

            // 强制重绘
            overlay.offsetHeight;

            // 淡出动画效果：从下往上逐渐消失
            setTimeout(() => {
                overlay.style.height = '0';
            }, 10);

            // 移除遮罩层
            setTimeout(() => {
                if (overlay && overlay.parentNode) {
                    overlay.parentNode.removeChild(overlay);
                }
                // 重置动画标志位
                this.isAnimating = false;
            }, 800);
        };
        img.onerror = () => {
            console.error('背景图片加载失败:', bgUrl);
            if (overlay && overlay.parentNode) {
                overlay.parentNode.removeChild(overlay);
            }
            // 重置动画标志位
            this.isAnimating = false;
        };
        img.src = bgUrl;
    }

    // 选择背景
    async selectBackground(filename) {
        if (!window.backgroundManager) {
            console.error('背景管理器未初始化');
            return;
        }

        // 查找背景在列表中的位置
        // 移除所有可能的扩展名，只比较基础文件名
        const baseFilename = filename.replace(/\.(webp|png|jpg|jpeg)$/i, '');
        const bg = this.backgrounds.find(b => {
            const bgFile = b.webp || b.file || b;
            const bgBaseFilename = bgFile.replace(/\.(webp|png|jpg|jpeg)$/i, '');
            return bgBaseFilename === baseFilename;
        });

        if (!bg) {
            console.error('未找到背景', filename);
            return;
        }

        // 设置背景
        const bgFile = bg.file || bg;

        // 直接使用WebP格式
        const actualBgFile = bg.webp || bgFile;

        // 构建背景URL，使用当前域名
        const bgUrl = `${window.location.origin}/resource/backgrounds/${actualBgFile}`;

        // 检查是否已经缓存
        if (window.backgroundCacheManager) {
            const isCached = await window.backgroundCacheManager.isBackgroundCached(actualBgFile);
            if (isCached) {
                console.log('使用缓存的背景:', actualBgFile);
            } else {
                console.log('背景未缓存，从网络加载:', actualBgFile);
            }
        }

        const img = new Image();
        img.onload = () => {
            document.body.style.setProperty('--bg-image', `url(${img.src})`);
            document.body.classList.remove('bg-fade');
            void document.body.offsetWidth;
            document.body.classList.add('bg-fade');

            // 更新背景管理器当前背景
            window.backgroundManager.currentBackground = bg;

            // 保存到localStorage
            localStorage.setItem('currentBg', actualBgFile);
            console.log('背景设置成功:', actualBgFile);
        };

        img.onerror = () => {
            console.error('背景图片加载失败:', bgFile);
            if (window.backgroundManager) {
                window.backgroundManager.setRandomBackground();
            }
        };

        img.src = bgUrl;
    }

    // 设置背景类型
    setBackgroundType(type) {
        // 如果正在播放动画，则不执行
        if (this.isAnimating) {
            return;
        }

        this.backgroundType = type;
        localStorage.setItem('backgroundType', type);

        // 更新UI显示
        const imageSettings = document.getElementById('imageSettings');
        const colorSettings = document.getElementById('colorSettings');

        if (type === 'image') {
            if (imageSettings) imageSettings.style.display = 'block';
            if (colorSettings) colorSettings.style.display = 'none';

            // 恢复背景图片，带动画效果
            if (window.backgroundManager) {
                const savedBackground = localStorage.getItem('currentBg');
                
                // 确保背景管理器已加载背景列表
                if (!window.backgroundManager.backgrounds || window.backgroundManager.backgrounds.length === 0) {
                    console.log('背景管理器背景列表为空，尝试加载...');
                    // 延迟执行，确保背景管理器有时间初始化
                    setTimeout(async () => {
                        try {
                            await window.backgroundManager.loadBackgrounds();
                            console.log('背景管理器背景列表加载完成，数量:', window.backgroundManager.backgrounds.length);
                            
                            // 更新本地背景列表
                            this.backgrounds = window.backgroundManager.backgrounds;
                            
                            if (savedBackground) {
                                this.selectBackgroundWithAnimation(savedBackground);
                            } else {
                                this.selectBackgroundWithAnimation(null);
                            }
                        } catch (error) {
                            console.error('加载背景列表失败:', error);
                            this.selectBackgroundWithAnimation(null);
                        }
                    }, 100);
                } else {
                    // 背景列表已加载，直接恢复背景
                    if (savedBackground) {
                        this.selectBackgroundWithAnimation(savedBackground);
                    } else {
                        this.selectBackgroundWithAnimation(null);
                    }
                }
            }
        } else {
            if (imageSettings) imageSettings.style.display = 'none';
            if (colorSettings) colorSettings.style.display = 'block';

            // 应用主题颜色，带动画效果
            this.applyThemeColorWithAnimation();
        }

        // 更新背景类型按钮状态
        this.updateBackgroundTypeButtons();
    }

    // 设置主题模式
    setThemeMode(mode) {
        this.themeMode = mode;
        localStorage.setItem('themeMode', mode);

        // 更新按钮状态
        this.updateThemeModeButtons();

        // 应用主题颜色
        this.applyThemeColor();
    }

    // 设置主题颜色
    setThemeColor(color) {
        // 如果正在播放动画，则不执行
        if (this.isAnimating) {
            return;
        }

        this.selectedColor = color;
        localStorage.setItem('selectedColor', color);

        // 更新按钮状态
        this.updateThemeColorButtons();

        // 应用主题颜色，带动画效果
        this.applyThemeColorWithAnimation();
    }

    // 更新主题模式按钮状态
    updateThemeModeButtons() {
        const buttons = document.querySelectorAll('[onclick*="setThemeMode"]');
        buttons.forEach(btn => {
            if (btn.getAttribute('onclick').includes("'light'")) {
                btn.classList.toggle('active', this.themeMode === 'light');
            } else if (btn.getAttribute('onclick').includes("'dark'")) {
                btn.classList.toggle('active', this.themeMode === 'dark');
            }
        });
    }

    // 更新主题颜色按钮状态
    updateThemeColorButtons() {
        const buttons = document.querySelectorAll('[onclick*="setThemeColor"]');
        buttons.forEach(btn => {
            const color = btn.getAttribute('onclick').match(/'([^']+)'/)[1];
            btn.classList.toggle('active', this.selectedColor === color);
        });
    }

    // 应用主题颜色
    applyThemeColor() {
        // 设置背景颜色
        document.body.style.backgroundColor = this.selectedColor;
        document.body.style.setProperty('--bg-color', this.selectedColor);

        // 设置文字颜色
        if (this.themeMode === 'light') {
            document.body.style.setProperty('--text-color', '#333');
        } else {
            document.body.style.setProperty('--text-color', '#fff');
        }

        // 移除背景图片
        document.body.style.setProperty('--bg-image', 'none');

        // 更新标题样式
        const headerTitle = document.querySelector('header h1');
        if (headerTitle) {
            headerTitle.style.color = this.themeMode === 'light' ? '#333' : '#fff';
        }
    }

    // 应用主题颜色，带动画效果
    applyThemeColorWithAnimation() {
        // 如果正在播放动画，则不执行
        if (this.isAnimating) {
            return;
        }

        // 设置动画标志位
        this.isAnimating = true;

        // 创建遮罩层元素
        let overlay = document.getElementById('theme-transition-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'theme-transition-overlay';
            overlay.style.position = 'fixed';
            overlay.style.top = '0';
            overlay.style.left = '0';
            overlay.style.width = '100%';
            overlay.style.height = '0';
            overlay.style.backgroundColor = this.selectedColor;
            overlay.style.zIndex = '-1';
            overlay.style.transition = 'height 0.8s cubic-bezier(0.4, 0, 0.2, 1)';
            document.body.appendChild(overlay);
        } else {
            overlay.style.backgroundColor = this.selectedColor;
            overlay.style.height = '0';
        }

        // 强制重绘
        overlay.offsetHeight;

        // 开始动画
        setTimeout(() => {
            overlay.style.height = '100vh';
        }, 10);

        // 动画完成后应用主题颜色
        setTimeout(() => {
            // 设置背景颜色
            document.body.style.backgroundColor = this.selectedColor;
            document.body.style.setProperty('--bg-color', this.selectedColor);

            // 设置文字颜色
            if (this.themeMode === 'light') {
                document.body.style.setProperty('--text-color', '#333');
            } else {
                document.body.style.setProperty('--text-color', '#fff');
            }

            // 移除背景图片
            document.body.style.setProperty('--bg-image', 'none');

            // 更新标题样式
            const headerTitle = document.querySelector('header h1');
            if (headerTitle) {
                headerTitle.style.color = this.themeMode === 'light' ? '#333' : '#fff';
            }

            // 淡出动画效果：从下往上逐渐消失
            overlay.style.transition = 'height 0.8s cubic-bezier(0.4, 0, 0.2, 1)';
            overlay.style.height = '0';

            // 移除遮罩层
            setTimeout(() => {
                if (overlay && overlay.parentNode) {
                    overlay.parentNode.removeChild(overlay);
                }
                // 重置动画标志位
                this.isAnimating = false;
            }, 800);
        }, 800);
    }

    // 更新背景类型按钮状态
    updateBackgroundTypeButtons() {
        const buttons = document.querySelectorAll('[onclick*="setBackgroundType"]');
        buttons.forEach(btn => {
            if (btn.getAttribute('onclick').includes("'image'")) {
                btn.classList.toggle('active', this.backgroundType === 'image');
            } else if (btn.getAttribute('onclick').includes("'color'")) {
                btn.classList.toggle('active', this.backgroundType === 'color');
            }
        });
    }

    // 应用背景类型
    applyBackgroundType() {
        if (this.backgroundType === 'color') {
            // 应用颜色背景
            if (window.themeSettings) {
                window.themeSettings.applyThemeMode();
            }
        } else {
            // 应用图片背景
            if (window.backgroundManager && window.backgroundManager.currentBackground) {
                const bg = window.backgroundManager.currentBackground;
                const bgFile = bg.webp || bg.file;
                const bgUrl = `${window.location.origin}/resource/backgrounds/${bgFile}`;
                document.body.style.setProperty('--bg-image', `url(${bgUrl})`);
                document.body.style.backgroundColor = '';
            }
        }
    }
}
   