const CACHE_NAME = "putzliga-shell-v4";
const ASSETS = [
  "/static/css/style.css",
  "/static/js/app.js",
  "/static/images/favicon.png",
  "/static/images/apple-touch-icon.png",
  "/static/images/logo-mark.png",
  "/static/images/pwa-icon-192.png",
  "/static/images/pwa-icon-512.png"
];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)));
  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)))
    )
  );
  self.clients.claim();
});

self.addEventListener("fetch", (event) => {
  if (event.request.method !== "GET") return;
  const url = new URL(event.request.url);
  const isStaticAsset =
    url.origin === self.location.origin &&
    (
      url.pathname.startsWith("/static/") ||
      url.pathname === "/manifest.json" ||
      url.pathname === "/service-worker.js"
    );

  if (event.request.mode === "navigate") {
    event.respondWith(fetch(event.request));
    return;
  }

  if (!isStaticAsset) {
    return;
  }

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

self.addEventListener("push", (event) => {
  const payload = event.data ? event.data.json() : {};
  const title = payload.title || "Putzliga";
  event.waitUntil(
    self.registration.showNotification(title, {
      body: payload.body || "Es gibt Neuigkeiten in der Putzliga.",
      icon: payload.icon || "/static/images/pwa-icon-192.png",
      badge: payload.badge || "/static/images/pwa-badge.png",
      tag: payload.tag || "putzliga",
      data: { url: payload.url || "/my-tasks" }
    })
  );
});

self.addEventListener("notificationclick", (event) => {
  event.notification.close();
  const targetUrl = event.notification.data?.url || "/my-tasks";
  event.waitUntil(
    clients.matchAll({ type: "window", includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if ("focus" in client) {
          client.navigate(targetUrl);
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(targetUrl);
      }
    })
  );
});
