// Page components — relies on window.SITE

const { useEffect, useRef, useState } = React;

/* ---------- Reveal-on-scroll hook ---------- */
function useReveal(deps = []) {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, deps);
}

/* ---------- Home (LoveFrom-style centered intro + cycling words) ---------- */
function HomePage({ introAnim, introKey }) {
  useReveal([introKey]);

  const ref = useRef(null);
  const FULL_NAME = "Maitree Mervana Parekh";
  const [typed, setTyped] = useState("");
  const [phase, setPhase] = useState("idle"); // idle -> typing -> done
  useEffect(() => {
    setTyped("");
    setPhase("idle");
    let i = 0;
    const startDelay = setTimeout(() => {
      setPhase("typing");
      const tick = () => {
        i += 1;
        setTyped(FULL_NAME.slice(0, i));
        if (i < FULL_NAME.length) {
          // jitter for natural cadence
          const base = 70;
          const jitter = Math.random() * 60;
          timer = setTimeout(tick, base + jitter);
        } else {
          timer = setTimeout(() => setPhase("done"), 350);
        }
      };
      let timer = setTimeout(tick, 80);
      cleanup = () => clearTimeout(timer);
    }, 200);
    let cleanup = () => {};
    return () => {clearTimeout(startDelay); cleanup();};
  }, [introKey]);

  // cycling roles
  const ROLES = ["investor", "tinkerer", "creative", "optimist", "student", "curator"];
  const [roleIdx, setRoleIdx] = useState(0);
  useEffect(() => {
    if (phase !== "done") return;
    const id = setInterval(() => setRoleIdx((i) => (i + 1) % ROLES.length), 1800);
    return () => clearInterval(id);
  }, [phase]);

  // Longest role for spacer width
  const longest = ROLES.reduce((a, b) => a.length > b.length ? a : b);

  return (
    <div className="page active home-page" ref={ref} data-phase={phase}>
      {/* Hero */}
      <section className="home-hero">
        <div className="home-hero-inner">
          <h1 className="home-name">
            <span className="home-name-ghost" aria-hidden="true">{FULL_NAME}</span>
            <span className="home-name-inner">
              <span className="home-name-typed">{typed}</span><span className="home-name-caret" aria-hidden="true"></span>
            </span>
          </h1>
          <div className="home-roles">
            <span className="home-cycle" aria-live="polite">
              <span className="home-cycle-spacer" aria-hidden="true">{longest}</span>
              {ROLES.map((r, i) =>
              <span
                key={r}
                className={`home-cycle-word ${i === roleIdx ? "on" : ""}`} style={{ fontSize: "45px" }}>
                
                  {r}
                </span>
              )}
            </span>
          </div>
        </div>
        <div className="home-scroll-hint" aria-hidden="true">
          <span>scroll</span>
          <span className="home-scroll-line" />
        </div>
      </section>

      {/* Below-the-fold sections */}
      <section className="home-sec reveal">
        <div className="home-sec-label">// bio</div>
        {SITE.bio.map((p, i) => <p key={i} className="home-sec-body">{p}</p>
        )}
        <p className="home-sec-body">
          Currently investing at <a href="https://www.acrewcapital.com/team-members/maitree-mervana" target="_blank" rel="noopener">Acrew Capital</a>. I write occasionally at <a href="https://tinkeringnewsletter.substack.com/" target="_blank" rel="noopener">Tinkering</a>, a small newsletter on what I'm noticing across markets, products, and culture. More on the <a href="#/about" onClick={(e) => {e.preventDefault();location.hash = "#/about";}}>about</a> page.
        </p>
      </section>

      <section className="home-sec reveal">
        <div className="home-sec-label">// selected essays</div>
        <ul className="home-essay-list">
          {SITE.essays.map((e) =>
          <li key={e.slug}>
              <a href={`#/essay/${e.slug}`} onClick={(ev) => {ev.preventDefault();location.hash = `#/essay/${e.slug}`;}}>
                <span className="home-essay-title">{e.title}</span>
                <span className="home-essay-meta">{e.date}</span>
              </a>
            </li>
          )}
        </ul>
      </section>

      <section className="home-sec reveal">
        <div className="home-sec-label">// elsewhere</div>
        <ul className="home-elsewhere">
          {SITE.socials.map((s) =>
          <li key={s.label}>
              <a href={s.href} target="_blank" rel="noopener">{s.label}</a>
            </li>
          )}
        </ul>
      </section>
    </div>);

}

/* ---------- About ---------- */
function AboutPage() {
  useReveal();
  return (
    <div className="page active">
      <div className="page-title">// about</div>
      <div className="hero-photo" aria-label="Photo of Maitree" />
      <div className="photo-credit">photo credit // self</div>
      <div className="bio">
        {SITE.bio.map((p, i) => <p key={i}>{p}</p>)}
        <p>
          She's currently investing at <a href="https://www.acrewcapital.com/team-members/maitree-mervana" target="_blank" rel="noopener">Acrew Capital</a>, where she partners with founders at the earliest stages. Before Acrew, she's worked across product, research, and writing &mdash; threads she still pulls on today.
        </p>
        <p>
          She writes occasionally at <a href="https://tinkeringnewsletter.substack.com/" target="_blank" rel="noopener">Tinkering</a>, and builds small projects on the weekend to stay close to the craft.
        </p>
      </div>

      <div className="section-h reveal">A few things I'm thinking about</div>
      <ul className="list-arrow reveal">
        <li>The shape of agentic commerce and what it does to brand</li>
        <li>Tools that make creative work feel less lonely</li>
        <li>How small teams compound when imagination is the moat</li>
        <li>Books, mostly fiction, occasionally philosophy</li>
      </ul>

      <div className="section-h reveal">Elsewhere</div>
      <ul className="list-arrow reveal">
        {SITE.socials.map((s) =>
        <li key={s.label}>
            <a href={s.href} target="_blank" rel="noopener">{s.label}</a>
          </li>
        )}
      </ul>
    </div>);

}

