import React from "react";
import { hydrateRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import { RootApp } from "./ui/App.js";
import type { ViewContext } from "./types.js";

declare global {
  interface Window {
    __CSD_VIEW_CONTEXT__?: ViewContext;
  }
}

const context = window.__CSD_VIEW_CONTEXT__;
if (!context) {
  throw new Error("Missing CS Dashboard hydration context");
}

function HydrationReady({ children }: { children: React.ReactNode }) {
  React.useEffect(() => {
    document.getElementById("root")?.setAttribute("data-hydrated", "true");
  }, []);
  return children;
}

hydrateRoot(
  document.getElementById("root") as HTMLElement,
  <HydrationReady>
    <BrowserRouter>
      <RootApp context={context} />
    </BrowserRouter>
  </HydrationReady>,
);
