// Root app — routing state + page mounting
const { useState: useStateApp, useEffect: useEffectApp } = React;

const App = () => {
  // Route: { name: "home" | "curriculum" | ... | "branch", branchId?: string }
  const [route, setRoute] = useStateApp({ name: "home" });
  const [locale, setLocale] = useStateApp("EN");
  const [tour, setTour] = useStateApp({ open: false, branch: "" });

  // Scroll to top on route change
  useEffectApp(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route]);

  const navigate = (name, branchId) => {
    if (name === "branch") setRoute({ name: "branch", branchId: branchId });
    else setRoute({ name });
  };

  const onBookTour = (presetBranch) => {
    setTour({ open: true, branch: typeof presetBranch === "string" ? presetBranch : "" });
  };
  const closeTour = () => setTour({ open: false, branch: "" });

  let page = null;
  switch (route.name) {
    case "home":        page = <HomePage navigate={navigate} onBookTour={onBookTour} />; break;
    case "curriculum":  page = <CurriculumPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "programmes":  page = <ProgrammesPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "facilities":  page = <FacilitiesPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "branches":    page = <BranchesPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "branch":      page = <BranchDetail branchId={route.branchId} navigate={navigate} onBookTour={onBookTour} />; break;
    case "admissions":  page = <AdmissionsPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "about":       page = <AboutPage navigate={navigate} onBookTour={onBookTour} />; break;
    case "contact":     page = <ContactPage navigate={navigate} onBookTour={onBookTour} />; break;
    default:            page = <HomePage navigate={navigate} onBookTour={onBookTour} />;
  }

  const navName = route.name === "branch" ? "branches" : route.name;

  return (
    <>
      <Nav route={navName} navigate={navigate} locale={locale} setLocale={setLocale} onBookTour={() => onBookTour()} />
      <main>{page}</main>
      <Footer navigate={navigate} />
      <Fab />
      <MobileCta onBookTour={() => onBookTour()} />
      <Modal open={tour.open} onClose={closeTour}>
        <TourForm onClose={closeTour} presetBranch={tour.branch} />
      </Modal>
    </>
  );
};

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