// v2-project.jsx — project case page (three layouts: editorial · cinematic · magazine)

const BackArrow = ({ flip }) => (
  <svg width="34" height="10" viewBox="0 0 34 10" fill="none" aria-hidden="true" style={flip ? { transform: "scaleX(-1)" } : undefined}>
    <path d="M0 5h32M28 1l4 4-4 4" stroke="currentColor" strokeWidth="1" />
  </svg>
);

function CaseImg({ id, w = 2200, alt, onClick, className = "" }) {
  return (
    <button type="button" className={`cs-img zoomable ${className}`} onClick={onClick} aria-label={alt}>
      <img src={DRIVE_IMG(id, w)} alt={alt} loading="lazy" />
    </button>
  );
}

// ── output reel — horizontal, counter + arrow controls ────────
function CaseReel({ p }) {  const trackRef = React.useRef(null);
  const [active, setActive] = React.useState(1);
  const [edge, setEdge] = React.useState({ start: true, end: false });
  const n = p.gallery.length;

  const step = () => {
    const el = trackRef.current;
    if (!el) return el ? el.clientWidth : 1;
    const first = el.querySelector(".cs-reel-item");
    const g = parseFloat(getComputedStyle(el).columnGap || getComputedStyle(el).gap) || 0;
    return (first ? first.offsetWidth : el.clientWidth) + g;
  };
  const onScroll = () => {
    const el = trackRef.current; if (!el) return;
    const s = step() || 1;
    setActive(Math.max(1, Math.min(n, Math.round(el.scrollLeft / s) + 1)));
    setEdge({ start: el.scrollLeft <= 2, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 2 });
  };
  const go = (dir) => {
    const el = trackRef.current; if (!el) return;
    el.scrollBy({ left: dir * step(), behavior: "smooth" });
  };
  React.useEffect(() => { onScroll(); }, []);

  return (
    <section className="cs-reel-wrap" data-screen-label={`Project — ${p.name} — output`}>
      <Reveal>
        <div className="cs-reel-bar" style={{ paddingTop: 0 }}>
          <div className="cs-reel-lead">
            <span className="cs-reel-kick">Selected frames</span>
            <span className="cs-reel-count">
              {String(active).padStart(2, "0")} <span className="tot">— {String(n).padStart(2, "0")}</span>
            </span>
          </div>
          <div className="cs-reel-nav">
            <button type="button" className="cs-reel-btn" onClick={() => go(-1)} disabled={edge.start} aria-label="Previous">
              <svg width="34" height="10" viewBox="0 0 34 10" fill="none" style={{ transform: "scaleX(-1)" }}><path d="M0 5h32M28 1l4 4-4 4" stroke="currentColor" strokeWidth="1" /></svg>
            </button>
            <button type="button" className="cs-reel-btn" onClick={() => go(1)} disabled={edge.end} aria-label="Next">
              <svg width="34" height="10" viewBox="0 0 34 10" fill="none"><path d="M0 5h32M28 1l4 4-4 4" stroke="currentColor" strokeWidth="1" /></svg>
            </button>
          </div>
        </div>
      </Reveal>
      <div className="cs-reel-track" ref={trackRef} onScroll={onScroll}>
        {p.gallery.map((gid, i) => (
          <button key={gid} type="button" className="cs-reel-item" onClick={() => openLightbox(p.gallery, i)} aria-label={`${p.name} — open image ${i + 1}`}>
            <img src={DRIVE_IMG(gid, 1800)} alt={`${p.name} ${String(i + 1).padStart(2, "0")}`} loading="lazy" />
            <span className="cs-reel-cap">{p.name} — Nº {String(i + 1).padStart(2, "0")}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

// ══ EDITORIAL — split intro (facts panel · image) + output reel ══
function CaseEditorial({ p, onBack }) {
  const [cover] = p.gallery;
  const n = p.gallery.length;
  const num = String(PROJECTS.findIndex(x => x.slug === p.slug) + 1).padStart(2, "0");
  const outputCopy = `Obsidian Studio delivered the full visual set for ${p.name} — ${p.services.join(", ").toLowerCase()} across ${p.cat.toLowerCase()} architecture in ${p.loc}. ${n} final frame${n > 1 ? "s" : ""}, produced end-to-end in-house and formatted for the boardroom, the sales floor and print.`;
  return (
    <>
      <section className="cs-split" data-screen-label={`Project — ${p.name}`}>
        <div className="cs-split-panel">
          <Reveal>
            <div className="cs-crumb label">
              <button type="button" onClick={onBack}>Work</button>
              <span className="sep">/</span>
              <span className="cur">{p.name}</span>
            </div>
          </Reveal>
          <Reveal delay={60}>
            <span className="cs-over label">Nº {num} · {p.cat}</span>
          </Reveal>
          <Reveal delay={90}><h1 className="cs-title">{p.name}</h1></Reveal>
          <Reveal delay={160}><p className="cs-lede">{p.summary}</p></Reveal>
          <Reveal delay={220}>
            <div className="cs-panel-out">
              <span className="cs-reel-kick">Obsidian output</span>
              <p className="cs-lede">{outputCopy}</p>
            </div>
          </Reveal>
          <Reveal delay={280}><hr className="cs-rule" /></Reveal>
          <Reveal delay={320}>
            <div className="cs-metrics">
              <div className="cs-metric">
                <span className="k">Location</span><span className="val">{p.loc}</span>
              </div>
              <div className="cs-metric">
                <span className="k">Sector</span><span className="val">{p.cat} · {p.year}</span>
              </div>
              <div className="cs-metric">
                <span className="k">Output</span><span className="val">{n} final frame{n > 1 ? "s" : ""} · in-house, Lviv</span>
              </div>
              <div className="cs-metric">
                <span className="k">Services</span>
                <div className="cs-chips">
                  {p.services.map(s => <span key={s} className="cs-chip">{s}</span>)}
                </div>
              </div>
            </div>
          </Reveal>
        </div>
        <div className="cs-split-media">
          <img src={DRIVE_IMG(cover, 2000)} alt={p.name} />
        </div>
      </section>

      <CaseReel p={p} />
    </>
  );
}

// ══ CINEMATIC — full-viewport hero, facts strip, full-bleed reel ══
function CaseCinematic({ p, onBack }) {
  const [cover, ...rest] = p.gallery;
  return (
    <>
      <section className="cs2-hero" data-screen-label={`Project — ${p.name}`}>
        <img className="cs2-hero-img" src={DRIVE_IMG(cover, 2400)} alt={p.name} />
        <div className="pd-hero-scrim"></div>
        <button type="button" className="pd-back line-link dark" onClick={onBack}>
          <BackArrow flip />
          <span className="label" style={{ letterSpacing: ".22em" }}>All work</span>
        </button>
        <div className="cs2-hero-body">
          <span className="label" style={{ color: "var(--w-2)" }}>{p.cat} · {p.loc}</span>
          <h1 className="d1" style={{ color: "var(--w-1)" }}>{p.name}</h1>
        </div>
      </section>

      <div className="cs2-strip">
        <div className="cs2-cell">
          <span className="label" style={{ color: "var(--w-3)" }}>Location</span>
          <span className="cs2-cell-v">{p.loc}</span>
        </div>
        <div className="cs2-cell">
          <span className="label" style={{ color: "var(--w-3)" }}>Sector</span>
          <span className="cs2-cell-v">{p.cat}</span>
        </div>
        <div className="cs2-cell">
          <span className="label" style={{ color: "var(--w-3)" }}>Year</span>
          <span className="cs2-cell-v">{p.year}</span>
        </div>
        <div className="cs2-cell">
          <span className="label" style={{ color: "var(--w-3)" }}>Scope</span>
          <span className="cs2-cell-v">{p.services.join(" · ")}</span>
        </div>
      </div>

      <section className="sec dark">
        <Reveal>
          <p className="d3 cs2-sum" style={{ color: "var(--w-1)" }}>{p.summary}</p>
        </Reveal>
      </section>

      {rest.length > 0 && (
        <div className="cs2-reel">
          {rest.map((gid, i) => (
            <button key={gid} type="button" className="cs2-shot zoomable" onClick={() => openLightbox(p.gallery, i + 1)} aria-label={`${p.name} — image ${i + 2}`}>
              <img src={DRIVE_IMG(gid, 2400)} alt={`${p.name} ${String(i + 2).padStart(2, "0")}`} loading="lazy" />
            </button>
          ))}
        </div>
      )}
    </>
  );
}

// ══ MAGAZINE — sticky facts column + scrolling gallery ════════
function CaseMagazine({ p, onBack, onContact }) {
  return (
    <div className="cs3" data-screen-label={`Project — ${p.name}`}>
      <aside className="cs3-side">
        <button type="button" className="line-link dark" onClick={onBack}>
          <BackArrow flip />
          <span className="label" style={{ letterSpacing: ".22em" }}>All work</span>
        </button>
        <h1 className="d2" style={{ color: "var(--w-1)" }}>{p.name}</h1>
        <p style={{ color: "var(--w-2)", maxWidth: "52ch" }}>{p.summary}</p>
        <ul className="cs3-facts">
          <li className="cs3-frow"><span className="k">Location</span><span className="v">{p.loc}</span></li>
          <li className="cs3-frow"><span className="k">Sector</span><span className="v">{p.cat}</span></li>
          <li className="cs3-frow"><span className="k">Year</span><span className="v">{p.year}</span></li>
          <li className="cs3-frow"><span className="k">Scope</span><span className="v">{p.services.join(" · ")}</span></li>
        </ul>
        <LineLink tone="dark" onClick={onContact}>Start a project like this</LineLink>
      </aside>
      <div className="cs3-feed">
        {p.gallery.map((gid, i) => (
          <CaseImg key={gid} id={gid} w={2000} alt={`${p.name} ${String(i + 1).padStart(2, "0")}`} onClick={() => openLightbox(p.gallery, i)} />
        ))}
      </div>
    </div>
  );
}

// ══ PAGE ══════════════════════════════════════════════════════
function ProjectPage2({ slug, layout = "editorial", onOpenProject, onBack, onContact }) {
  const p = getProject(slug);
  const idx = PROJECTS.findIndex(x => x.slug === p.slug);
  const next = PROJECTS[(idx + 1) % PROJECTS.length];

  const body =
    layout === "cinematic" ? <CaseCinematic p={p} onBack={onBack} /> :
    layout === "magazine"  ? <CaseMagazine p={p} onBack={onBack} onContact={onContact} /> :
    <CaseEditorial p={p} onBack={onBack} />;

  return (
    <div className="page2 proj-detail" key={p.slug + layout}>
      {body}

      {/* Next project */}
      <section className="pd-next" onClick={() => onOpenProject(next.slug)}>
        <img className="pd-next-bg" src={DRIVE_IMG(next.cover, 2000)} alt="" aria-hidden="true" />
        <div className="pd-next-scrim"></div>
        <div className="pd-next-inner">
          <span className="label" style={{ color: "var(--w-3)" }}>Next project</span>
          <h2 className="d1" style={{ color: "var(--w-1)" }}>{next.name}</h2>
          <span className="label pd-next-cta" style={{ color: "var(--accent)" }}>
            View project →
          </span>
        </div>
      </section>

      <Closing2 onContact={onContact} />
    </div>
  );
}

Object.assign(window, { ProjectPage2 });
