const CACHE_NAME = "amaris-cache-v1";
const urlsToCache = [
  "/",
  "/about",
  "/contact",
  "/services",
  "/portfolio",
  "/blog",
  "/pricing",
  "/faq",
  "/legal/privacy",
  "/legal/terms",
  "/legal/cookies",
  "/manifest.json",
  "/icon.svg",
  "/apple-icon.svg",
];

const isLocalhost = 
  self.location.hostname === "localhost" || 
  self.location.hostname === "127.0.0.1" ||
  self.location.hostname.startsWith("192.168.");

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

self.addEventListener("fetch", (event) => {
  if (isLocalhost) return; // Bypass service worker cache for local development to prevent infinite reloading loops
  
  event.respondWith(
    caches.match(event.request).then((response) => {
      if (response) return response;
      return fetch(event.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(event.request, responseToCache);
        });
        return response;
      });
    })
  );
});

self.addEventListener("activate", (event) => {
  if (isLocalhost) {
    event.waitUntil(
      self.registration.unregister().then(() => self.clients.claim())
    );
    return;
  }
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
