import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

const CHUNK_RECOVERY_KEY = "_chunk_recovery_attempted";

async function hardRecoverFromChunkError() {
  if (sessionStorage.getItem(CHUNK_RECOVERY_KEY) === "1") return;
  sessionStorage.setItem(CHUNK_RECOVERY_KEY, "1");

  try {
    if ("caches" in window) {
      const names = await caches.keys();
      await Promise.all(names.map((name) => caches.delete(name)));
    }

    if ("serviceWorker" in navigator) {
      const registrations = await navigator.serviceWorker.getRegistrations();
      await Promise.all(registrations.map((registration) => registration.unregister()));
    }
  } finally {
    window.location.reload();
  }
}

function isChunkLoadError(reason: unknown) {
  const message = reason instanceof Error ? reason.message : String(reason ?? "");
  return message.includes("Failed to fetch dynamically imported module")
    || message.includes("Importing a module script failed")
    || message.includes("ChunkLoadError");
}

window.addEventListener("error", (event) => {
  if (isChunkLoadError(event.error ?? event.message)) {
    void hardRecoverFromChunkError();
  }
});

window.addEventListener("unhandledrejection", (event) => {
  if (isChunkLoadError(event.reason)) {
    void hardRecoverFromChunkError();
  }
});

createRoot(document.getElementById("root")!).render(<App />);
