// A robust, installable Service Worker for SPA (Inertia)

const CACHE_NAME = 'titan-news-cache-v1';
const OFFLINE_URL = '/offline.html'; // We will create this page soon if needed

// On install, pre-cache the offline page
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            // Pre-caching an offline page is a PWA best practice.
            // For now, we are skipping it to keep it simple, but the structure is here.
            // return cache.add(OFFLINE_URL);
            return self.skipWaiting();
        })
    );
});

// Clean up old caches on activation
self.addEventListener('activate', (event) => {
    event.waitUntil(
        (async () => {
            const cacheNames = await caches.keys();
            await Promise.all(
                cacheNames
                    .filter((name) => name !== CACHE_NAME)
                    .map((name) => caches.delete(name))
            );
            await clients.claim();
        })()
    );
});

// Handle fetch requests
self.addEventListener('fetch', (event) => {
    // We only want to handle navigation requests (page loads)
    if (event.request.mode === 'navigate') {
        event.respondWith(
            (async () => {
                try {
                    // First, try to fetch from the network
                    const networkResponse = await fetch(event.request);
                    return networkResponse;
                } catch (error) {
                    // If the network fails, it means the user is offline
                    console.log('Fetch failed; returning offline page instead.', error);

                    // You can optionally return a pre-cached offline page here
                    // const cache = await caches.open(CACHE_NAME);
                    // const cachedResponse = await cache.match(OFFLINE_URL);
                    // return cachedResponse;
                    
                    // For now, we just let the browser handle the offline error
                    return new Response('Network error occurred', {
                        status: 408,
                        headers: { 'Content-Type': 'text/plain' },
                    });
                }
            })()
        );
    }
});