/* CaseStudy — process-led deep read; image figures + editorial text */

function csHTML(t) { return { __html: t }; }

function Block({ b }) {
  switch (b.type) {
    case "p":
      return <p className={b.lead ? "lead" : ""} dangerouslySetInnerHTML={csHTML(b.t)} />;
    case "pull":
      return <blockquote className="pull"><span dangerouslySetInnerHTML={csHTML(b.t)} /></blockquote>;
    case "decisions":
      return (
        <div className="decisions">
          {b.items.map((it, i) => (
            <div className="decision" key={i}>
              <span className="dn">{String(i + 1).padStart(2, "0")}</span>
              <div><h4>{it.h}</h4><p>{it.p}</p></div>
            </div>
          ))}
        </div>
      );
    default: return null;
  }
}

function Figure({ b }) {
  return (
    <figure className="figure bleed">
      <Placeholder aspect={b.aspect} kind={b.kind} label={b.label} src={b.src || null} srcset={b.srcset || null} sizes={b.sizes || null} />
      <figcaption>
        <span className="fc-num label label-sm">Fig. {b.fc}</span>
        <span className="fc-text">{b.fcText}</span>
      </figcaption>
    </figure>
  );
}

function FigureRow({ b }) {
  const count = Math.min(Math.max(b.items.length, 2), 3);
  return (
    <div className="figure-row bleed">
      <div className={`figure-row-images cols-${count}`}>
        {b.items.map((item, i) => (
          <figure key={i} className="figure-row-item">
            <Placeholder aspect={item.aspect} kind={item.kind || "image"} label={item.label} src={item.src || null} srcset={item.srcset || null} sizes={item.sizes || null} />
            {(item.fc || item.fcText) && (
              <figcaption>
                {item.fc && <span className="fc-num label label-sm">Fig. {item.fc}</span>}
                {item.fcText && <span className="fc-text">{item.fcText}</span>}
              </figcaption>
            )}
          </figure>
        ))}
      </div>
    </div>
  );
}

function Section({ s }) {
  const groups = [];
  let buf = [];
  const flush = () => { if (buf.length) { groups.push({ kind: "prose", blocks: buf }); buf = []; } };
  s.body.forEach((b) => {
    if (b.type === "figure") { flush(); groups.push({ kind: "figure", block: b }); }
    else if (b.type === "figure-row") { flush(); groups.push({ kind: "figure-row", block: b }); }
    else buf.push(b);
  });
  flush();

  return (
    <div className="reveal">
      <div className="prose">
        <div className="section-num">
          <span className="n">{s.n}</span>
          <h2>{s.h}</h2>
        </div>
      </div>
      {groups.map((g, i) =>
        g.kind === "figure"
          ? <Figure key={i} b={g.block} />
          : g.kind === "figure-row"
          ? <FigureRow key={i} b={g.block} />
          : <div className="prose" key={i}>{g.blocks.map((b, j) => <Block key={j} b={b} />)}</div>
      )}
    </div>
  );
}

function CaseStudy({ id, go }) {
  const reveal = useReveal();
  const p = DATA.projects.find((x) => x.id === id) || DATA.projects[0];
  const next = DATA.projects.find((x) => x.id === p.next);

  useLayoutEffect(() => { window.scrollTo({ top: 0, behavior: "auto" }); }, [id]);

  return (
    <div className="view cs" ref={reveal}>
      <div className="shell-wide">
        <span className="cs-back" onClick={() => go({ name: "home" })}>← All work</span>
      </div>

      {/* hero */}
      <header className="cs-hero shell-wide">
        <div className="cs-eyebrow label">
          <span className="proj">Project {p.idx}</span>
          <span className="sep">/</span>
          <span>{p.year}</span>
          <span className="sep">/</span>
          <span>{disciplineLabel(p.tags)}</span>
        </div>
        <h1 className="cs-title">{p.title}</h1>
        <p className="cs-standfirst" dangerouslySetInnerHTML={csHTML(p.standfirst)} />
      </header>

      {/* opening full-bleed image */}
      <div className="figure bleed" style={{ marginTop: 8 }}>
        <Placeholder aspect={p.coverAspect || "aspect-16-9"} kind="image" label={`${p.title} — lead image`} src={p.coverSrc || null} srcset={p.coverSrcset || null} sizes={p.coverSizes || null} />
        {!p.coverSrc && (
          <figcaption className="figure" style={{ margin: 0, display: "flex", gap: 14, alignItems: "baseline", marginTop: 13 }}>
            <span className="fc-num label label-sm">Lead</span>
            <span className="fc-text" style={{ color: "var(--ink-faint)", fontStyle: "italic", fontSize: "0.92rem" }}>Drop the hero render or photograph here.</span>
          </figcaption>
        )}
      </div>

      {/* fact strip */}
      <div className="shell-wide">
        <div className="factstrip">
          {p.facts.map((f, i) => (
            <div className="fact" key={i}><span className="k label label-sm">{f.k}</span><span className="v">{f.v}</span></div>
          ))}
        </div>
      </div>

      {/* sections */}
      <div className="shell-wide">
        {p.sections.map((s) => <Section key={s.n} s={s} />)}
      </div>

      {/* next project */}
      {next && (
        <div className="shell-wide">
          <div className="cs-next" onClick={() => go({ name: "project", id: next.id })}>
            <div>
              <span className="nx-label">Next — Project {next.idx}</span>
              <h3>{next.title}</h3>
            </div>
            <span className="nx-arrow">→</span>
          </div>
        </div>
      )}

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

window.CaseStudy = CaseStudy;
