/* global React, ReactDOM, PROJECTS, ALL_PROJECTS,
          TopBar, Hero, Projects, Skills, Experience, Contact, Footer,
          ProjectPage,
          useInView, Reveal, SectionHead, Tag, Stamp, Cursor, Label,
          NameTitle, Uptime, CursorTrail, FaultyTerminal */

const { useState, useEffect } = React;

// ─── Hash router helpers ───────────────────────────────────────────────────
// Routes:
//   #/                  → index (all sections)
//   #/projects/:slug    → project page

function getRoute() {
  const hash = window.location.hash.replace(/^#/, "") || "/";
  const m = hash.match(/^\/projects\/(.+)$/);
  if (m) return { page: "project", slug: m[1] };
  return { page: "index" };
}

function navigate(path) {
  window.location.hash = path;
}

// ============================================================
// APP — root + hash routing
// ============================================================
function App() {
  const [route, setRoute] = useState(getRoute);
  const [active, setActive] = useState("identity");

  useEffect(() => {
    const onHash = () => setRoute(getRoute());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffect(() => {
    if (route.page !== "index") return;
    const ids = ["identity", "work", "skills", "experience", "contact"];
    const obs = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); }),
      { rootMargin: "-40% 0px -55% 0px", threshold: 0 }
    );
    ids.forEach((id) => { const el = document.getElementById(id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, [route.page]);

  useEffect(() => {
    if (route.page === "project") window.scrollTo(0, 0);
  }, [route.page, route.slug]);

  // ── Project page ──────────────────────────────────────────
  if (route.page === "project") {
    const project = ALL_PROJECTS.find((p) => p.slug === route.slug);
    if (!project) {
      return (
        <div>
          <TopBar active={null} onNavigate={() => navigate("/")} />
          <section style={{ padding: "120px 64px" }}>
            <p style={{ color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
              Project not found: <code>{route.slug}</code>
            </p>
          </section>
        </div>
      );
    }
    return (
      <div>
        <TopBar active={null} onNavigate={() => navigate("/")} />
        <ProjectPage
          project={project}
          onClose={() => navigate("/")}
          onNav={(slug) => navigate(`/projects/${slug}`)}
        />
      </div>
    );
  }

  // ── Index page ────────────────────────────────────────────
  return (
    <div>
      <TopBar active={active} onNavigate={(id) => { navigate("/"); setTimeout(() => { const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: "smooth" }); }, 80); }} />
      <Hero />
      <Projects onOpenProject={(p) => navigate(`/projects/${p.slug}`)} />
      <Skills />
      <Experience />
      <Contact />
      <Footer />
    </div>
  );
}

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