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

initSentry();

const CHUNK_RELOAD_KEY = "megga_chunk_reload_once";

const shouldAutoReloadForChunkError = (message?: string) => {
  if (!message) return false;
  const normalized = message.toLowerCase();
  return (
    normalized.includes("failed to fetch dynamically imported module") ||
    normalized.includes("dynamically imported module") ||
    normalized.includes("importing a module script failed") ||
    normalized.includes("loading chunk")
  );
};

const safeReloadOnChunkError = (reason: unknown) => {
  const message = reason instanceof Error ? reason.message : String(reason ?? "");
  if (!shouldAutoReloadForChunkError(message)) return;

  if (!sessionStorage.getItem(CHUNK_RELOAD_KEY)) {
    sessionStorage.setItem(CHUNK_RELOAD_KEY, "1");
    window.location.reload();
  }
};

window.addEventListener("error", (event) => {
  safeReloadOnChunkError(event.error ?? event.message);
});

window.addEventListener("unhandledrejection", (event) => {
  safeReloadOnChunkError(event.reason);
});

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