/**
 * Yatoon Booking System - Merchant Admin PWA Service Worker
 * Scope: /wp-admin/admin.php?page=yatoon-* (registered at /wp-admin/ scope)
 * Note: WordPress restricts SW scope to the path the SW file is served from.
 * This SW is served via a PHP proxy at /wp-admin/yatoon-sw-admin.js
 */

const CACHE_NAME = 'yatoon-admin-v1';

// ── Install ───────────────────────────────────────────────────────────────────
self.addEventListener('install', (event) => {
    self.skipWaiting();
});

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

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

    // Skip POST, AJAX, wp-json
    if (
        event.request.method !== 'GET' ||
        url.pathname.includes('/wp-json') ||
        url.searchParams.has('action')   // wp-admin AJAX calls
    ) {
        return;
    }

    // Cache plugin's own CSS/JS/images (from /wp-content/plugins/yatoon-*)
    if (
        url.pathname.includes('/yatoon-booking-system/assets/') &&
        url.pathname.match(/\.(css|js|png|jpg|jpeg|gif|svg|webp|woff|woff2)$/)
    ) {
        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((c) => c.put(event.request, clone));
                    return response;
                });
            })
        );
    }
    // All other requests: network only (don't cache admin pages)
});

// ── Push Notifications - new booking alerts ───────────────────────────────────
self.addEventListener('push', (event) => {
    if (!event.data) return;

    let data = {};
    try {
        data = event.data.json();
    } catch (e) {
        data = { title: 'New Booking', body: event.data.text() };
    }

    const options = {
        body:    data.body    || 'A new appointment has been booked.',
        icon:    data.icon    || '/yatoon-icon-192.png',
        badge:   data.badge   || '/yatoon-icon-96.png',
        vibrate: [200, 100, 200],
        tag:     data.tag     || 'yatoon-booking',
        renotify: true,
        data: {
            url: data.url || '/wp-admin/admin.php?page=yatoon-booking-system',
            bookingId: data.booking_id || null,
        },
        actions: [
            { action: 'view',    title: 'View Booking' },
            { action: 'dismiss', title: 'Dismiss' },
        ],
    };

    event.waitUntil(
        self.registration.showNotification(data.title || '📅 New Booking', options)
    );
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();

    if (event.action === 'dismiss') return;

    const target =
        (event.notification.data && event.notification.data.url) ||
        '/wp-admin/admin.php?page=yatoon-booking-system';

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
            // Focus existing admin tab if open
            for (const client of windowClients) {
                if (client.url.includes('yatoon-booking-system') && 'focus' in client) {
                    return client.focus();
                }
            }
            // Otherwise open new tab
            if (clients.openWindow) return clients.openWindow(target);
        })
    );
});
