/* global React, ReactDOM */
const { useState: useStateA, useEffect: useEffectA } = React;

const TOP = ["home", "services", "about", "sustainability", "news", "contact"];

function parseHash() {
  const h = (location.hash || "#home").replace(/^#/, "");
  if (h.startsWith("post/")) return "post:" + h.slice(5);
  return TOP.includes(h) ? h : "home";
}

function App() {
  const [page, setPage] = useStateA(parseHash);

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

  const navigate = (id) => {
    setPage(id);
    if (id.startsWith("post:")) {
      location.hash = "#post/" + id.slice(5);
    } else {
      location.hash = "#" + id;
    }
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  let content;
  if (page.startsWith("post:")) {
    content = <PostPage slug={page.slice(5)} onNavigate={navigate} />;
  } else {
    switch (page) {
      case "services": content = <ServicesPage onNavigate={navigate} />; break;
      case "about": content = <AboutPage onNavigate={navigate} />; break;
      case "sustainability": content = <SustainabilityPage onNavigate={navigate} />; break;
      case "news": content = <NewsPage onNavigate={navigate} />; break;
      case "contact": content = <ContactPage onNavigate={navigate} />; break;
      default: content = <HomePage onNavigate={navigate} />;
    }
  }

  const navPage = page.startsWith("post:") ? "news" : page;

  return (
    <div data-screen-label={page}>
      <Nav page={navPage} onNavigate={navigate} />
      {content}
      <Footer onNavigate={navigate} />
    </div>
  );
}

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