const CACHE_NAME = "foundation-cache-v1";
const ASSETS_TO_CACHE = [
  "/",
  "/css/site.css",
  "/css/inter.css",
  "/css/bootstrap-icons.min.css",
  "/css/all.min.css",
  "/lib/bootstrap/dist/css/bootstrap.min.css",
  "/lib/jquery/dist/jquery.min.js",
  "/lib/bootstrap/dist/js/bootstrap.bundle.min.js",
  "/js/site.js",
];

// Install Event
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll(ASSETS_TO_CACHE);
    })
  );
  self.skipWaiting();
});

// Activate Event
self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cache) => {
          if (cache !== CACHE_NAME) {
            return caches.delete(cache);
          }
        })
      );
    })
  );
  self.clients.claim();
});

// Fetch Event - Stale-While-Revalidate Strategy
self.addEventListener("fetch", (event) => {
  // Skip non-GET requests
  if (event.request.method !== "GET") return;

  event.respondWith(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.match(event.request).then((cachedResponse) => {
        const fetchedResponse = fetch(event.request)
          .then((networkResponse) => {
            // Update cache with new response
            if (networkResponse.ok) {
              cache.put(event.request, networkResponse.clone());
            }
            return networkResponse;
          })
          .catch(() => {
            // If network fails and no cache, maybe return an offline page
            return cachedResponse;
          });

        return cachedResponse || fetchedResponse;
      });
    })
  );
});
