/* global React, ReactDOM, PORTFOLIO, Nav, Intro, Home, ProjectDetail, Cursor */

const { useState, useEffect, useCallback } = React;

function App({ initialRoute = "intro" }) {
  const [route, setRoute] = useState(initialRoute);
  const [scrollAnchor, setScrollAnchor] = useState(null);
  const [activeSection, setActiveSection] = useState("projects");
  const [mask, setMask] = useState(null);

  useEffect(() => {
    if (route !== "home") return;
    const ids = ["projects", "experience", "about", "contact"];
    const els = ids.map((id) => document.getElementById(id)).filter(Boolean);
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActiveSection(e.target.id);
        });
      },
      { rootMargin: "-40% 0px -55% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [route]);

  const navigate = useCallback((nextRoute, anchor = null) => {
    if (route === nextRoute && !anchor) return;
    setMask("in");
    setTimeout(() => {
      setRoute(nextRoute);
      setScrollAnchor(anchor);
      window.scrollTo({ top: 0, behavior: "instant" });
      setMask("out");
      setTimeout(() => setMask(null), 480);
    }, 380);
  }, [route]);

  const enterFromIntro = useCallback(() => setRoute("home"), []);
  const openProject = useCallback((id) => navigate(`project:${id}`), [navigate]);
  const goHome = useCallback((anchor = null) => navigate("home", anchor), [navigate]);

  let body;
  if (route === "intro") {
    body = <Intro onEnter={enterFromIntro} />;
  } else if (route.startsWith("project:")) {
    const id = route.split(":")[1];
    body = (
      <>
        <Nav active={null} onNav={goHome} current={route} />
        <ProjectDetail id={id} onBack={() => goHome("projects")} />
      </>
    );
  } else {
    body = (
      <>
        <Nav active={activeSection} current="home" />
        <Home onOpenProject={openProject} scrollAnchor={scrollAnchor} />
      </>
    );
  }

  return (
    <>
      <AsciiBackground opacity={0.08} cell={14} scale={0.045} drift={0.035} bias={0.54} contrast={1.8} />
      {body}
      {mask ? <div className={`route-mask is-${mask}`} /> : null}
      <Cursor />
    </>
  );
}

Object.assign(window, { App });
