/**
 * Service worker for /mobile PWA — scope: .../mobile/
 * Enables install + offline message when navigation fails.
 */
/* global self, caches, fetch */

const SW_URL = new URL(self.location.href);
const MOBILE_BASE = SW_URL.pathname.replace(/\/sw\.js$/i, '');
const OFFLINE_URL = SW_URL.origin + MOBILE_BASE + '/offline.html';
const CACHE_STATIC = 'nazareth-mobile-v1';

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_STATIC).then(function (cache) {
            return cache.add(OFFLINE_URL).catch(function () {
                return Promise.resolve();
            });
        })
    );
    self.skipWaiting();
});

self.addEventListener('activate', function (event) {
    event.waitUntil(
        caches.keys().then(function (keys) {
            return Promise.all(
                keys
                    .filter(function (k) {
                        return k.startsWith('nazareth-mobile-') && k !== CACHE_STATIC;
                    })
                    .map(function (k) {
                        return caches.delete(k);
                    })
            );
        }).then(function () {
            return self.clients.claim();
        })
    );
});

self.addEventListener('fetch', function (event) {
    var req = event.request;
    if (req.method !== 'GET' || req.mode !== 'navigate') return;

    event.respondWith(
        fetch(req).catch(function () {
            return caches.match(OFFLINE_URL).then(function (cached) {
                return cached || new Response('Offline', { status: 503, statusText: 'Offline' });
            });
        })
    );
});
