/* Home — image-forward hero + project grid + dark statement band */

function HeroInner({ go, current, emColor, emText }) {
  return (
    <div className="hero-inner shell-wide">
      <p className="hero-kicker label">{DATA.meta.name} — {DATA.meta.role}</p>
      <h1 className="hero-statement">
        What if you start at the <em style={emColor ? { color: emColor } : undefined}>{emText || "feeling"}</em>, and build backwards?
      </h1>
      <div className="hero-bottom">
        <span className="hero-cue">Selected work <span className="arrow">↓</span></span>
        {current && (
          <span className="hero-project-link" key={current.id} onClick={() => go({ name: "project", id: current.id })}>
            {current.title} <span className="hpl-arrow">→</span>
          </span>
        )}
      </div>
    </div>
  );
}

function HeroSlideshow({ go, navH }) {
  // heroSlides entries can be plain id strings or { id, emColor } objects
  const slideList = (DATA.meta.heroSlides || [])
    .map((entry) => {
      const id       = typeof entry === "string" ? entry : entry.id;
      const emColor  = typeof entry === "object" ? (entry.emColor || null) : null;
      const emText   = typeof entry === "object" ? (entry.emText  || null) : null;
      const project  = DATA.projects.find((p) => p.id === id);
      return project ? { project, emColor, emText } : null;
    })
    .filter(Boolean);

  const interval = DATA.meta.heroInterval || 5000;
  const [idx,     setIdx]     = useState(0);
  const [emColor, setEmColor] = useState(() => slideList[0]?.emColor || null);
  const [emText,  setEmText]  = useState(null);
  const firstRun = useRef(true);

  // On first mount leave emText/emColor null so the hardcoded defaults show.
  // After every real slide change, pull the values from the incoming slide.
  useEffect(() => {
    if (firstRun.current) { firstRun.current = false; return; }
    const entry = slideList[idx];
    if (entry) {
      setEmColor(entry.emColor || null);
      setEmText(entry.emText  || null);
    }
  }, [idx]);

  // auto-advance; resets the countdown after any change (incl. manual nav)
  useEffect(() => {
    if (slideList.length <= 1) return;
    const t = setTimeout(() => setIdx((i) => (i + 1) % slideList.length), interval);
    return () => clearTimeout(t);
  }, [idx, slideList.length, interval]);

  const prev    = () => setIdx((i) => (i - 1 + slideList.length) % slideList.length);
  const fwd     = () => setIdx((i) => (i + 1) % slideList.length);
  const current = slideList[idx]?.project || null;

  return (
    <header className="hero" style={{ marginTop: `-${navH}px` }}>
      <div className="hero-media">
        {slideList.length === 0 && <Placeholder dark aspect="" label="Header image — add ids to meta.heroSlides" />}
        {slideList.map(({ project: s }, i) => (
          <div key={s.id} className={"hero-slide" + (i === idx ? " active" : "")} aria-hidden={i !== idx}>
            <div className="ph dark hero-ph">
              {s.coverSrc
                ? <img src={s.coverSrc} srcSet={s.coverSrcset || undefined} sizes={s.coverSizes || undefined} alt={s.title} className="ph-img" loading={i === 0 ? "eager" : "lazy"} />
                : <span className="hero-ph-name">{s.title}</span>
              }
              {!s.coverSrc && <span className="ph-label hero-ph-hint">Header image — drop a photograph for {s.title}</span>}
            </div>
          </div>
        ))}
      </div>
      <div className="hero-scrim" />

      {slideList.length > 1 && (
        <React.Fragment>
          <div className="hero-nav-zone left" onClick={prev} role="button" aria-label="Previous project">
            <span className="hero-arrow">←</span>
          </div>
          <div className="hero-nav-zone right" onClick={fwd} role="button" aria-label="Next project">
            <span className="hero-arrow">→</span>
          </div>
        </React.Fragment>
      )}

      <HeroInner go={go} current={current} emColor={emColor} emText={emText} />
    </header>
  );
}

function ProjectCard({ p, feature, go }) {
  return (
    <article className={"card" + (feature ? " feature" : "")} onClick={() => go({ name: "project", id: p.id })}>
      <div className="card-media">
        <span className="card-index">{p.idx}</span>
        <Placeholder
          aspect={feature ? "aspect-3-2" : "aspect-4-3"}
          kind={p.tags.includes("software") ? "video" : "image"}
          label={p.cover}
          src={p.coverSrc || null}
          srcset={p.coverSrcset || null}
          sizes={p.coverSizes || null}
        />
      </div>
      <div className="card-meta">
        <span className="card-disc label label-sm">{disciplineLabel(p.tags)}</span>
        <h3 className="card-title">{p.title} <span className="yr">{p.year}</span></h3>
        {feature && <p className="card-summary">{p.standfirst}</p>}
        {!feature && <p className="card-summary">{p.summary}</p>}
        <span className="card-open">View project →</span>
      </div>
    </article>
  );
}

function Home({ go }) {
  const [navH, setNavH] = useState(68);
  const reveal = useReveal();

  // Measure the nav so the hero can be pulled up behind it.
  // Hero height itself is handled in CSS (dvh) to survive mobile address-bar resize.
  useEffect(() => {
    const compute = () => {
      const nav = document.querySelector('.nav');
      setNavH(nav ? nav.getBoundingClientRect().height : 68);
    };
    compute();
    window.addEventListener('resize', compute);
    return () => window.removeEventListener('resize', compute);
  }, []);

  const projects = DATA.projects;
  const feature  = projects[0];
  const rest     = projects.slice(1);

  return (
    <div className="view" ref={reveal}>

      {/* ---------- Image-forward hero slideshow ---------- */}
      <HeroSlideshow go={go} navH={navH} />

      {/* ---------- Work ---------- */}
      <section className="work shell-wide">
        <div className="work-head">
          <div>
            <span className="label" style={{ whiteSpace: "nowrap" }}>Selected work — {projects.length} projects</span>
            <h2>Spatial, experiential, and narrative design.</h2>
          </div>
        </div>

        <div className="grid">
          {feature && <ProjectCard p={feature} feature go={go} />}
          {rest.map((p) => <ProjectCard key={p.id} p={p} go={go} />)}
        </div>
      </section>

      {/* ---------- Dark statement band ---------- */}
      <section className="band reveal">
        <div className="band-inner shell-wide">
          <div>
            <span className="label">On method</span>
            <p className="band-quote">Every project here is the same move in a different material: name the <em>feeling</em> first, then build the conditions that make it inevitable.</p>
          </div>
          <span className="band-link" onClick={() => go({ name: "manifesto" })}>Read how I think →</span>
        </div>
      </section>

      <Footer go={go} />
    </div>
  );
}

window.Home = Home;
