import { createRoot } from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";

import App from "./App.tsx";
import "./index.css";
import { registerServiceWorker } from "./registerSW";
import { applyAppSystemBars, applySplashSystemBars } from "./lib/systemBars";
import { installAuthUserCache } from "./lib/authUserCache";
import { sanitizeStoredSession, installSessionRecovery } from "./lib/sessionIntegrity";

sanitizeStoredSession();
installAuthUserCache();
installSessionRecovery();
registerServiceWorker();

// Startbildschirm: System-Bars schwarz, damit sie nahtlos zum Splash passen.
applySplashSystemBars();


// Auto-recover from stale dynamic-import chunks after a new deploy.
// When the user's tab holds an old index bundle, code-split chunk hashes
// no longer exist on the server and `import()` throws. Reload once to
// pick up the fresh manifest.
const CHUNK_RELOAD_KEY = "bn_chunk_reload_ts";
function isChunkLoadError(message: string): boolean {
  return (
    message.includes("Failed to fetch dynamically imported module") ||
    message.includes("Importing a module script failed") ||
    message.includes("error loading dynamically imported module")
  );
}
function maybeReload() {
  try {
    const last = Number(sessionStorage.getItem(CHUNK_RELOAD_KEY) || "0");
    if (Date.now() - last < 10_000) return; // avoid reload loops
    sessionStorage.setItem(CHUNK_RELOAD_KEY, String(Date.now()));
  } catch {
    // sessionStorage blocked: fall back to the cache-bust timestamp in the URL,
    // which survives the reload, so we never loop.
    const prev = Number(new URL(window.location.href).searchParams.get("_r") || "0");
    if (prev && Date.now() - prev < 10_000) return;
  }
  // Cache-bust to force a fresh index.html + manifest from the CDN.
  const url = new URL(window.location.href);
  url.searchParams.set("_r", String(Date.now()));
  window.location.replace(url.toString());
}

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

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

// Splash ist ausgeblendet -> System-Bars auf die App-Farbe zurücksetzen.
requestAnimationFrame(() => {
  window.setTimeout(applyAppSystemBars, 400);
});


