// Root app
function App() {
  const [lang, setLang] = useLang();
  const [route, setRoute] = React.useState(() => parseHash());

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

  React.useEffect(() => {
    document.body.classList.toggle("theme-dark", route.name === "about");
  }, [route.name]);

  function parseHash() {
    const h = (window.location.hash || "").replace(/^#\/?/, "");
    if (!h || h === "home") return { name: "home" };
    if (h === "about") return { name: "about" };
    if (h.startsWith("about/contact")) return { name: "about", anchor: "contact" };
    if (h.startsWith("project/")) return { name: "project", id: h.slice("project/".length) };
    // legacy: just project id
    if (PROJECTS.find((p) => p.id === h)) return { name: "project", id: h };
    return { name: "home" };
  }

  const navigate = React.useCallback((r) => {
    let hash = "#";
    if (r.name === "home") hash = "#/home";
    else if (r.name === "about") hash = r.anchor ? `#/about/${r.anchor}` : "#/about";
    else if (r.name === "project") hash = `#/project/${r.id}`;
    if (window.location.hash !== hash) {
      window.location.hash = hash;
    } else {
      // same route — force re-render of effect (e.g. scroll to contact)
      setRoute({ ...r });
    }
  }, []);

  let page = null;
  if (route.name === "home") page = <Home key="home" lang={lang} navigate={navigate} />;
  else if (route.name === "about") page = <About key={`about-${route.anchor || "top"}`} lang={lang} navigate={navigate} anchor={route.anchor} />;
  else if (route.name === "project") page = <ProjectPage key={`p-${route.id}`} lang={lang} id={route.id} navigate={navigate} />;

  return (
    <div className="app">
      <Header route={route} navigate={navigate} lang={lang} setLang={setLang} />
      {page}
      <Footer lang={lang} />
    </div>
  );
}

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