// 设置面板模块
// 全局变量
let settingsToggling = false; // 防止重复触发

// debounce函数已在helpers.js中定义

// 背景缓存功能已移除

// 切换设置面板
window.toggleSettings = function() {
    if (settingsToggling) return; // 如果正在切换，直接返回
    settingsToggling = true;
    
    // 如果有正在进行的动画，先取消它
    if (window.settingsAnimationTimeout) {
        clearTimeout(window.settingsAnimationTimeout);
        window.settingsAnimationTimeout = null;
    }

    const sidebar = document.querySelector('.settings-sidebar');
    const settingsButton = document.querySelector('.settings-button');
    const body = document.body;

    if (!sidebar || !settingsButton || !body) {
        console.error('找不到设置面板元素');
        settingsToggling = false;
        return;
    }

    sidebar.classList.toggle('active');
    settingsButton.classList.toggle('active');

    // 切换body的动画状态类
    body.classList.toggle('settings-open');

    // 添加动画控制类，确保动画只在用户主动触发时播放
    if (body.classList.contains('settings-open')) {
        // 设置面板打开时，添加动画类
        body.classList.add('settings-animated');
    } else {
        // 设置面板关闭时，先播放返回动画，然后移除动画类
        setTimeout(() => {
            body.classList.remove('settings-animated');
        }, 700); // 等待返回动画完成
    }

    console.log('设置面板状态:', sidebar.classList.contains('active') ? '已打开' : '已关闭');

    // 创建或移除遮罩层
    if (sidebar.classList.contains('active')) {
        createSettingsOverlay();
    } else {
        removeSettingsOverlay();
    }

    // 动画完成后重新允许切换
    window.settingsAnimationTimeout = setTimeout(() => {
        settingsToggling = false;
        window.settingsAnimationTimeout = null;
    }, 1000); // 调整为1秒，确保新的长动画完成
};

