const CACHE_NAME = "nern-v50-clean-url";
const APP_SHELL = [
  "./",
  "./index.html",
  "./manifest.webmanifest",
  "./icons/icon.svg",
  "./icons/icon-192.png",
  "./icons/icon-512.png",
  "./vendor/xlsx.full.min.js",
  "./tutorials/daily-nudge-queue.webm?v=5",
  "./tutorials/advance-a-deal.webm?v=5",
  "./tutorials/client-memory.webm?v=5",
  "./tutorials/send-a-template.webm?v=5"
];

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

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

self.addEventListener("fetch", event => {
  if (event.request.method !== "GET") return;
  const requestUrl = new URL(event.request.url);
  if (requestUrl.origin !== self.location.origin || requestUrl.pathname.startsWith("/api/")) return;

  if (event.request.mode === "navigate") {
    event.respondWith(
      fetch(event.request)
        .then(response => {
          if (!response.ok) throw new Error(`Navigation failed: ${response.status}`);
          const copy = response.clone();
          return caches.open(CACHE_NAME)
            .then(cache => cache.put("./index.html", copy))
            .then(() => response);
        })
        .catch(() => caches.match("./index.html").then(cached => cached || new Response(
          "<!doctype html><title>Nern offline</title><h1>Nern is offline</h1><p>Reconnect once to refresh the app cache.</p>",
          { headers: { "Content-Type": "text/html; charset=utf-8" } }
        )))
    );
    return;
  }

  event.respondWith(
    caches.match(event.request).then(cached => {
      if (cached) return cached;
      return fetch(event.request).then(response => {
        if (!response.ok) return response;
        const copy = response.clone();
        return caches.open(CACHE_NAME)
          .then(cache => cache.put(event.request, copy))
          .then(() => response);
      });
    })
  );
});

