// 背景设置模块
class BackgroundSettings {
    constructor() {
        this.isEnabled = false;
        this.interval = 30; // 默认30秒
        this.currentPage = 1;
        this.itemsPerPage = 6;
        this.backgrounds = [];
        this.intervalTimer = null;
    }

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

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

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

        // 初始化缓存状态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>
                    <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>

            <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>
        `;
    }

    // 更新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';
            bgItemInner.style.backgroundImage = `url(${getApiUrl('/background/' + bg.file)})`;
            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 selectBackground(filename) {
        if (!window.backgroundManager) {
            console.error('背景管理器未初始化');
            return;
        }

        // 查找背景在列表中的位置
        const bg = this.backgrounds.find(b => (b.file || b) === filename);
        if (!bg) {
            console.error('未找到背景:', filename);
            return;
        }

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

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

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

        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', bgFile);
            console.log('背景设置成功:', bgFile);
        };

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

        img.src = bgUrl;
    }
}