/* ---------- Musings ---------- */
function MusingsPage() {
  useReveal();
  return (
    <div className="page active">
      <div className="page-title">// musings</div>
      <p style={{ color: "var(--ink-soft)", marginBottom: 28 }}>
        Notes, essays, and half-formed thoughts. Cross-posted occasionally to <a href="https://tinkeringnewsletter.substack.com/" target="_blank" rel="noopener">Tinkering</a>.
      </p>
      <ul className="essay-list">
        {SITE.essays.map((e) =>
        <li key={e.slug} className="reveal">
            <div className="essay-row">
              <div className="meta">{e.date} · {e.venue}</div>
              <div className="title">
                <a href={`#/essay/${e.slug}`} onClick={(ev) => {ev.preventDefault();location.hash = `#/essay/${e.slug}`;}}>
                  {e.title}
                </a>
              </div>
              <div className="excerpt">{e.excerpt}</div>
            </div>
          </li>
        )}
      </ul>
    </div>);

}

/* ---------- Essay reader ---------- */
function EssayPage({ slug }) {
  const essay = SITE.essays.find((e) => e.slug === slug);
  useReveal([slug]);
  useEffect(() => {window.scrollTo(0, 0);}, [slug]);
  if (!essay) return (
    <div className="page active">
      <a className="essay-back" href="#/musings" onClick={(e) => {e.preventDefault();location.hash = "#/musings";}}>back to musings</a>
      <p>Essay not found.</p>
    </div>);

  return (
    <div className="page active essay-reader">
      <a className="essay-back" href="#/musings" onClick={(e) => {e.preventDefault();location.hash = "#/musings";}}>back to musings</a>
      <h1 className="essay-h1">{essay.title}</h1>
      <div className="essay-meta">{essay.date} · {essay.venue}{essay.external ? <> · <a className="plain" href={essay.external} target="_blank" rel="noopener">read on {essay.venue}</a></> : null}</div>
      <div className="essay-body">
        {essay.body.map((b, i) => {
          if (b.type === "h2") return <h2 key={i}>{b.text}</h2>;
          if (b.type === "blockquote") return <blockquote key={i}>{b.text}</blockquote>;
          return <p key={i}>{b.text}</p>;
        })}
      </div>
    </div>);

}

/* ---------- Projects ---------- */
function ProjectsPage() {
  useReveal();
  return (
    <div className="page active">
      <div className="page-title">// projects</div>
      <p style={{ color: "var(--ink-soft)", marginBottom: 32 }}>
        A handful of small things — some shipped, some half-built. Hover to see them move.
      </p>
      <div className="proj-grid">
        {SITE.projects.map((p) =>
        <div className="proj reveal" key={p.slug}>
            <div className="proj-media">
              {p.media?.type === "image" || p.media?.type === "gif" ? (
                <img src={p.media.src} alt={p.media.alt || ""} className="proj-media-fill" />
              ) : p.media?.type === "video" ? (
                <video src={p.media.src} poster={p.media.poster} className="proj-media-fill"
                       autoPlay loop muted playsInline />
              ) : (
                <>
                  {p.anim === "pulse" && <div className="anim-pulse" />}
                  {p.anim === "grid" && <div className="anim-grid" />}
                  {p.anim === "bars" &&
                    <div className="anim-bars">
                      <span /><span /><span /><span /><span /><span /><span />
                    </div>
                  }
                  <div className="placeholder">[ gif placeholder ]</div>
                </>
              )}
            </div>
            <div className="proj-title">{p.title}</div>
            <div className="proj-desc">{p.desc}</div>
          </div>
        )}
      </div>
    </div>);

}

/* ---------- Contact ---------- */
function ContactPage() {
  useReveal();
  return (
    <div className="page active">
      <div className="page-title">// contact</div>
      <p style={{ marginBottom: 8 }}>
        The best way to reach me is by email or DM. I read everything; I reply to most things.
      </p>
      <p style={{ color: "var(--ink-soft)" }}>
        I'm always happy to hear from founders building at the edges, writers chasing a strange thread, and anyone who wants to make something together.
      </p>
      <ul className="contact-list reveal">
        {SITE.socials.map((s) =>
        <li key={s.label}>
            <span className="label">{s.label}</span>
            <a href={s.href} target="_blank" rel="noopener">{s.href.replace(/^https?:\/\//, "").replace(/\/$/, "")}</a>
          </li>
        )}
      </ul>
    </div>);

}

window.HomePage = HomePage;
window.AboutPage = AboutPage;
window.MusingsPage = MusingsPage;
window.EssayPage = EssayPage;
window.ProjectsPage = ProjectsPage;
window.ContactPage = ContactPage;