// Service Worker for background caching
const CACHE_NAME = 'video-web-bg-cache-v1';
const BACKGROUND_CACHE_PREFIX = '/background/';

// 安装Service Worker
self.addEventListener('install', event => {
    console.log('Service Worker 安装成功');
    self.skipWaiting();
});

// 激活Service Worker
self.addEventListener('activate', event => {
    console.log('Service Worker 激活成功');
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.map(cacheName => {
                    // 删除旧版本的缓存
                    if (cacheName !== CACHE_NAME) {
                        console.log('删除旧缓存:', cacheName);
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
    return self.clients.claim();
});

// 处理资源请求
self.addEventListener('fetch', event => {
    const request = event.request;
    const url = new URL(request.url);

    // 只处理背景图片请求
    if (url.pathname.startsWith(BACKGROUND_CACHE_PREFIX)) {
        // 添加请求ID到日志中，方便跟踪
        const requestId = Math.random().toString(36).substring(2, 9);
        console.log(`[${requestId}] Service Worker 处理背景请求:`, url.pathname);
        
        event.respondWith(
            caches.open(CACHE_NAME).then(cache => {
                // 先检查缓存
                return cache.match(request).then(response => {
                    if (response) {
                        console.log(`[${requestId}] 从缓存返回背景:`, url.pathname);
                        return response;
                    }

                    // 缓存中没有，从网络获取
                    console.log(`[${requestId}] 从网络获取背景:`, url.pathname);
                    return fetch(request).then(response => {
                        // 检查响应是否有效
                        if (!response || response.status !== 200 || response.type !== 'basic') {
                            console.log(`[${requestId}] 响应无效:`, response ? response.status : 'null');
                            return response;
                        }

                        // 克隆响应，因为响应流只能使用一次
                        const responseToCache = response.clone();

                        // 添加到缓存
                        cache.put(request, responseToCache);
                        console.log(`[${requestId}] 背景已添加到缓存:`, url.pathname);

                        return response;
                    }).catch(error => {
                        console.error(`[${requestId}] 获取背景失败:`, error);
                        // 返回一个简单的错误响应
                        return new Response('背景加载失败', { status: 404, statusText: 'Not Found' });
                    });
                });
            })
        );
    }

    // 其他请求正常处理
    return;
});