const STATIC_CACHE_NAME = 'v2.2.1';

const FILES_TO_CACHE = [
    '/',
    "/css/main.css",
    "/config.js",
    "/lib/router/router.js",
    "/lib/router/routes.js",

    "/lib/customElements/notifManager.js",
    "/lib/customElements/pwaInstallBanner.js",
    "/lib/customElements/swipeUpdater.js",
    "/lib/customElements/menuContainer.js",
    "/lib/customElements/territoryCard.js",
    "/lib/customElements/smartSelect.js",

    "/lib/components/leaflet/leaflet.css",
    "/lib/components/leaflet/leaflet.js",

    "/lib/components/geoman/leaflet-geoman.css",
    "/lib/components/geoman/leaflet-geoman.min.js",

    "/lib/components/turf.min.js",

    "/lib/components/cloud.js",

    "/lib/components/clipboard.js",
    "/lib/components/colorGroup.js",
    "/lib/components/makeid.js",
    "/lib/components/detectBrowser.js",
    "/lib/components/detectOS.js",
    "/lib/components/formattedDate.js",
    "/lib/components/setLeafletCursor.js",
    "/lib/components/webPush.js",

    "/lib/pages/auth/script.js",
    "/lib/pages/auth/style.css",
    "/lib/pages/auth/index.html",

    "/lib/pages/home/script.js",
    "/lib/pages/home/style.css",
    "/lib/pages/home/index.html",

    "/lib/pages/territory/list/script.js",
    "/lib/pages/territory/list/style.css",
    "/lib/pages/territory/list/index.html",

    "/lib/pages/territory/manager/script.js",
    "/lib/pages/territory/manager/style.css",
    "/lib/pages/territory/manager/index.html",

    "/lib/pages/territory/map/script.js",
    "/lib/pages/territory/map/style.css",
    "/lib/pages/territory/map/index.html",

    "/lib/pages/territory/history/script.js",
    "/lib/pages/territory/history/style.css",
    "/lib/pages/territory/history/index.html",

    "/lib/pages/territory/constructor/script.js",
    "/lib/pages/territory/constructor/style.css",
    "/lib/pages/territory/constructor/index.html",

    "/lib/pages/territory/editor/script.js",
    "/lib/pages/territory/editor/style.css",
    "/lib/pages/territory/editor/index.html",

    "/lib/pages/territory/editor/script.js",
    "/lib/pages/territory/editor/style.css",
    "/lib/pages/territory/editor/index.html",

    "/lib/pages/territory/card/script.js",
    "/lib/pages/territory/card/style.css",
    "/lib/pages/territory/card/index.html",

    "/lib/pages/options/script.js",
    "/lib/pages/options/style.css",
    "/lib/pages/options/index.html",

    "/lib/pages/sheeps/script.js",
    "/lib/pages/sheeps/style.css",
    "/lib/pages/sheeps/index.html",

    "/lib/pages/stand/list/script.js",
    "/lib/pages/stand/list/style.css",
    "/lib/pages/stand/list/index.html",

    "/lib/pages/stand/card/script.js",
    "/lib/pages/stand/card/style.css",
    "/lib/pages/stand/card/index.html",

    "/lib/pages/stand/constructor/script.js",
    "/lib/pages/stand/constructor/style.css",
    "/lib/pages/stand/constructor/index.html",

    "/lib/pages/schedule/list/script.js",
    "/lib/pages/schedule/list/style.css",
    "/lib/pages/schedule/list/index.html",

    "/lib/pages/schedule/constructor/script.js",
    "/lib/pages/schedule/constructor/style.css",
    "/lib/pages/schedule/constructor/index.html",

    "/lib/app.js"
];

// ----------------------- INSTALL -----------------------
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(STATIC_CACHE_NAME).then(cache => {
            return Promise.all(FILES_TO_CACHE.map(url =>
                fetch(url).then(res => {
                    if (!res.ok) throw new Error(`${url} not found`);
                    return cache.put(url, res);
                }).catch(err => console.warn('[ServiceWorker] ', err))
            ));
        })
    );
});


// ----------------------- ACTIVATE -----------------------
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(keys.map(key => {
                if (key !== STATIC_CACHE_NAME) return caches.delete(key);
            }));
        }).then(() => self.clients.claim())
    );
});

// ----------------------- FETCH -----------------------
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(cached => cached ?? fetch(event.request))
    );
});

// ----------------------- PUSH -----------------------
self.addEventListener("push", event => {
    let data = {};
    try { data = event.data.json(); } catch { data = { title: "Повідомлення", body: event.data?.text() }; }

    console.log('[ServiceWorker] ', data);


    const title = data.title || "Повідомлення";
    const options = {
        body: data.body || "",
        icon: "/img/icon.png",
        badge: "/img/badge.png",
        data: data.url || "/"
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener("notificationclick", event => {
    event.notification.close();
    event.waitUntil(
        clients.matchAll({ type: "window", includeUncontrolled: true }).then(clientList => {
            for (const client of clientList) {
                if (client.url === event.notification.data && "focus" in client) return client.focus();
            }
            if (clients.openWindow) return clients.openWindow(event.notification.data);
        })
    );
});

// ----------------------- UPDATE CACHE -----------------------
self.addEventListener('message', event => {
    if (event.data === 'skipWaiting') {
        self.skipWaiting(); // активує новий воркер, але не оновлює кеш автоматично
    }
    if (event.data === 'updateCache') {
        updateALL(); // кеш оновлюється тільки після натискання на банер
    }
});

async function updateALL() {
    const cacheNames = await caches.keys();
    await Promise.all(cacheNames.map(name => caches.delete(name)));

    const cache = await caches.open(STATIC_CACHE_NAME);
    await Promise.all(FILES_TO_CACHE.map(url =>
        fetch(url).then(res => {
            if (!res.ok) throw new Error(`${url} not found`);
            return cache.put(url, res);
        }).catch(err => console.warn('[ServiceWorker] ', err))
    ));
    console.log('[ServiceWorker] All caches updated');
}