/* global React, ReactDOM,
   Header, Footer, HomePage, ResidencesPage, AmenitiesPage,
   GalleryPage, LocationPage, ContactPage, PreferredEmployerPage,
   PrivacyPage, TermsPage,
   ScheduleTourModal, ApplyNowModal */

const {
  useState: useStateApp,
  useEffect: useEffectApp,
  useLayoutEffect: useLayoutEffectApp,
  useRef: useRefApp,
} = React;

// Production tweak defaults (Tweaks panel is a designer-only A/B tool, not shipped).
const TWEAKS = {
  heroVariant: "fullbleed",
  colorTheme: "cream",
  headlineIdx: 0,
  density: "spacious",
  preLeasing: true,
};

const VALID_PAGES = ["home", "residences", "amenities", "gallery", "location", "contact", "employer", "privacy", "terms"];

function App() {
  const initialPage = (window.location.hash || "#home").replace("#", "");
  const [page, setPage] = useStateApp(VALID_PAGES.includes(initialPage) ? initialPage : "home");
  const [routePhase, setRoutePhase] = useStateApp("route-ready");
  const [tourOpen, setTourOpen] = useStateApp(false);
  const [applyOpen, setApplyOpen] = useStateApp(false);
  const pageRef = useRefApp(page);
  const routeTimerRef = useRefApp(null);
  const routeBusyRef = useRefApp(false);

  const transitionTo = (id, updateHistory = false) => {
    if (!VALID_PAGES.includes(id)) return;
    if (id === pageRef.current && !routeBusyRef.current) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    window.clearTimeout(routeTimerRef.current);
    routeBusyRef.current = true;
    setRoutePhase("route-leaving");
    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    routeTimerRef.current = window.setTimeout(() => {
      pageRef.current = id;
      setPage(id);
      setRoutePhase("route-entering");
      if (updateHistory) window.history.pushState(null, "", `#${id}`);
      window.scrollTo({ top: 0, behavior: "instant" });
      window.requestAnimationFrame(() => {
        window.requestAnimationFrame(() => {
          routeBusyRef.current = false;
          setRoutePhase("route-ready");
        });
      });
    }, reduceMotion ? 0 : 180);
  };

  const navTo = (id) => transitionTo(id, true);

  useEffectApp(() => {
    const onHash = () => {
      const p = (window.location.hash || "#home").replace("#", "");
      if (VALID_PAGES.includes(p)) transitionTo(p, false);
    };
    window.addEventListener("popstate", onHash);
    window.addEventListener("hashchange", onHash);
    return () => {
      window.clearTimeout(routeTimerRef.current);
      window.removeEventListener("popstate", onHash);
      window.removeEventListener("hashchange", onHash);
    };
  }, []);

  useEffectApp(() => {
    document.body.dataset.density = TWEAKS.density;
  }, []);

  useLayoutEffectApp(() => {
    const root = document.querySelector(".route-view");
    if (!root) return undefined;

    const selectors = [
      ".section-head",
      ".card-grid > *",
      ".intro-grid > *",
      ".contact-grid > *",
      ".map-grid > *",
      ".amenity",
      ".policy-body > *",
      ".waitlist-band .shell > *",
    ].join(",");
    const elements = [...root.querySelectorAll(selectors)];
    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    elements.forEach((element, index) => {
      element.classList.add("reveal-item");
      element.style.setProperty("--reveal-order", index % 6);
    });

    if (reduceMotion || !("IntersectionObserver" in window)) {
      elements.forEach((element) => element.classList.add("is-visible"));
      return undefined;
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        entry.target.classList.add("is-visible");
        observer.unobserve(entry.target);
      });
    }, { threshold: 0.08, rootMargin: "0px 0px -6%" });

    elements.forEach((element) => observer.observe(element));
    return () => observer.disconnect();
  }, [page]);

  const openTour = () => setTourOpen(true);
  const openApply = () => setApplyOpen(true);

  return (
    <>
      <Header
        page={page}
        navTo={navTo}
        openTour={openTour}
        showPreLeasing={TWEAKS.preLeasing} />

      <div className={`route-view ${routePhase}`}>
        {page === "home" && (
          <HomePage tweaks={TWEAKS} openTour={openTour} openApply={openApply} navTo={navTo} />
        )}
        {page === "residences" && (
          <ResidencesPage openTour={openTour} openApply={openApply} />
        )}
        {page === "amenities" && (
          <AmenitiesPage openTour={openTour} navTo={navTo} />
        )}
        {page === "gallery" && (
          <GalleryPage />
        )}
        {page === "location" && (
          <LocationPage navTo={navTo} openTour={openTour} />
        )}
        {page === "contact" && (
          <ContactPage openTour={openTour} openApply={openApply} navTo={navTo} />
        )}
        {page === "employer" && (
          <PreferredEmployerPage navTo={navTo} openTour={openTour} />
        )}
        {page === "privacy" && <PrivacyPage />}
        {page === "terms" && <TermsPage />}
      </div>

      <Footer navTo={navTo} />
      <LeasingChat hidden={tourOpen || applyOpen} />

      <ScheduleTourModal open={tourOpen} onClose={() => setTourOpen(false)} />
      <ApplyNowModal open={applyOpen} onClose={() => setApplyOpen(false)} />
    </>
  );
}

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