/**
 * Yatoon Staff Portal - Service Worker
 * Scope: /yatoon-staff/ (or wherever the portal page lives)
 * Caches portal shell for offline "You're offline" graceful message.
 */

const CACHE = 'yatoon-staff-v1';
const SHELL = []; // populated dynamically via install event

self.addEventListener('install', (e) => {
    self.skipWaiting();
});

self.addEventListener('activate', (e) => {
    e.waitUntil(
        caches.keys()
            .then(keys => Promise.all(
                keys.filter(k => k.startsWith('yatoon-staff-') && k !== CACHE)
                    .map(k => caches.delete(k))
            ))
            .then(() => self.clients.claim())
    );
});

self.addEventListener('fetch', (e) => {
    const url = new URL(e.request.url);

    // Never intercept AJAX / REST
    if (
        e.request.method !== 'GET' ||
        url.searchParams.has('action') ||
        url.pathname.includes('/wp-json/')
    ) return;

    // Cache-first for plugin static assets (CSS/JS/images)
    if (
        url.pathname.includes('/yatoon-booking-system/assets/') &&
        /\.(css|js|png|jpg|jpeg|svg|webp|woff2?)$/.test(url.pathname)
    ) {
        e.respondWith(
            caches.match(e.request).then(cached => {
                if (cached) return cached;
                return fetch(e.request).then(resp => {
                    if (!resp || resp.status !== 200) return resp;
                    const clone = resp.clone();
                    caches.open(CACHE).then(c => c.put(e.request, clone));
                    return resp;
                });
            })
        );
        return;
    }

    // Network-first for portal page itself
    e.respondWith(
        fetch(e.request).catch(() =>
            caches.match(e.request).then(cached => cached || new Response(
                '<h2 style="font-family:sans-serif;padding:32px">You\'re offline. Please reconnect to view your schedule.</h2>',
                { headers: { 'Content-Type': 'text/html' } }
            ))
        )
    );
});
