/* App — client router tying the marketing screens together.
   "Book a visit" opens the clinic's online booking system in a new tab. */
function App() {
  const [route, setRoute] = React.useState("home");
  const mainRef = React.useRef(null);

  const onNav = (to) => { setRoute(to); window.scrollTo(0, 0); };
  const onBook = () => { window.open("https://qstk9.healthquest.ca:3000/onlinebooking", "_blank", "noopener,noreferrer"); };

  // Soft fade-up on every route change, replayed by forcing a reflow.
  React.useEffect(() => {
    const el = mainRef.current;
    if (!el) return;
    el.classList.remove("tmc-page-enter");
    void el.offsetWidth;
    el.classList.add("tmc-page-enter");
  }, [route]);

  // Lets plain-JS UI outside React (the cookie consent banner) route
  // to a page without a full navigation.
  React.useEffect(() => {
    const handler = (e) => { if (e.detail) onNav(e.detail); };
    window.addEventListener("tmc:navigate", handler);
    return () => window.removeEventListener("tmc:navigate", handler);
  }, []);

  // Header gains a soft shadow once the page scrolls under it.
  React.useEffect(() => {
    const header = document.querySelector(".tmc-site-header");
    if (!header) return;
    const onScroll = () => header.classList.toggle("tmc-header-scrolled", window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Reveal each page section as it enters the viewport.
  React.useEffect(() => {
    const sections = mainRef.current ? mainRef.current.querySelectorAll("section") : [];
    if (!sections.length) return;
    if (!("IntersectionObserver" in window)) {
      sections.forEach((s) => s.classList.add("is-visible"));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-visible");
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -60px 0px" });
    sections.forEach((s) => { s.classList.add("tmc-reveal"); io.observe(s); });
    return () => io.disconnect();
  }, [route]);

  const Screen =
    route === "about" ? window.AboutUs :
    route === "services" ? window.Services :
    route === "specialties" ? window.Specialties :
    route === "contact" ? window.Contact :
    route === "terms" ? window.TermsAndConditions :
    route === "privacy" ? window.PrivacyPolicy :
    window.Home;

  return (
    <div>
      <window.SiteHeader route={route} onNav={onNav} onBook={onBook} />
      <div ref={mainRef}>
        <Screen onNav={onNav} onBook={onBook} />
      </div>
      <window.SiteFooter onNav={onNav} onBook={onBook} />
    </div>
  );
}

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