/**
 * Claude Board - Service Worker
 *
 * Minimal service worker to satisfy PWA install requirements.
 * Caches the app shell for offline capability.
 */

const CACHE_NAME = 'claude-board-v1';
const APP_SHELL = [
    '/',
    '/static/style.css',
    '/static/app.js',
];

self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL))
    );
    self.skipWaiting();
});

self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((keys) =>
            Promise.all(
                keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))
            )
        )
    );
    self.clients.claim();
});

self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // Never cache WebSocket, API, or terminal requests
    if (
        url.pathname.startsWith('/ws') ||
        url.pathname.startsWith('/api/') ||
        event.request.method !== 'GET'
    ) {
        return;
    }

    // Network-first for app shell, fall back to cache
    event.respondWith(
        fetch(event.request)
            .then((response) => {
                const clone = response.clone();
                caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
                return response;
            })
            .catch(() => caches.match(event.request))
    );
});
