/* global React, ReactDOM, Nav, Footer, ContactModal, CookieBanner, HomePage, AboutPage, ConsultancyPage, CoachingPage, PartnersPage, DiagnosticPage, PrivacyPage */
const { useState, useEffect } = React;

const ROUTES = ["home", "about", "consultancy", "coaching", "partners", "diagnostic", "privacy"];
const ROUTE_LABELS = {
  home: "People Cake",
  about: "About",
  consultancy: "HR Consultancy",
  coaching: "Career Coaching",
  partners: "Partners",
  diagnostic: "Team Diagnostic",
  privacy: "Privacy Policy"
};

function App() {
  const [route, setRoute] = useState(() => {
    const h = window.location.hash.replace("#", "");
    return ROUTES.includes(h) ? h : "home";
  });
  const [contactOpen, setContactOpen] = useState(false);
  const [modalAccent, setModalAccent] = useState("purple");

  const navigate = (id) => {
    if (!ROUTES.includes(id)) return;
    setRoute(id);
    window.location.hash = id;
    window.scrollTo({ top: 0, behavior: "instant" });
    document.title = `${ROUTE_LABELS[id]} · People Cake`;
  };

  const openContact = (accent = "purple") => {
    setModalAccent(typeof accent === "string" ? accent : "purple");
    setContactOpen(true);
  };

  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace("#", "");
      if (ROUTES.includes(h) && h !== route) setRoute(h);
    };
    window.addEventListener("hashchange", onHash);
    document.title = `${ROUTE_LABELS[route]} · People Cake`;
    return () => window.removeEventListener("hashchange", onHash);
  }, [route]);

  const pageProps = { navigate, onCTA: () => openContact(route === "coaching" ? "violet" : "purple") };

  let Page;
  switch (route) {
    case "about": Page = AboutPage; break;
    case "consultancy": Page = ConsultancyPage; break;
    case "coaching": Page = CoachingPage; break;
    case "partners": Page = PartnersPage; break;
    case "diagnostic": Page = DiagnosticPage; break;
    case "privacy": Page = PrivacyPage; break;
    default: Page = HomePage;
  }

  return (
    <React.Fragment>
      <Nav route={route} navigate={navigate} onCTA={() => openContact()}/>
      <main key={route} data-screen-label={ROUTE_LABELS[route]}>
        <Page {...pageProps}/>
      </main>
      <Footer navigate={navigate} onCTA={() => openContact()}/>
      <ContactModal open={contactOpen} onClose={() => setContactOpen(false)} accent={modalAccent}/>
      <CookieBanner navigate={navigate}/>
    </React.Fragment>
  );
}

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