/* ============================================================
   IBC Labs — App Router
   ============================================================ */
function parseHash() {
  let h = window.location.hash.replace(/^#\/?/, "");
  return h || "home";
}

function App() {
  const [route, setRoute] = React.useState(parseHash());

  React.useEffect(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // navigate handler used by all Link components
  React.useEffect(() => {
    window.IBC.navigate = (path) => {
      if (parseHash() === path) {
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        window.location.hash = "/" + path;
      }
    };
  }, []);

  // scroll to top on route change
  React.useEffect(() => { window.scrollTo({ top: 0 }); }, [route]);

  const [top, sub] = route.split("/");
  let view;
  switch (top) {
    case "home": view = <HomePage />; break;
    case "about": view = <AboutPage />; break;
    case "research":
      view = sub ? <PaperPage key={sub} id={sub} /> : <ResearchPage />;
      break;
    case "methodologies": view = <MethodologiesPage />; break;
    case "concepts": view = <ConceptsPage />; break;
    case "problem": view = <ProblemPage />; break;
    case "notes": view = <NotesPage />; break;
    case "contact": view = <ContactPage />; break;
    default: view = <HomePage />;
  }

  return (
    <React.Fragment>
      <Navbar route={route} />
      <main key={route}>{view}</main>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