// 创建设置面板遮罩层
function createSettingsOverlay() {
    // 检查是否已存在遮罩层
    let overlay = document.getElementById('settings-overlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.id = 'settings-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.3);
            z-index: 998;
            opacity: 0;
            transition: opacity 0.4s ease;
            backdrop-filter: blur(2px);
            -webkit-backdrop-filter: blur(2px);
        `;
        document.body.appendChild(overlay);

        // 添加点击事件，点击遮罩层关闭面板
        overlay.addEventListener('click', () => {
            const sidebar = document.querySelector('.settings-sidebar');
            const settingsButton = document.querySelector('.settings-button');

            if (sidebar && settingsButton) {
                // 添加动画效果
                document.body.classList.add('settings-animated');
                
                // 移除活动类
                sidebar.classList.remove('active');
                settingsButton.classList.remove('active');
                document.body.classList.remove('settings-open');
                
                // 延迟移除动画类和遮罩层，确保动画播放完成
                window.settingsAnimationTimeout = setTimeout(() => {
                    document.body.classList.remove('settings-animated');
                    removeSettingsOverlay();
                    window.settingsAnimationTimeout = null;
                }, 700); // 与CSS过渡时间保持一致
            }
        });
    }
}

// 移除设置面板遮罩层
function removeSettingsOverlay() {
    const overlay = document.getElementById('settings-overlay');
    if (overlay) {
        // 添加淡出动画
        overlay.style.opacity = '0';

        // 动画完成后移除元素
        setTimeout(() => {
            if (overlay.parentNode) {
                overlay.parentNode.removeChild(overlay);
            }
        }, 400); // 等待淡出动画完成
    }
}

// 背景缓存功能函数
// 缓存所有背景图片
window.cacheAllBackgrounds = async function() {
    if (!window.backgroundCacheManager) {
        console.error('背景缓存管理器未初始化');
        return;
    }

    // 显示进度条
    const progressContainer = document.getElementById('bgCacheProgressContainer');
    const progressText = document.getElementById('bgCacheProgressText');
    if (progressContainer) progressContainer.style.display = 'block';
    if (progressText) progressText.style.display = 'block';

    // 禁用缓存按钮
    const cacheBtn = document.getElementById('cacheAllBtn');
    if (cacheBtn) cacheBtn.disabled = true;

    // 开始缓存
    await window.backgroundCacheManager.cacheAllBackgrounds();

    // 缓存完成后隐藏进度条
    setTimeout(() => {
        if (progressContainer) progressContainer.style.display = 'none';
        if (progressText) progressText.style.display = 'none';

        // 重新启用缓存按钮
        if (cacheBtn) cacheBtn.disabled = false;
    }, 1000);
};

// 清除所有缓存
window.clearAllCache = async function() {
    if (!window.backgroundCacheManager) {
        console.error('背景缓存管理器未初始化');
        return;
    }

    // 确认对话框
    if (confirm('确定要清除所有背景缓存吗？')) {
        const success = await window.backgroundCacheManager.clearAllCache();

        if (success) {
            // 显示成功提示
            const cacheStatusEl = document.getElementById('bgCacheStatus');
            if (cacheStatusEl) {
                cacheStatusEl.textContent = '已清除';
                cacheStatusEl.className = 'bg-cache-status cache-status-idle';

                // 2秒后恢复默认状态
                setTimeout(() => {
                    window.backgroundCacheManager.updateCacheStatusUI();
                }, 2000);
            }
        }
    }
};

// 初始化设置面板
window.initializeSettingsPanel = function() {
    console.log('初始化设置面板...');

    // 添加设置按钮和侧边栏
    const settingsHTML = `
        <div class="settings-button" onclick="toggleSettings()">⚙️</div>
        <div class="settings-sidebar">
            <div class="settings-header">
                <h2>设置</h2>
            </div>

            <!-- 🖼️ 背景设置区域 -->
            <div class="setting-item" data-setting="background">
                <div class="setting-header" onclick="toggleSettingSection('background')">
                    <h3>🖼️ 背景设置 <span class="toggle-icon">▼</span></h3>
                </div>
                <div class="setting-content" id="background-content">


                    <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="toggleBgSwitch()" style="min-width: 100px;">
                                已关闭 (∞s)
                            </button>
                        </div>
                        <div id="bgIntervalContainer" style="display: none; margin-top: 10px;">
                            <input type="number" id="bgInterval" min="1" value="30"
                                onchange="updateInterval(this.value)"
                                style="width: 100%;
                                        padding: 12px 20px;
                                        background: rgba(66, 66, 66, 0.15);
                                        backdrop-filter: blur(40px);
                                        -webkit-backdrop-filter: blur(40px);
                                        border: 2px solid rgba(255, 255, 255, 0.3);
                                        color: rgba(210, 210, 210, 0.9);
                                        border-radius: 20px;
                                        font-size: 14px;
                                        transition: all 0.3s ease;
                                        outline: none;">
                        </div>
                    </div>

                    <div>
                        <label style="margin-bottom: 10px; display: block; font-size: 14px;">背景选择</label>
                        <div class="bg-grid-container" id="bgGrid" style="display: grid !important; grid-template-columns: repeat(3, 1fr) !important; grid-template-rows: repeat(2, 1fr) !important; gap: 8px !important; height: 240px !important; overflow: hidden !important;"></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="bg-cache-btn" onclick="cacheAllBackgrounds()">
                                <span>缓存所有背景</span>
                            </button>
                            <button id="clearCacheBtn" class="bg-cache-btn clear-btn" onclick="clearAllCache()">
                                <span>清除缓存</span>
                            </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>
            </div>

            <!-- ✨ 点击效果设置区域 -->
            <div class="setting-item" data-setting="sound">
                <div class="setting-header" onclick="toggleSettingSection('sound')">
                    <h3>✨ 点击效果 <span class="toggle-icon">▼</span></h3>
                </div>
                <div class="setting-content" id="sound-content">
                    <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="soundToggle" onclick="toggleSoundEffects()" style="min-width: 100px;">
                                已开启
                            </button>
                        </div>
                        <div id="soundStatus" style="font-size: 12px; color: rgba(255,255,255,0.6); display: none;">
                            检查音效状态中...
                        </div>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                            <span>Ciallo 特效</span>
                            <button class="mode-btn" id="cialloToggle" onclick="toggleCialloEffect()" style="min-width: 100px;">
                                已开启
                            </button>
                        </div>
                        <div id="cialloStatus" style="font-size: 12px; color: rgba(255,255,255,0.6);">
                            点击时显示 Ciallo～(∠・ω< )⌒★
                        </div>

                    </div>

                    <div style="margin-bottom: 15px;">
                        <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                            <span>音效音量</span>
                            <span id="volumeValue" style="color: rgba(255,255,255,0.8);">80%</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span style="font-size: 12px; color: rgba(255,255,255,0.6);">🔈</span>
                            <input type="range" id="soundVolumeSlider" min="0" max="100" value="80"
                                   style="flex: 1; -webkit-appearance: none; height: 4px; border-radius: 2px; background: rgba(255,255,255,0.2); outline: none;"
                                   oninput="updateSoundVolume(this.value)"
                                   onchange="testSoundVolume()">
                            <span style="font-size: 12px; color: rgba(255,255,255,0.6);">🔊</span>
                        </div>
                    </div>


                </div>
            </div>



            <!-- 📹 视频播放设置 -->
            <div class="setting-item" data-setting="video">
                <div class="setting-header" onclick="toggleSettingSection('video')">
                    <h3>📹 视频播放设置 <span class="toggle-icon">▼</span></h3>
                </div>
                <div class="setting-content" id="video-content">
                    <div style="margin-bottom: 15px;">
                        <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
                            <span style="color: white;">视频清晰度优先级</span>
                            <button class="mode-btn" id="qualityPriorityToggle" onclick="toggleQualityPriority()" style="min-width: 100px;">
                                高清优先
                            </button>
                        </div>
                        <div style="font-size: 12px; color: rgba(255, 255, 255, 0.6);">
                            <div>高清优先: 4K/1080p → 720p</div>
                            <div>流畅优先: 720p → 4K/1080p</div>
                        </div>
                    </div>


                </div>
            </div>

            <!-- ⚙️ 其他设置 -->
            <div class="setting-item" data-setting="other">
                <div class="setting-header" onclick="toggleSettingSection('other')">
                    <h3>⚙️ 其他设置 <span class="toggle-icon">▼</span></h3>
                </div>
                <div class="setting-content" id="other-content">
                </div>
            </div>
        </div>
    `;

    document.body.insertAdjacentHTML('beforeend', settingsHTML);

    // 初始化设置面板状态
    setTimeout(() => {
        updateSoundToggleUI();
        updateSoundVolumeUI(); // 添加音效音量UI更新
        updateCialloToggleUI();
        updateQualityPriorityUI();

        updateBgSwitchUI(); // 添加背景切换UI更新

        // 初始化背景选择器
        loadBackgroundsWithPagination();

        // 初始化缓存状态UI
        if (window.backgroundCacheManager) {
            window.backgroundCacheManager.updateCacheStatusUI();
        }
        
        // 添加窗口大小变化监听器，确保设置面板状态一致
        window.addEventListener('resize', debounce(() => {
            const sidebar = document.querySelector('.settings-sidebar');
            if (sidebar && sidebar.classList.contains('active')) {
                // 确保设置面板在窗口大小变化时保持正确的位置
                // 不直接设置样式，让CSS类来控制
            }
        }, 100));

        console.log('设置面板初始化完成');
    }, 500);
}

// 切换设置区域展开/折叠
function toggleSettingSection(sectionId) {
    const content = document.getElementById(`${sectionId}-content`);
    const header = document.querySelector(`[data-setting="${sectionId}"] .setting-header`);
    const icon = header.querySelector('.toggle-icon');

    // 如果正在动画中，则不执行任何操作
    if (content && content.isAnimating) {
        return;
    }

    if (content) {
        // 标记为动画中
        content.isAnimating = true;
        
        // 获取当前状态
        const isExpanded = !content.classList.contains('hidden');
        
        // 使用更平滑的缓动函数
        const smoothCubicBezier = 'cubic-bezier(0.25, 0.46, 0.45, 0.94)';
        
        if (isExpanded) {
            // 收起动画
            // 设置过渡效果
            content.style.transition = `max-height 0.4s ${smoothCubicBezier}, opacity 0.3s ease-out`;
            content.style.maxHeight = content.scrollHeight + 'px';
            content.style.opacity = '1';
            content.style.overflow = 'hidden';
            
            // 下一帧触发动画
            requestAnimationFrame(() => {
                content.style.maxHeight = '0';
                content.style.opacity = '0';
            });
            
            // 更新图标
            if (icon) {
                icon.style.transition = `transform 0.4s ${smoothCubicBezier}`;
                icon.style.transform = 'rotate(-90deg)';
                icon.textContent = '▶';
            }
            
            // 动画完成后添加hidden类并重置动画状态
            setTimeout(() => {
                content.classList.add('hidden');
                content.style.maxHeight = '';
                content.style.opacity = '';
                content.style.overflow = '';
                content.style.transition = '';
                content.isAnimating = false; // 重置动画状态
            }, 400);
        } else {
            // 展开动画
            // 先移除hidden类，但设置初始状态
            content.classList.remove('hidden');
            content.style.maxHeight = '0';
            content.style.opacity = '0';
            content.style.overflow = 'hidden';
            
            // 下一帧触发动画
            requestAnimationFrame(() => {
                content.style.transition = `max-height 0.4s ${smoothCubicBezier}, opacity 0.3s ease-in`;
                content.style.maxHeight = content.scrollHeight + 'px';
                content.style.opacity = '1';
            });
            
            // 更新图标
            if (icon) {
                icon.style.transition = `transform 0.4s ${smoothCubicBezier}`;
                icon.style.transform = 'rotate(0deg)';
                icon.textContent = '▼';
            }
            
            // 动画完成后清除内联样式并重置动画状态
            setTimeout(() => {
                content.style.maxHeight = '';
                content.style.opacity = '';
                content.style.overflow = '';
                content.style.transition = '';
                content.isAnimating = false; // 重置动画状态
            }, 400);
        }
    }
}

// 更新视频缓存开关UI
// 视频缓存功能已移除
function updateVideoCacheToggleUI() {
    const toggle = document.getElementById('videoCacheToggle');
    if (!toggle) return;

    // 检查视频缓存是否启用
    const videoCacheEnabled = window.videoCache && window.videoCache.cacheEnabled;
    
    if (videoCacheEnabled) {
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';
        toggle.textContent = '已开启';
    } 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 = '已关闭';
    }
}

// 背景缓存功能已移除
    


// 背景缓存UI更新函数已移除
    


// 音频缓存功能已移除

// 切换视频清晰度优先级
window.toggleQualityPriority = function() {
    window.qualityPriorityHigh = !window.qualityPriorityHigh;
    localStorage.setItem('qualityPriorityHigh', window.qualityPriorityHigh.toString());
    console.log('视频清晰度优先级已切换为:', window.qualityPriorityHigh ? '高清优先' : '流畅优先');

    // 更新UI
    updateQualityPriorityUI();
}

// 更新视频清晰度优先级UI
function updateQualityPriorityUI() {
    const toggle = document.getElementById('qualityPriorityToggle');

    if (!toggle) return;

    if (window.qualityPriorityHigh) {
        // 高清优先状态
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';
        toggle.textContent = '高清优先';
    } 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 = '流畅优先';
    }
}



// 更新音效音量UI
function updateSoundVolumeUI() {
    const volumeSlider = document.getElementById('soundVolumeSlider');
    const volumeValue = document.getElementById('volumeValue');
    
    if (!volumeSlider || !volumeValue || !window.soundEffectManager) return;
    
    // 获取保存的音量值
    const volume = window.soundEffectManager.getVolume();
    const volumePercent = Math.round(volume * 100);
    
    // 更新滑块和显示值
    volumeSlider.value = volumePercent;
    volumeValue.textContent = `${volumePercent}%`;
}

// 更新背景切换UI
function updateBgSwitchUI() {
    const toggle = document.getElementById('bgToggle');
    const bgIntervalContainer = document.getElementById('bgIntervalContainer');
    const bgInterval = document.getElementById('bgInterval');
    
    if (!toggle || !bgIntervalContainer) return;
    
    // 获取保存的背景切换状态和间隔
    const bgSwitchEnabled = localStorage.getItem('bgSwitchEnabled') === 'true';
    const interval = parseInt(localStorage.getItem('bgInterval')) || 30;
    
    // 更新输入框的值
    if (bgInterval) {
        bgInterval.value = interval;
    }
    
    // 更新按钮状态和显示
    if (bgSwitchEnabled) {
        // 开启状态
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';
        toggle.textContent = `已开启 (${interval}s)`;
        bgIntervalContainer.style.display = 'block';
    } 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)';
        bgIntervalContainer.style.display = 'none';
    }
}

// 更新背景切换间隔
function updateInterval(value) {
    const interval = parseInt(value);
    if (isNaN(interval) || interval < 1) {
        console.warn('无效的间隔值:', value);
        return;
    }

    localStorage.setItem('bgInterval', interval.toString());

    const toggle = document.getElementById('bgToggle');
    const bgIntervalContainer = document.getElementById('bgIntervalContainer');

    if (toggle && bgIntervalContainer) {
        if (window.bgSwitchEnabled) {
            toggle.textContent = `已开启 (${interval}s)`;

            // 重启自动切换定时器
            if (window.bgInterval) {
                clearInterval(window.bgInterval);
            }

            window.bgInterval = setInterval(setRandomBackground, interval * 1000);
            console.log(`背景自动切换间隔已更新为 ${interval} 秒`);
        } else {
            toggle.textContent = '已关闭 (∞s)';
            bgIntervalContainer.style.display = 'none';

            // 停止自动切换定时器
            if (window.bgInterval) {
                clearInterval(window.bgInterval);
                window.bgInterval = null;
            }
        }
    }
}

// 加载背景选择器
function loadBackgrounds() {
    const bgGrid = document.getElementById('bgGrid');
    if (!bgGrid) return;

    // 确保网格布局正确应用
    bgGrid.style.display = 'grid';
    bgGrid.style.gridTemplateColumns = 'repeat(2, 1fr)';
    bgGrid.style.gridTemplateRows = 'repeat(3, 1fr)';
    bgGrid.style.gap = '8px';
    bgGrid.style.height = '240px';
    bgGrid.style.overflowY = 'auto';

    // 显示加载状态
    bgGrid.innerHTML = '<div class="loading">正在加载背景列表...</div>';

    // 获取背景列表
    fetch(getApiUrl('/videolist/bg.json'), {
        cache: 'no-cache'
    })
    .then(response => response.json())
    .then(data => {
        if (!data.backgrounds || !Array.isArray(data.backgrounds)) {
            throw new Error('无效的背景数据格式');
        }

        // 渲染背景选择器
        bgGrid.innerHTML = data.backgrounds.map(bg => {
            const isActive = bg.file === localStorage.getItem('currentBg');
            return `
                <div class="bg-item ${isActive ? 'active' : ''}" 
                     onclick="(async () => { await selectBackground('${bg.file}'); })()"
                     data-bg="${bg.file}">
                    <img src="${getApiUrl('/background/' + bg.file)}" alt="${bg.file}">
                    <div class="bg-name">${bg.file}</div>
                </div>
            `;
        }).join('');
        
        // 确保网格布局保持不变
        if (bgGrid) {
            bgGrid.style.display = 'grid';
            bgGrid.style.gridTemplateColumns = 'repeat(2, 1fr)';
            bgGrid.style.gridTemplateRows = 'repeat(3, 1fr)';
            bgGrid.style.gap = '8px';
            bgGrid.style.height = '240px';
            bgGrid.style.overflowY = 'auto';
        }
    })
    .catch(error => {
        console.error('加载背景列表失败:', error);
        bgGrid.innerHTML = '<div class="error">加载失败，请刷新重试</div>';
    });
}

// 带分页的加载背景选择器
function loadBackgroundsWithPagination() {
    const bgGrid = document.getElementById('bgGrid');
    if (!bgGrid) return;

    // 确保网格布局正确应用
    bgGrid.style.display = 'grid';
    bgGrid.style.gridTemplateColumns = 'repeat(3, 1fr)';
    bgGrid.style.gridTemplateRows = 'repeat(2, 1fr)';
    bgGrid.style.gap = '8px';
    bgGrid.style.height = '240px';
    bgGrid.style.overflow = 'hidden';

    // 显示加载状态
    bgGrid.innerHTML = '<div class="loading">正在加载背景列表...</div>';

    // 获取背景列表
    fetch(getApiUrl('/videolist/bg.json'), {
        cache: 'no-cache'
    })
    .then(response => response.json())
    .then(data => {
        if (!data.backgrounds || !Array.isArray(data.backgrounds)) {
            throw new Error('无效的背景数据格式');
        }

        // 存储背景数据到全局变量
        window.backgroundsData = data.backgrounds;
        console.log('背景数据加载成功:', data.backgrounds.length, '张背景');
        
        // 重置页码到第一页
        window.currentPage = 1;
        
        // 调用分页函数渲染背景
        if (typeof renderBackgrounds === 'function') {
            renderBackgrounds();
            console.log('背景渲染完成');
        } else {
            console.error('renderBackgrounds函数不存在');
        }
        
        // 调用分页函数渲染分页控件
        if (typeof renderPagination === 'function') {
            renderPagination();
            console.log('分页控件渲染完成');
        } else {
            console.error('renderPagination函数不存在');
        }
    })
    .catch(error => {
        console.error('加载背景列表失败:', error);
        bgGrid.innerHTML = '<div class="error">加载失败，请刷新重试</div>';
    });
}

// 选择背景
async function selectBackground(filename) {
    if (!filename) return;

    // 保存选择的背景
    localStorage.setItem('currentBg', filename);

    // 更新UI - 只更新当前选中项的激活状态，不重新加载
    const bgItems = document.querySelectorAll('.bg-item');
    bgItems.forEach(item => {
        if (item.dataset.bg === filename) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });

    // 应用选择的背景
    await setRandomBackgroundWithFile(filename);
}

// 设置指定背景文件
async function setRandomBackgroundWithFile(filename) {
    if (!filename) {
        if (window.backgroundManager) {
            window.backgroundManager.setRandomBackground();
        }
        return;
    }

    // 背景缓存功能已移除，不再需要初始化缓存管理器
    
    // 直接获取背景URL
    const timestamp = Date.now();
    let bgUrl;
    // 使用当前域名下的资源
    bgUrl = `${window.location.origin}/background/${filename}?t=${timestamp}`;
    console.log('使用背景URL:', filename);

    const bg = new Image();
    bg.src = bgUrl;

    bg.onload = async () => {
        document.body.style.setProperty('--bg-image', `url(${bg.src})`);
        document.body.classList.remove('bg-fade');
        void document.body.offsetWidth; // 强制重绘
        document.body.classList.add('bg-fade');

        // 应用亮背景样式（背景是亮的，文字是暗的）
        document.body.classList.add('light-bg');
        document.body.classList.remove('dark-bg');

        // 确保标题是深色的（但不要太黑）并添加发光效果
        const headerTitle = document.querySelector('header h1');
        if (headerTitle) {
            headerTitle.classList.add('light-bg-glow');
            headerTitle.classList.remove('dark-bg');
        }

        // 保存选择的背景
        localStorage.setItem('currentBg', filename);
        console.log('背景设置成功:', filename);
    };

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

// 背景缓存功能已移除



// 缓存状态显示功能已移除

// 切换背景自动切换
window.toggleBgSwitch = function() {
    const toggle = document.getElementById('bgToggle');
    const bgIntervalContainer = document.getElementById('bgIntervalContainer');

    if (!toggle || !bgIntervalContainer) return;

    window.bgSwitchEnabled = !window.bgSwitchEnabled;
    localStorage.setItem('bgSwitchEnabled', window.bgSwitchEnabled.toString());

    if (window.bgSwitchEnabled) {
        // 开启状态
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';

        const interval = parseInt(localStorage.getItem('bgInterval')) || 30;
        toggle.textContent = `已开启 (${interval}s)`;
        bgIntervalContainer.style.display = 'block';

        // 启动自动切换定时器
        if (window.bgInterval) {
            clearInterval(window.bgInterval);
        }

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

        window.bgInterval = 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 不存在或背景列表为空！');
            }
        }, interval * 1000);
        console.log(`背景自动切换已开启，间隔: ${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)';
        bgIntervalContainer.style.display = 'none';

        // 停止自动切换定时器
        if (window.bgInterval) {
            clearInterval(window.bgInterval);
            window.bgInterval = null;
        }

        console.log('背景自动切换已关闭');
    }
}
