"use client";

import { useEffect } from "react";
import { PWA_VERSION } from "@/lib/pwaConfig";

function isIosSafari(): boolean {
  if (typeof navigator === "undefined") return false;
  const ua = navigator.userAgent;
  return /iphone|ipad|ipod/i.test(ua) && !/crios|fxios|edgios/i.test(ua);
}

async function cleanupStaleServiceWorkers() {
  if (!("serviceWorker" in navigator)) return;

  try {
    const registrations = await navigator.serviceWorker.getRegistrations();
    await Promise.all(
      registrations.map((registration) => registration.unregister())
    );
  } catch {
    // ignore
  }
}

export default function RegisterSW() {
  useEffect(() => {
    if (!("serviceWorker" in navigator)) return;

    const register = async () => {
      try {
        const registration = await navigator.serviceWorker.register(
          `/service-worker.js?v=${PWA_VERSION}`,
          { scope: "/" }
        );
        await registration.update();
      } catch (error) {
        console.error("Service Worker registration failed:", error);
        if (isIosSafari()) {
          await cleanupStaleServiceWorkers();
        }
      }
    };

    if (document.readyState === "complete") {
      void register();
    } else {
      window.addEventListener("load", () => void register(), { once: true });
    }
  }, []);

  return null;
}
