/**
 * Yatoon Booking System - Customer Booking PWA Service Worker
 * Scope: public booking pages only (/yatoon-sw-booking-scope/)
 */

const CACHE_NAME = 'yatoon-booking-v4';
const STATIC_ASSETS = [
    // Core assets cached on install - paths are relative to SW scope
    // Actual URLs are rewritten at runtime via cache-first strategy
];

// ── Install: pre-cache nothing (avoid hardcoding URLs) ──────────────────────
self.addEventListener('install', (event) => {
    self.skipWaiting();
});

// ── Activate: clear old caches ───────────────────────────────────────────────
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((keys) =>
            Promise.all(
                keys
                    .filter((k) => k.startsWith('yatoon-booking-') && k !== CACHE_NAME)
                    .map((k) => caches.delete(k))
            )
        ).then(() => self.clients.claim())
    );
});

function isCacheablePluginAsset(url, response) {
    if (url.origin !== self.location.origin || !url.pathname.includes('/yatoon-booking-system/assets/')) {
        return false;
    }
    if (!response || response.status !== 200 || response.type === 'opaque') {
        return false;
    }
    const control = response.headers.get('Cache-Control') || '';
    return !/(?:no-store|private)/i.test(control);
}

function offlineResponse() {
    return new Response('You are offline. Reconnect to continue booking.', {
        status: 503,
        headers: { 'Content-Type': 'text/plain; charset=UTF-8', 'Cache-Control': 'no-store' },
    });
}

// ── Fetch: never persist HTML/API responses; cache plugin static assets only ─
self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // Never cache admin, AJAX, or POST requests
    if (
        url.pathname.includes('/wp-admin') ||
        url.pathname.includes('/wp-json') ||
        url.searchParams.has('wc-ajax') ||
        event.request.method !== 'GET'
    ) {
        return;
    }

    // Booking HTML may contain customer-specific content and short-lived
    // WordPress nonces. Always request it from the network and never cache it.
    if (event.request.mode === 'navigate' || event.request.destination === 'document') {
        event.respondWith(fetch(event.request).catch(offlineResponse));
        return;
    }

    if (url.origin !== self.location.origin || !url.pathname.includes('/yatoon-booking-system/assets/')) {
        return;
    }

    // JS and CSS - Network-first (so plugin updates are always picked up)
    if (url.pathname.match(/\.(css|js)$/)) {
        event.respondWith(
            fetch(event.request).then((response) => {
                if (isCacheablePluginAsset(url, response)) {
                    const clone = response.clone();
                    return caches.open(CACHE_NAME)
                        .then((cache) => cache.put(event.request, clone))
                        .then(() => response);
                }
                return response;
            }).catch(() => caches.match(event.request))
        );
        return;
    }

    // Static assets (images, fonts) - Cache-first
    if (
        url.pathname.match(/\.(png|jpg|jpeg|gif|svg|webp|woff|woff2|ico)$/)
    ) {
        event.respondWith(
            caches.match(event.request).then((cached) => {
                if (cached) return cached;
                return fetch(event.request).then((response) => {
                    if (isCacheablePluginAsset(url, response)) {
                        const clone = response.clone();
                        return caches.open(CACHE_NAME)
                            .then((cache) => cache.put(event.request, clone))
                            .then(() => response);
                    }
                    return response;
                });
            })
        );
        return;
    }

    // Non-static responses remain under normal browser/network handling.
});

// ── Push Notifications (future use) ──────────────────────────────────────────
self.addEventListener('push', (event) => {
    if (!event.data) return;
    const data = event.data.json();
    event.waitUntil(
        self.registration.showNotification(data.title || 'Yatoon Booking', {
            body: data.body || '',
            icon: data.icon || '/yatoon-icon-192.png',
            badge: data.badge || '/yatoon-icon-96.png',
            data: { url: data.url || '/' },
        })
    );
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    const target = (event.notification.data && event.notification.data.url) || '/';
    event.waitUntil(clients.openWindow(target));
});
