const CACHE_NAME = "compagnon-lagon-v1";
const urlsToCache = [
  "/",
  "/accueil",
  "/explorer",
  "/mana-tracker",
  "/infos",
  "/manifest.json",
];

const API_CACHE_NAME = "compagnon-lagon-api-v1";

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

self.addEventListener("fetch", (event) => {
  const { request } = event;
  const url = new URL(request.url);

  // Cache strategy pour les API routes
  if (url.pathname.startsWith("/api/")) {
    event.respondWith(
      caches.open(API_CACHE_NAME).then((cache) => {
        return cache.match(request).then((cachedResponse) => {
          if (cachedResponse) {
            // Retourner le cache et mettre à jour en arrière-plan
            fetch(request)
              .then((response) => {
                if (response && response.status === 200) {
                  cache.put(request, response.clone());
                }
              })
              .catch(() => {});
            return cachedResponse;
          }
          // Pas de cache, faire la requête
          return fetch(request)
            .then((response) => {
              if (response && response.status === 200) {
                cache.put(request, response.clone());
              }
              return response;
            })
            .catch(() => {
              // En cas d'erreur réseau, retourner une réponse par défaut
              return new Response(
                JSON.stringify({ error: "Offline" }),
                {
                  status: 503,
                  headers: { "Content-Type": "application/json" },
                }
              );
            });
        });
      })
    );
    return;
  }

  // Cache strategy pour les pages statiques
  event.respondWith(
    caches.match(request).then((response) => {
      if (response) {
        return response;
      }
      return fetch(request)
        .then((response) => {
          if (!response || response.status !== 200 || response.type !== "basic") {
            return response;
          }
          const responseToCache = response.clone();
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(request, responseToCache);
          });
          return response;
        })
        .catch(() => {
          // Retourner une page offline si disponible
          return caches.match("/offline");
        });
    })
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames
          .filter(
            (cacheName) =>
              cacheName !== CACHE_NAME && cacheName !== API_CACHE_NAME
          )
          .map((cacheName) => caches.delete(cacheName))
      );
    })
  );
});

// Gestion des notifications push
self.addEventListener("push", (event) => {
  const data = event.data ? event.data.json() : {};
  const title = data.title || "Compagnon du lagon - Pension Marama";
  const options = {
    body: data.message || "Nouvelle notification",
    icon: "/icon-192x192.png",
    badge: "/icon-192x192.png",
    tag: data.id || "notification",
    requireInteraction: data.important || false,
    data: data,
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

// Gestion du clic sur une notification
self.addEventListener("notificationclick", (event) => {
  event.notification.close();

  const data = event.notification.data;
  const urlToOpen = data.url || "/mana-tracker";

  event.waitUntil(
    clients
      .matchAll({
        type: "window",
        includeUncontrolled: true,
      })
      .then((clientList) => {
        for (let i = 0; i < clientList.length; i++) {
          const client = clientList[i];
          if (client.url === urlToOpen && "focus" in client) {
            return client.focus();
          }
        }
        if (clients.openWindow) {
          return clients.openWindow(urlToOpen);
        }
      })
  );
});

