// Entry point: loads the styles, applies the saved preferences, mounts the shell inside the data provider. The
// component states page (`?mode=sample&state=<component>.<state>` or `?state=components`) is a dev and test tool: it
// mounts only in dev or in a build made with VITE_STATE_PAGES=1 (QA's production-build checks), never in a plain
// production build, so it can't ship (self-check item 24).
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles/tokens.css";
import "./styles/fonts.css";
import "./styles/fonts-fallback.css";
import "./styles/base.css";
import { App } from "./app/App";
import { DataProvider } from "./data/DataProvider";
import { prepareRuntime } from "./data/prepare-runtime";
import { getParams, markMode } from "./app/modes";
import { initPreferences } from "./app/theme";
import { applyTextSize } from "./app/text-size";
import { reviewStep } from "./app/review-steps";
import { positionsReview } from "./app/positions-review";

markMode(getParams());
initPreferences();
// D-2 and D-4 before the first paint: the reader's text size (or MS-24's 200 %), and MS-25's right to left
{
  const ui = getParams().mode === "sample" ? reviewStep(getParams().state)?.ui : undefined;
  applyTextSize(ui?.text200 ? 2 : null);
  const positions = getParams().mode === "sample" ? positionsReview(getParams().state)?.ui : undefined;
  if (ui?.rtl || positions?.rtl) document.documentElement.setAttribute("dir", "rtl");
}

const root = document.getElementById("root");
if (!root) throw new Error("index.html has no #root");
const { mode, state } = getParams();
// Whether this build may show the dev and test pages (statically false in a plain production build, so they drop out).
const statePages = import.meta.env.DEV || import.meta.env.VITE_STATE_PAGES === "1";
if (statePages && state?.startsWith("chart.") && (import.meta.env.DEV || mode === "sample")) {
  // `?state=chart.<name>` shows the chart alone (Section 6 dev page). A QA build (VITE_STATE_PAGES=1) allows it in Sample only:
  // on Demo the page's test hooks could place and close real demo trades
  void import("./screens/chart-states/mount").then((m) => m.mountChartStates(root));
} else if (statePages && mode === "sample" && state !== null && (state === "components" || state.includes("."))) {
  void import("./screens/states/mount").then((m) => m.mountStatesPage(root, state));
} else {
  // the first paint already knows the feed's status (the demo pill's words never change after it shows, QA MF-S7-4)
  void prepareRuntime().then((runtime) =>
    createRoot(root).render(
      <StrictMode>
        <DataProvider runtime={runtime}>
          <App />
        </DataProvider>
      </StrictMode>,
    ),
  );
}
