/* MyClaw mobile shell cache — network-first, offline fallback for static shell.
 * 资产更新策略：每次 SW activate 时清理旧缓存；页面请求始终网络优先，
 * 失败（离线）才回退缓存，保证 web/ 热更新立刻可见。 */
const CACHE = 'myclaw-shell-v1';
const SHELL = ['/mobile', '/mobile.css', '/mobile.js', '/manifest.json', '/icon.svg'];

self.addEventListener('install', (e) => {
  e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
});

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

self.addEventListener('fetch', (e) => {
  const url = new URL(e.request.url);
  if (e.request.method !== 'GET' || url.pathname.startsWith('/ws')) return;
  // API 与 WebSocket 握手永不缓存；仅缓存静态壳资产。
  const cacheable = SHELL.includes(url.pathname) || url.pathname.startsWith('/icon');
  if (!cacheable) return;
  e.respondWith(
    fetch(e.request)
      .then((resp) => {
        const copy = resp.clone();
        caches.open(CACHE).then((c) => c.put(e.request, copy));
        return resp;
      })
      .catch(() => caches.match(e.request))
  );
});
