// 背景缓存管理器
class BackgroundCacheManager {
    constructor() {
        this.cacheName = 'video-web-bg-cache-v1';
        this.cachedBackgrounds = [];
        this.isCaching = false;
        this.cacheStatus = 'idle'; // idle, caching, completed, error
        this.init();
    }

    async init() {
        // 检查Service Worker支持
        if ('serviceWorker' in navigator) {
            try {
                // 检查是否已经注册Service Worker
                const registrations = await navigator.serviceWorker.getRegistrations();
                let existingRegistration = null;
                
                // 查找已注册的Service Worker
                for (const reg of registrations) {
                    if (reg.active && reg.active.scriptURL.includes('sw.js')) {
                        existingRegistration = reg;
                        console.log('找到已注册的Service Worker:', reg.active.scriptURL);
                        break;
                    }
                }
                
                // 如果没有找到已注册的Service Worker，则注册新的
                if (!existingRegistration) {
                    // 注册Service Worker
                    const registration = await navigator.serviceWorker.register('/js/sw.js');
                    console.log('Service Worker 注册成功:', registration);
                }
            } catch (error) {
                console.error('Service Worker 注册失败:', error);
                // Service Worker注册失败，但仍然可以使用Cache API
                console.log('将使用Cache API进行缓存，Service Worker功能不可用');
            }
        } else {
            console.log('浏览器不支持Service Worker，将使用Cache API进行缓存');
        }

        // 检查缓存状态- 使用更稳妥的验证方法
        await this.verifyCacheStatus();
    }

    // 检查缓存状态
    async checkCacheStatus() {
        if ('caches' in window) {
            try {
                const cache = await caches.open(this.cacheName);
                const keys = await cache.keys();
                this.cachedBackgrounds = keys.map(request => 
                    request.url.split('/').pop()
                );
                console.log('已缓存的背景图片:', this.cachedBackgrounds);

                // 更新缓存状态
                if (this.cachedBackgrounds.length > 0) {
                    this.cacheStatus = 'completed';
                } else {
                    this.cacheStatus = 'idle';
                }

                // 更新UI显示
                this.updateCacheStatusUI();

                return this.cachedBackgrounds;
            } catch (error) {
                console.error('检查缓存状态失败:', error);
                return [];
            }
        }
        return [];
    }

    // 缓存所有背景图片
    async cacheAllBackgrounds() {
        if (this.isCaching) {
            console.log('正在缓存中，请勿重复操作');
            return;
        }

        if (!window.backgroundManager || !window.backgroundManager.backgrounds.length) {
            console.error('背景管理器未初始化或背景列表为空');
            this.cacheStatus = 'error';
            return;
        }

        this.isCaching = true;
        this.cacheStatus = 'caching';
        this.updateCacheStatusUI();

        // 清除旧缓存
        console.log('清除旧缓存...');
        try {
            if ('caches' in window) {
                await caches.delete(this.cacheName);
                this.cachedBackgrounds = [];
                console.log('旧缓存已清除');
            }
        } catch (error) {
            console.error('清除旧缓存失败:', error);
        }

        const backgrounds = window.backgroundManager.backgrounds;
        let successCount = 0;
        let failCount = 0;

        try {
            if ('caches' in window) {
                const cache = await caches.open(this.cacheName);

                // 逐个缓存背景图片
                for (const bg of backgrounds) {
                    try {
                        // 直接使用WebP格式
                        const bgFile = bg.webp || bg.file;
                        console.log('缓存WebP格式:', bgFile);

                        // 构建完整的背景URL
                        let bgUrl;
                        // 使用当前域名下的资源
                        bgUrl = `${window.location.origin}/resource/backgrounds/${bgFile}`;

                        const response = await fetch(bgUrl);

                        if (response.ok) {
                            await cache.put(bgUrl, response);
                            successCount++;
                            this.cachedBackgrounds.push(bgFile);
                            console.log(`成功缓存背景: ${bgFile}`);
                        } else {
                            failCount++;
                            console.error(`缓存背景失败: ${bgFile}, 状态 ${response.status}`);
                        }
                    } catch (error) {
                        failCount++;
                        console.error(`缓存背景出错: ${bg.file}`, error);
                    }

                    // 更新进度
                    const progress = Math.round((successCount + failCount) / backgrounds.length * 100);
                    this.updateCacheProgressUI(progress, successCount, failCount, backgrounds.length);
                }

                this.cacheStatus = 'completed';
                console.log(`背景缓存完成: 成功 ${successCount} 个 失败 ${failCount} 个`);
            } else {
                throw new Error('浏览器不支持缓存API');
            }
        } catch (error) {
            this.cacheStatus = 'error';
            console.error('缓存背景失败:', error);
        } finally {
            this.isCaching = false;
            this.updateCacheStatusUI();
        }
    }

