import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import { registerPublicAssetServiceWorker } from "./public-asset-cache.js";
import { UserAuthPage } from "./user-auth.js";

const root = document.getElementById("root");

if (!root) {
  throw new Error("Dada web root element is missing.");
}

// Cache failure leaves public assets network-backed and must not create alternate persistence.
void registerPublicAssetServiceWorker().catch(() => undefined);

const appRoot = createRoot(root);
let authRevision = 0;

function renderAuthenticationEntry() {
  authRevision += 1;
  appRoot.render(
    <StrictMode>
      <UserAuthPage key={authRevision} />
    </StrictMode>,
  );
}

// Any authenticated surface can dispatch this after a revoked/invalid session response.
window.addEventListener("dada:session-invalid", renderAuthenticationEntry);
renderAuthenticationEntry();
