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

try {
  if (localStorage.getItem("asuacasa_theme") === "dark") {
    document.documentElement.classList.add("dark");
  }
} catch {
  /* ignore */
}

// Recarrega quando um chunk lazy falha após deploy (ficheiros antigos removidos do CDN)
const RELOAD_KEY = "asuacasa_chunk_reload";
function isChunkLoadError(message: string): boolean {
  return /Failed to fetch dynamically imported module|Importing a module script failed|ChunkLoadError|Loading chunk [\d]+ failed/i.test(message);
}
function handleChunkError(message: string) {
  if (!isChunkLoadError(message)) return;
  try {
    const last = Number(sessionStorage.getItem(RELOAD_KEY) || "0");
    if (Date.now() - last < 10_000) return; // evita loop
    sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
  } catch { /* ignore */ }
  window.location.reload();
}
window.addEventListener("error", (e) => handleChunkError(e?.message || ""));
window.addEventListener("unhandledrejection", (e) => handleChunkError(String((e as PromiseRejectionEvent)?.reason?.message || (e as PromiseRejectionEvent)?.reason || "")));

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