/* global React, ReactDOM, Nav, Footer, ScheduleModal, HomePage, ServiciosPage, ServicioDetail, RedPage, PlanesPage, PublicarPage, TrabajaPage, ContactoPage, LegalPage, NotFound */
const { useState, useEffect } = React;

function useHistoryRoute() {
  const get = () => window.location.pathname || "/";
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const onPop = () => {
      setRoute(get());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);
  const navigate = (path) => {
    window.history.pushState(null, "", path);
    setRoute(path);
    window.scrollTo({ top: 0, behavior: "instant" });
  };
  return [route, navigate];
}

function App() {
  const [route, navigate] = useHistoryRoute();
  const [scheduleOpen, setScheduleOpen] = useState(false);
  const openSchedule = () => setScheduleOpen(true);

  let page;
  if (route === "/" || route === "") page = <HomePage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/servicios") page = <ServiciosPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route.startsWith("/servicios/")) {
    const slug = route.replace("/servicios/", "");
    page = <ServicioDetail slug={slug} navigate={navigate} openSchedule={openSchedule} />;
  }
  else if (route === "/red") page = <RedPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/planes") page = <PlanesPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/publicar" || route.startsWith("/publicar/")) page = <PublicarPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/trabaja-con-nosotros") page = <TrabajaPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/contacto") page = <ContactoPage navigate={navigate} openSchedule={openSchedule} />;
  else if (route === "/aviso-legal") page = <LegalPage kind="aviso-legal" navigate={navigate} />;
  else if (route === "/privacidad") page = <LegalPage kind="privacidad" navigate={navigate} />;
  else if (route === "/cookies") page = <LegalPage kind="cookies" navigate={navigate} />;
  else page = <NotFound navigate={navigate} />;

  return (
    <React.Fragment>
      <Nav route={route} navigate={navigate} openSchedule={openSchedule} />
      {page}
      <Footer navigate={navigate} openSchedule={openSchedule} />
      <ScheduleModal open={scheduleOpen} onClose={() => setScheduleOpen(false)} />
    </React.Fragment>
  );
}

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