    // 清除所有缓存
    async clearAllCache() {
        try {
            if ('caches' in window) {
                // 清除特定缓存
                await caches.delete(this.cacheName);
                
                // 尝试清除所有可能的缓存
                const cacheNames = await caches.keys();
                for (const name of cacheNames) {
                    if (name.includes('video-web-bg-cache')) {
                        // 先检查缓存内容，再删除图片文件
                        const cache = await caches.open(name);
                        const requests = await cache.keys();
                        
                        for (const request of requests) {
                            const url = new URL(request.url);
                            const pathname = url.pathname;
                            // 只删除图片文件（.png, .jpg, .jpeg, .gif, .webp）
                            if (pathname.match(/\.(png|jpg|jpeg|gif|webp)$/i)) {
                                await cache.delete(request);
                            }
                        }
                        
                        console.log(`已清除缓存${name}中的图片文件`);
                    }
                }
                
                // 重置内部状态
                this.cachedBackgrounds = [];
                this.cacheStatus = 'idle';
                console.log('背景缓存已清除');
                this.updateCacheStatusUI();
                return true;
            } else {
                throw new Error('浏览器不支持缓存API');
            }
        } catch (error) {
            console.error('清除缓存失败:', error);
            this.cacheStatus = 'error';
            this.updateCacheStatusUI();
            return false;
        }
    }
    
    // 验证缓存状态- 更稳妥的检查方法
    async verifyCacheStatus() {
        try {
            // 清空内部状态
            this.cachedBackgrounds = [];
            
            // 重新检查所有可能的缓存
            if ('caches' in window) {
                const cacheNames = await caches.keys();
                let totalCached = 0;
                
                for (const name of cacheNames) {
                    if (name.includes('video-web-bg-cache')) {
                        const cache = await caches.open(name);
                        const keys = await cache.keys();
                        const bgFiles = keys
                            .map(request => {
                                const url = new URL(request.url);
                                const pathname = url.pathname;
                                // 只统计图片文件（.png, .jpg, .jpeg, .gif, .webp）
                                if (pathname.match(/\.(png|jpg|jpeg|gif|webp)$/i)) {
                                    return pathname.split('/').pop();
                                }
                                return null;
                            })
                            .filter(file => file !== null); // 过滤掉非图片文件
                        
                        this.cachedBackgrounds = [...this.cachedBackgrounds, ...bgFiles];
                        totalCached += bgFiles.length;
                        console.log(`缓存 ${name} 中有 ${bgFiles.length} 张图片`);
                    }
                }
                
                // 去重
                this.cachedBackgrounds = [...new Set(this.cachedBackgrounds)];
                
                // 更新状态
                if (this.cachedBackgrounds.length > 0) {
                    this.cacheStatus = 'completed';
                } else {
                    this.cacheStatus = 'idle';
                }
                
                this.updateCacheStatusUI();
                console.log(`验证完成: 共缓存了 ${this.cachedBackgrounds.length} 张背景图片`);
                return this.cachedBackgrounds;
            }
            return [];
        } catch (error) {
            console.error('验证缓存状态失败:', error);
            this.cacheStatus = 'error';
            this.updateCacheStatusUI();
            return [];
        }
    }

