const CACHE_NAME = 'tep-tv-cache-v2';
const ASSETS = [
    '/',
    '/index.html',
    '/logo.png',
    '/poster 3.png',
    '/poster 4.png'
];

// Install Event
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            console.log('[Service Worker] Pre-caching offline assets...');
            return cache.addAll(ASSETS);
        }).then(() => self.skipWaiting())
    );
});

// Activate Event
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((keys) => {
            return Promise.all(
                keys.map((key) => {
                    if (key !== CACHE_NAME) {
                        console.log('[Service Worker] Removing old cache:', key);
                        return caches.delete(key);
                    }
                })
            );
        }).then(() => self.clients.claim())
    );
});

// Fetch Interceptor with Strategy Routing
self.addEventListener('fetch', (event) => {
    // Only intercept local HTTP/HTTPS requests
    if (!event.request.url.startsWith(self.location.origin)) {
        return;
    }

    const url = new URL(event.request.url);
    const isImage = url.pathname.match(/\.(png|jpg|jpeg|gif|svg|webp)$/i);

    if (isImage) {
        // Stale-While-Revalidate for images (Logos, Posters)
        event.respondWith(
            caches.match(event.request).then((cachedResponse) => {
                const fetchPromise = fetch(event.request).then((networkResponse) => {
                    if (networkResponse && networkResponse.status === 200) {
                        caches.open(CACHE_NAME).then((cache) => {
                            cache.put(event.request, networkResponse.clone());
                        });
                    }
                    return networkResponse;
                }).catch(() => {
                    return cachedResponse;
                });
                return cachedResponse || fetchPromise;
            })
        );
    } else {
        // Stale-While-Revalidate for HTML, JS, CSS for instantaneous boot loads
        event.respondWith(
            caches.match(event.request).then((cachedResponse) => {
                const fetchPromise = fetch(event.request).then((networkResponse) => {
                    if (networkResponse && networkResponse.status === 200 && networkResponse.type === 'basic') {
                        const responseClone = networkResponse.clone();
                        caches.open(CACHE_NAME).then((cache) => {
                            cache.put(event.request, responseClone);
                        });
                    }
                    return networkResponse;
                }).catch(() => {
                    return cachedResponse;
                });
                return cachedResponse || fetchPromise;
            })
        );
    }
});
