// pages-project-detail.jsx

function ProjectDetailPage({ slug, go }) {
  const collections = [
    { list: window.PROJECTS, key: "released" },
    { list: window.UPCOMING.map(p => ({ ...p, title: p.titleDisplay, logline: p.action })), key: "upcoming" },
    { list: window.LIVE_EVENTS || [], key: "live-events" }
  ];
  let found = null;
  for (const c of collections) {
    const idx = c.list.findIndex(p => p.slug === slug);
    if (idx !== -1) { found = { list: c.list, idx }; break; }
  }
  if (!found) {
    return (
      <main className="page shell" data-screen-label="04 Project · Not Found">
        <div className="pd-not-found">
          <div className="eg-label">Not Found</div>
          <h1 className="eg-display pd-not-found-title">No such project.</h1>
          <a className="eg-label pd-not-found-back" onClick={() => go("work")}>← Back to slate</a>
        </div>
      </main>
    );
  }
  const { list, idx } = found;
  const p = list[idx];
  const hasSiblings = list.length > 1;
  const prev = hasSiblings ? list[(idx - 1 + list.length) % list.length] : null;
  const next = hasSiblings ? list[(idx + 1) % list.length] : null;

  return <ProjectDetailPinned p={p} idx={idx} prev={prev} next={next} go={go} />;
}

Object.assign(window, { ProjectDetailPage });

function ProjectDetailPinned({ p, idx, prev, next, go }) {
  const [heroFailed, setHeroFailed] = React.useState(false);
  const [posterFailed, setPosterFailed] = React.useState(false);
  React.useEffect(() => { setHeroFailed(false); setPosterFailed(false); }, [p.slug]);
  const useLandscape = !!p.heroImage && !heroFailed;
  const heroSrc = useLandscape ? p.heroImage : (posterFailed ? null : p.poster);
  const isPortraitFallback = !useLandscape && !!heroSrc;
  const wrapRef = React.useRef(null);
  const scrimRef = React.useRef(null);
  const imgRef = React.useRef(null);
  const contentRef = React.useRef(null);

  React.useEffect(() => {
    const onScroll = () => {
      const progress = Math.min(1, window.scrollY / 500);
      if (scrimRef.current) scrimRef.current.style.opacity = 0.4 * progress;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  React.useEffect(() => {
    const els = contentRef.current ? Array.from(contentRef.current.querySelectorAll(".pd-reveal")) : [];
    const check = () => {
      els.forEach(el => {
        if (el.classList.contains("is-in")) return;
        const rect = el.getBoundingClientRect();
        if (rect.top < window.innerHeight * 0.92) el.classList.add("is-in");
      });
    };
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check);
    check();
    return () => { window.removeEventListener("scroll", check); window.removeEventListener("resize", check); };
  }, []);

  return (
    <main className="page pd-pin" data-screen-label={"04 Project · " + p.title}>
      <div className="pd-pin-hero" style={isPortraitFallback ? { height: "calc(100dvh - 72px)" } : { aspectRatio: "1720/960" }}>
        {heroSrc ? (
          <React.Fragment>
            <div className="pd-pin-placeholder">
              <div className="stripes"></div>
              <div className="placeholder"><span>{p.title.toUpperCase() + " · KEY ART"}</span></div>
            </div>
          <img className="pd-pin-img" key={heroSrc} ref={imgRef} src={heroSrc} alt={p.title + " key art"}
            width="1720" height="960" fetchPriority="high" decoding="async"
            onError={() => { if (useLandscape) setHeroFailed(true); else setPosterFailed(true); }}
            style={isPortraitFallback ? { objectFit: "contain" } : undefined} />
          </React.Fragment>
        ) : (
          <div className="pd-pin-placeholder">
            <div className="stripes"></div>
            <div className="placeholder">{p.title} · KEY ART · TO BE PROVIDED</div>
          </div>
        )}
        <div className="pd-pin-scrim" ref={scrimRef}></div>
      </div>
      <div className="pd-pin-spacer" style={isPortraitFallback ? { height: "calc(100dvh - 72px)" } : { aspectRatio: "1720/960" }}></div>

      <div className="pd-pin-content shell" ref={contentRef}>
        <h1 className="pd-reveal">{p.titleStyle === "italic" ? <em>{p.title}</em> : p.title}</h1>
        {p.slug === "jerry-garcia-experience" && (
          <a className="proj-filter proj-ticket-btn pd-reveal" href="https://eyesofthe.world/" target="_blank" rel="noopener noreferrer">Get Ticket Alerts</a>
        )}

        <div className="pd-body pd-reveal pd-body--stacked">
          <div>
            <div className="eg-label pd-about-label">About</div>
            <p className="logline pd-about-copy">{p.logline}</p>
          </div>
          <div className="sticky-meta">
            <dl className="pd-dl">
              <dt>Release Year</dt><dd>{p.year}</dd>
            </dl>
            {(p.director || p.writer || p.cast) && (
              <React.Fragment>
                <div className="eg-label pd-credits-label">Credits</div>
                <dl className="pd-dl">
                  {p.director && <><dt>Director</dt><dd>{p.director}</dd></>}
                  {p.writer && <><dt>Writer</dt><dd>{p.writer}</dd></>}
                  {p.cast && <><dt>Cast</dt><dd>{p.cast}</dd></>}
                </dl>
              </React.Fragment>
            )}
          </div>
        </div>

        {prev && next && (
          <div className="pd-next pd-reveal">
            <a onClick={() => go("project/" + prev.slug)}>
              <span className="lbl">← Previous</span>
              <span className="ttl">{prev.titleStyle === "italic" ? <em>{prev.title}</em> : prev.title}</span>
            </a>
            <a onClick={() => go("project/" + next.slug)}>
              <span className="lbl">Next →</span>
              <span className="ttl">{next.titleStyle === "italic" ? <em>{next.title}</em> : next.title}</span>
            </a>
          </div>
        )}
      </div>
    </main>
  );
}

Object.assign(window, { ProjectDetailPinned });
