/* JAM — App router & glue */

const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  const [hash, setHash] = useStateApp(() => window.location.hash.replace(/^#\/?/, "") || "");
  const [locale, setLocale] = useStateApp("EN");

  useEffectApp(() => {
    const onHash = () => {
      setHash(window.location.hash.replace(/^#\/?/, "") || "");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const goto = (route) => {
    window.location.hash = "#/" + (route || "");
  };

  const openWedding = (id) => {
    window.location.hash = "#/real-weddings/" + id;
  };

  // Parse route
  const [primary, sub] = hash.split("/");
  const route = primary || "";

  let view;
  if (route === "" || route === "home") {
    view = <HomePage setRoute={goto} openWedding={openWedding} />;
  } else if (route === "real-weddings" && sub) {
    view = <CaseStudyPage weddingId={sub} setRoute={goto} openWedding={openWedding} />;
  } else if (route === "real-weddings") {
    view = <RealWeddingsPage setRoute={goto} openWedding={openWedding} />;
  } else if (route === "services") {
    view = <ServicesPage setRoute={goto} />;
  } else if (route === "venues") {
    view = <VenuesPage setRoute={goto} />;
  } else if (route === "about") {
    view = <AboutPage setRoute={goto} />;
  } else if (route === "testimonials") {
    view = <TestimonialsPage setRoute={goto} />;
  } else if (route === "contact") {
    view = <ContactPage setRoute={goto} />;
  } else {
    view = <HomePage setRoute={goto} openWedding={openWedding} />;
  }

  return (
    <React.Fragment>
      <Nav route={route} setRoute={goto} locale={locale} setLocale={setLocale} />
      <main>{view}</main>
      <Footer setRoute={goto} />
      <WhatsAppFAB />
    </React.Fragment>
  );
}

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