// Service Worker for persistent tile + asset caching.
// Strategy: cache-first for tiles (fast repeat loads, offline-capable),
// network-first for HTML/JS (fresh code on each reload).
const VERSION = 'v18';
const TILE_CACHE = 'gendesign-tiles-' + VERSION;
const ASSET_CACHE = 'gendesign-assets-' + VERSION;
const TILE_HOSTS = [
  'basemaps.cartocdn.com',
  'tile.openstreetmap.org',
  'tile.openstreetmap.fr',
  'maps.2gis.com',
  'server.arcgisonline.com',
  'core-renderer-tiles.maps.yandex.net',
  'core-sat.maps.yandex.net',
  'unpkg.com',
  'cdn.jsdelivr.net',
];

self.addEventListener('install', e => {
  self.skipWaiting();
});

self.addEventListener('activate', e => {
  e.waitUntil((async () => {
    const keys = await caches.keys();
    await Promise.all(keys.filter(k => !k.endsWith(VERSION)).map(k => caches.delete(k)));
    await self.clients.claim();
  })());
});

self.addEventListener('fetch', e => {
  const req = e.request;
  if (req.method !== 'GET') return;
  const url = new URL(req.url);
  const isTile = TILE_HOSTS.some(h => url.hostname.endsWith(h));
  if (!isTile) return;  // let same-origin (FastAPI) requests pass through normally

  e.respondWith((async () => {
    const cacheName = url.hostname.includes('basemaps') || url.hostname.endsWith('cdn.jsdelivr.net') || url.hostname === 'unpkg.com'
                       ? ASSET_CACHE : TILE_CACHE;
    const cache = await caches.open(cacheName);
    const cached = await cache.match(req);
    if (cached) {
      // refresh in background (stale-while-revalidate)
      fetch(req).then(r => { if (r.ok) cache.put(req, r.clone()); }).catch(()=>{});
      return cached;
    }
    try {
      const resp = await fetch(req);
      if (resp.ok && resp.status === 200) {
        // size check — don't cache huge >1 MB blobs
        const len = +resp.headers.get('content-length') || 0;
        if (len < 2_000_000) cache.put(req, resp.clone());
      }
      return resp;
    } catch (err) {
      // offline: try fallback (e.g. blank tile) — for now just rethrow
      throw err;
    }
  })());
});

self.addEventListener('message', e => {
  if (e.data === 'clear-cache') {
    caches.keys().then(ks => Promise.all(ks.map(k => caches.delete(k))));
  }
});
