import { ViteReactSSG } from "vite-react-ssg";
import { routes } from "./routes";
import { initSentry } from "./lib/sentry";
import "./index.css";

// When a deploy ships new chunk hashes, browsers holding a stale index.html
// fail to import the old hashed chunks ("Failed to fetch dynamically imported
// module"). Force a one-time reload so they pick up the fresh index.html
// instead of a permanently broken page.
const RELOAD_KEY = "solvit:chunk-reload-at";
const handleChunkError = (message: string) => {
  if (!/Failed to fetch dynamically imported module|Importing a module script failed|ChunkLoadError/i.test(message)) return;
  const last = Number(sessionStorage.getItem(RELOAD_KEY) || 0);
  if (Date.now() - last < 10_000) return;
  sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
  window.location.reload();
};

export const createRoot = ViteReactSSG(
  {
    routes,
    basename: import.meta.env.BASE_URL,
  },
  ({ isClient }) => {
    if (!isClient) return;
    initSentry();
    window.addEventListener("error", (e) => handleChunkError(e?.message || ""));
    window.addEventListener("unhandledrejection", (e) => {
      const msg = (e?.reason && (e.reason.message || String(e.reason))) || "";
      handleChunkError(msg);
    });
  },
);
