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

// Auto-recover from stale dynamic-import chunks after a new deploy.
const RELOAD_KEY = "__chunk_reload_attempt__";
const isChunkLoadError = (msg: string) =>
  /Importing a module script failed|Failed to fetch dynamically imported module|error loading dynamically imported module|ChunkLoadError/i.test(
    msg || ""
  );

const tryReload = () => {
  try {
    const n = Number(sessionStorage.getItem(RELOAD_KEY) || "0");
    if (n >= 1) return; // avoid infinite loops
    sessionStorage.setItem(RELOAD_KEY, String(n + 1));
  } catch {}
  window.location.reload();
};

window.addEventListener("error", (e) => {
  if (isChunkLoadError(e?.message)) tryReload();
});
window.addEventListener("unhandledrejection", (e) => {
  const msg = (e?.reason && (e.reason.message || String(e.reason))) || "";
  if (isChunkLoadError(msg)) tryReload();
});

// Clear the guard once the app has loaded successfully.
window.addEventListener("load", () => {
  try { sessionStorage.removeItem(RELOAD_KEY); } catch {}
});

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