// Familiar PWA Service Worker — offline shell + cache-first for static assets
const CACHE_NAME = 'familiar-v2-v1';
const SHELL_URLS = ['/v2/'];

// Install: cache the app shell
self.addEventListener('install', (event) => {
	event.waitUntil(
		caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_URLS))
	);
	self.skipWaiting();
});

// Activate: clean old caches
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();
});

// Fetch: cache-first for immutable assets, network-first for API + HTML
self.addEventListener('fetch', (event) => {
	const url = new URL(event.request.url);

	// API calls — always network
	if (url.pathname.startsWith('/api/')) return;

	// Immutable hashed assets — cache forever
	if (url.pathname.includes('/_app/immutable/')) {
		event.respondWith(
			caches.match(event.request).then(
				(cached) => cached || fetch(event.request).then((res) => {
					const clone = res.clone();
					caches.open(CACHE_NAME).then((c) => c.put(event.request, clone));
					return res;
				})
			)
		);
		return;
	}

	// HTML/navigation — network-first with shell fallback
	if (event.request.mode === 'navigate') {
		event.respondWith(
			fetch(event.request).catch(() => caches.match('/v2/'))
		);
		return;
	}
});
