// πŸ€– NOTE: This file creates a service worker that cross-origin-isolates the page (read more here: https://web.dev/coop-coep/)
// πŸ” Normally you'd set the COOP and COEP headers on the server (yum), but Github Pages said: "No burgers for you!" πŸ”
// πŸ• So, we're doing a cheeky pizza hack πŸ• to make this work without server-side headers.

/* πŸ› οΈ Edited version of: coi-serviceworker v0.1.6 - Guido Zuidhof, licensed under MIT πŸ› οΈ */
// πŸ§™β€β™‚οΈ We're using wizardry from here: https://github.com/gzuidhof/coi-serviceworker

if (typeof window === 'undefined') { 
  // πŸ› οΈ Service Worker Time! (No windows allowed in this club)
  
  // πŸš€ Install event: "Let's skip the line and go straight to work!"
  self.addEventListener("install", () => self.skipWaiting());

  // πŸ”‹ Activate event: "I claim all clients! Mine! All mine!" (Mwahaha 😈)
  self.addEventListener("activate", e => e.waitUntil(self.clients.claim()));

  // 🍴 Handle fetch requests, like a master chef in the kitchen!
  async function handleFetch(request) {
    // πŸ§‚ Special seasoning: If we're caching but the mode's not right, we pass.
    if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
      return;
    }

    // πŸ•ΆοΈ For no-cors requests, we're keeping it cool 😎 with 'omit' credentials (Bug workarounds are fun, right? πŸ™„)
    if (request.mode === "no-cors") { 
      request = new Request(request.url, {
        cache: request.cache,
        credentials: "omit",
        headers: request.headers,
        integrity: request.integrity,
        destination: request.destination,
        keepalive: request.keepalive,
        method: request.method,
        mode: request.mode,
        redirect: request.redirect,
        referrer: request.referrer,
        referrerPolicy: request.referrerPolicy,
        signal: request.signal,
      });
    }

    // 🌍 Fetching data like a worldwide explorer! 🧭
    let r = await fetch(request).catch(e => console.error(e));

    // πŸ‘€ If the response status is zero, we return it β€” probably not what we were hoping for, but hey, it's something πŸ€·β€β™‚οΈ
    if (r.status === 0) {
      return r;
    }

    // 🎩 Magic header time! Setting the Cross-Origin rules like a boss πŸ§™β€β™€οΈ
    const headers = new Headers(r.headers);
    headers.set("Cross-Origin-Embedder-Policy", "credentialless"); // πŸ›‘οΈ Or: 'require-corp', for those fancy users
    headers.set("Cross-Origin-Opener-Policy", "same-origin"); // 🧱 Keep it locked down and safe.

    return new Response(r.body, { status: r.status, statusText: r.statusText, headers });
  }

  // πŸ—οΈ Fetch event listener: "Don't worry, I've got this!" Handling requests like a pro 🎯
  self.addEventListener("fetch", function(e) {
    e.respondWith(handleFetch(e.request)); // πŸ’‘ respondWith must be synchronous, like a well-timed joke! (But it can wait for a promise πŸ˜‰)
  });

} else {
  // 🌍 If we're running in a window (hello, browser!), we register the service worker like a superhero suiting up πŸ¦Έβ€β™€οΈ
  (async function() {
    // ❗ If we're already isolated, let's not double down on the isolation 😎
    if (window.crossOriginIsolated !== false) return;

    // 🎟️ Registering the service worker like we're entering the coolest club in town!
    let registration = await navigator.serviceWorker.register(window.document.currentScript.src).catch(e => console.error("COOP/COEP Service Worker failed to register:", e));
    
    if (registration) {
      console.log("COOP/COEP Service Worker registered", registration.scope);

      // πŸ†• When the service worker updates, we refresh the page like a fresh cup of coffee β˜•
      registration.addEventListener("updatefound", () => {
        console.log("Reloading page to make use of updated COOP/COEP Service Worker.");
        window.location.reload();
      });

      // πŸ›‘ If the service worker is active but not in control, we give the page a fresh reboot πŸš€
      if (registration.active && !navigator.serviceWorker.controller) {
        console.log("Reloading page to make use of COOP/COEP Service Worker.");
        window.location.reload();
      }
    }
  })();
}

// πŸ—‘οΈ Code to clean up: "Time to say goodbye!" Unregister the service worker and take out the trash 🧹
// let registrations = await navigator.serviceWorker.getRegistrations();
// for(let registration of registrations) {
//   await registration.unregister();
// }