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

const CACHE_NAME = 'yatoon-booking-v2';
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())
    );
});

// ── Fetch: Network-first for API/AJAX/JS, Cache-first for images/fonts ───────
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;
    }

    // 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 (!response || response.status !== 200) return response;
                const clone = response.clone();
                caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
                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 (!response || response.status !== 200) return response;
                    const clone = response.clone();
                    caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
                    return response;
                });
            })
        );
        return;
    }

    // HTML pages - Network-first, fall back to cache
    event.respondWith(
        fetch(event.request)
            .then((response) => {
                if (!response || response.status !== 200) return response;
                const clone = response.clone();
                caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
                return response;
            })
            .catch(() => caches.match(event.request))
    );
});

// ── 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));
});
