/* APP ROUTER */
const PAGES = {
  home: window.HomePage,
  about: window.AboutPage,
  plastics: window.PlasticsPage,
  metals: window.MetalsPage,
  contact: window.ContactPage,
};
const VALID = Object.keys(PAGES);
const RM_APP = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const labelFor = (id) => (NAV.find((n) => n.id === id) || {}).label || id;

function App() {
  const [loading, setLoading] = useState(true);
  const [route, setRoute] = useState(() => {
    const h = (location.hash || "").replace("#", "");
    return VALID.includes(h) ? h : "home";
  });

  const curtainRef = useRef(null);
  const labelRef = useRef(null);
  const busy = useRef(false);

  const refreshST = () => {
    const ST = window.ScrollTrigger;
    if (ST) requestAnimationFrame(() => ST.refresh());
  };

  const doSwap = (id) => {
    setRoute(id);
    if (location.hash !== "#" + id) history.pushState(null, "", "#" + id);
    window.scrollTo({ top: 0, behavior: "auto" });
    setTimeout(refreshST, 80);
  };

  const transition = (id) => {
    const G = window.gsap;
    if (!G || RM_APP) { doSwap(id); return; }
    if (busy.current) return;
    busy.current = true;
    const panels = curtainRef.current.querySelectorAll(".curtain__panel");
    const lab = labelRef.current;
    lab.textContent = labelFor(id);
    const tl = G.timeline({ onComplete: () => { busy.current = false; } });
    tl.set(panels, { yPercent: 100 })
      .set(lab, { opacity: 0 })
      // PHASE 1 — cover the screen; swap content only once fully black
      .to(panels, {
        yPercent: 0, duration: 0.5, ease: "power4.inOut", stagger: 0.045,
        onComplete: () => doSwap(id),
      })
      .to(lab, { opacity: 1, duration: 0.2 }, ">-0.12")
      .to(lab, { opacity: 0, duration: 0.2 }, ">0.18")
      // PHASE 2 — reveal the freshly-swapped page
      .to(panels, { yPercent: -100, duration: 0.55, ease: "power4.inOut", stagger: 0.045 }, ">-0.04")
      .set(panels, { yPercent: 100 });
  };

  const go = (id) => {
    if (!VALID.includes(id)) id = "home";
    if (id === route) { window.scrollTo({ top: 0, behavior: "smooth" }); return; }
    doSwap(id);
  };

  useEffect(() => {
    const onPop = () => {
      const h = (location.hash || "").replace("#", "");
      const id = VALID.includes(h) ? h : "home";
      setRoute(id);
      window.scrollTo({ top: 0, behavior: "auto" });
      setTimeout(refreshST, 80);
    };
    window.addEventListener("popstate", onPop);
    window.addEventListener("hashchange", onPop);
    window.addEventListener("load", refreshST);
    return () => { window.removeEventListener("popstate", onPop); window.removeEventListener("hashchange", onPop); window.removeEventListener("load", refreshST); };
  }, [route]);

  const Page = PAGES[route] || PAGES.home;
  return (
    <>
      {loading && <Preloader onDone={() => { setLoading(false); setTimeout(refreshST, 120); }} />}
      <Cursor />
      <Grain />
      <ScrollBar />
      <Nav route={route} go={go} />
      <Page key={route} go={go} />
      {route !== "contact" && <Footer go={go} />}

      <div className="curtain" ref={curtainRef} aria-hidden="true">
        {Array.from({ length: 6 }).map((_, i) => <div className="curtain__panel" key={i} />)}
      </div>
      <div className="curtain__label" ref={labelRef} aria-hidden="true" />
    </>
  );
}

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