    // 更新缓存状态UI
    updateCacheStatusUI() {
        const cacheStatusEl = document.getElementById('bgCacheStatus');
        if (!cacheStatusEl) return;

        let statusText = '';
        let statusClass = '';

        switch (this.cacheStatus) {
            case 'idle':
                statusText = '未缓存';
                statusClass = 'cache-status-idle';
                break;
            case 'caching':
                statusText = '缓存中...';
                statusClass = 'cache-status-caching';
                break;
            case 'completed':
                statusText = `已缓存(${this.cachedBackgrounds.length}张)`;
                statusClass = 'cache-status-completed';
                break;
            case 'error':
                statusText = '缓存错误';
                statusClass = 'cache-status-error';
                break;
        }

        cacheStatusEl.textContent = statusText;
        cacheStatusEl.className = `bg-cache-status ${statusClass}`;
    }

    // 更新缓存进度UI
    updateCacheProgressUI(progress, successCount, failCount, totalCount) {
        const progressEl = document.getElementById('bgCacheProgress');
        const progressTextEl = document.getElementById('bgCacheProgressText');

        if (progressEl) {
            progressEl.style.width = `${progress}%`;
        }

        if (progressTextEl) {
            progressTextEl.textContent = `${progress}% (${successCount}/${totalCount})`;
        }
    }

    // 检查特定背景是否已缓存
    async isBackgroundCached(bgFilename) {
        if (!bgFilename) return false;
        
        try {
            // 首先检查内部缓存列表
            if (this.cachedBackgrounds.includes(bgFilename)) {
                return true;
            }
            
            // 如果内部列表中没有，检查实际缓存
            if ('caches' in window) {
                const cache = await caches.open(this.cacheName);
                
                // 构建请求URL，使用当前域名
                const requestUrl = `${window.location.origin}/resource/backgrounds/${bgFilename}`;
                
                // 检查缓存中是否存在
                const response = await cache.match(requestUrl);
                if (response) {
                    // 如果存在，更新内部缓存列表
                    if (!this.cachedBackgrounds.includes(bgFilename)) {
                        this.cachedBackgrounds.push(bgFilename);
                    }
                    return true;
                }
            }
            
            return false;
        } catch (error) {
            console.error('检查背景缓存失败:', error);
            return false;
        }
    }

    // 检查浏览器是否支持WebP格式
    async checkWebPSupport() {
        // 检查是否已经缓存过检测结果
        if (typeof this.supportsWebP !== 'undefined') {
            return this.supportsWebP;
        }

        return new Promise((resolve) => {
            const webP = new Image();
            webP.onload = webP.onerror = function() {
                this.supportsWebP = (webP.height > 0 && webP.width > 0);
                resolve(this.supportsWebP);
            };
            webP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
        });
    }
}

// 全局背景缓存管理器实例
let backgroundCacheManager;

// 添加全局函数，方便在开发者工具中验证和清除缓存
// 这些函数将在 initManager.js 中初始化 backgroundCacheManager 后调用
window.verifyBackgroundCache = async function() {
    // 尝试从 window 属性获取 backgroundCacheManager
    const bgCacheManager = window.backgroundCacheManager || (typeof backgroundCacheManager !== 'undefined' ? backgroundCacheManager : null);
    
    if (bgCacheManager) {
        console.log('开始验证背景缓存...');
        const result = await bgCacheManager.verifyCacheStatus();
        console.log('验证结果:', result);
        return result;
    } else {
        console.error('背景缓存管理器未初始化，请等待页面加载完成后再试');
        console.log('提示：您可以在页面加载完成后，在控制台输入 window.backgroundCacheManager 检查属性是否存在');
        return null;
    }
};

window.clearBackgroundCache = async function() {
    // 尝试从 window 属性获取 backgroundCacheManager
    const bgCacheManager = window.backgroundCacheManager || (typeof backgroundCacheManager !== 'undefined' ? backgroundCacheManager : null);
    
    if (bgCacheManager) {
        console.log('开始清除背景缓存...');
        const result = await bgCacheManager.clearAllCache();
        console.log('清除结果:', result);
        return result;
    } else {
        console.error('背景缓存管理器未初始化，请等待页面加载完成后再试');
        console.log('提示：您可以在页面加载完成后，在控制台输入 window.backgroundCacheManager 检查属性是否存在');
        return false;
    }
};