import { StrictMode, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import "./styles/tokens.css";
import "./styles/global.css";

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

function render(node: ReactNode) {
  root.render(<StrictMode>{node}</StrictMode>);
}

/**
 * Network-failure handling (Phase 8 polish, spec §4.8): the dynamic imports
 * below fetch separate JS chunks over the network in a real deployment. If
 * that fetch fails (offline, a bad deploy, a flaky connection) the promise
 * rejects — with no `.catch`, that's an unhandled rejection AND `root.render`
 * never runs, so the page stays permanently blank with nothing in the DOM to
 * tell the user anything went wrong. Render a plain, dependency-free fallback
 * instead (no CSS classes from styles that themselves might not have loaded,
 * just inline styles) so there's always *something* legible on screen.
 */
function renderStartupFailure() {
  root.render(
    <main
      style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        gap: "0.75rem",
        padding: "2rem",
        textAlign: "center",
        fontFamily: "system-ui, sans-serif",
        color: "#2A2622",
      }}
    >
      <p style={{ fontSize: "1.25rem", margin: 0 }}>Castle Time couldn&apos;t start.</p>
      <p style={{ fontSize: "0.9375rem", margin: 0, color: "#5B5346" }}>
        Check your connection and reload the page.
      </p>
      <button
        type="button"
        onClick={() => window.location.reload()}
        style={{
          marginTop: "0.5rem",
          padding: "0.6rem 1.25rem",
          border: "none",
          borderRadius: "4px",
          background: "#445F6D",
          color: "#F2EAD3",
          cursor: "pointer",
        }}
      >
        Reload
      </button>
    </main>,
  );
}

if (import.meta.env.VITE_DEV_FIXTURES === "1") {
  // Dev fixture mode (visual QA without credentials): mount the main view
  // directly on fixture data — Firebase is never imported, so no config is
  // needed. The flag is a build-time constant (vite.config.ts `define`), so
  // this branch and everything it imports vanish from normal builds.
  void import("./components/CastleApp")
    .then(({ default: CastleApp }) => {
      render(<CastleApp />);
    })
    .catch(renderStartupFailure);
} else {
  void Promise.all([import("./App"), import("./lib/auth")])
    .then(([{ default: App }, { AuthProvider }]) => {
      render(
        <AuthProvider>
          <App />
        </AuthProvider>,
      );
    })
    .catch(renderStartupFailure);
}
