/* global React */
/* global I, Placeholder, useRoute */
const { useState: useWorkState, useMemo: useWorkMemo } = React;

/* ─────────────────────────────────────────────────────────────────
   Work index, case-study grid with discipline filter
   ───────────────────────────────────────────────────────────────── */
function Work() {
  const { route, goto } = useRoute();
  const initial = route.params?.filter || "all";
  const [filter, setFilter] = useWorkState(initial);
  const [layout, setLayout] = useWorkState("magazine"); // magazine | grid

  const filtered = useWorkMemo(() => {
    const f = window.WORK_FILTERS.find(x => x.key === filter);
    if (!f || !f.match) return window.WORK;
    return window.WORK.filter(f.match);
  }, [filter]);

  return (
    <main className="page-work">
      {/* Header */}
      <section className="container" style={{ padding: "72px 0 56px" }}>
        <span className="eyebrow eyebrow-gold">§ Selected Work</span>
        <h1 className="serif" style={{ fontSize: "clamp(56px, 9vw, 128px)", lineHeight: 0.92, letterSpacing: "-0.025em", margin: "16px 0 28px", maxWidth: 1200 }}>
          Selected work.<br/><span style={{ color: "var(--text-2)" }}>Made carefully, kept honest.</span>
        </h1>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 48, alignItems: "end" }}>
          <p className="pretty" style={{ fontSize: 16, lineHeight: 1.6, color: "var(--text-1)", maxWidth: 620, margin: 0 }}>
            We publish the case study only after the result has held for a season —
            press, sell-through, retention, awards, whatever the brief asked for.
            The rest stays in the studio.
          </p>
          <div className="work-meta-rail">
            <div><b>{window.WORK.length}</b><span>case studies</span></div>
            <div><b>2025</b><span>most recent year</span></div>
            <div><b>2021</b><span>founded</span></div>
          </div>
        </div>
      </section>

      {/* Filter bar */}
      <section className="container work-filterbar">
        <div className="work-filters">
          {window.WORK_FILTERS.map(f => (
            <button key={f.key} className={`filter-pill ${filter === f.key ? "is-active" : ""}`} onClick={() => setFilter(f.key)}>
              {f.label}
              <span className="mono">
                {f.key === "all" ? window.WORK.length : window.WORK.filter(f.match || (() => true)).length}
              </span>
            </button>
          ))}
        </div>
        <div className="work-layout-toggle">
          <span className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", color: "var(--text-3)", textTransform: "uppercase" }}>View</span>
          <button className={layout === "magazine" ? "is-active" : ""} onClick={() => setLayout("magazine")} aria-label="Magazine layout">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="1" y="1" width="12" height="6"/><rect x="1" y="9" width="5" height="4"/><rect x="8" y="9" width="5" height="4"/></svg>
          </button>
          <button className={layout === "grid" ? "is-active" : ""} onClick={() => setLayout("grid")} aria-label="Grid layout">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="1" y="1" width="5" height="5"/><rect x="8" y="1" width="5" height="5"/><rect x="1" y="8" width="5" height="5"/><rect x="8" y="8" width="5" height="5"/></svg>
          </button>
        </div>
      </section>

      {/* Project list */}
      {layout === "magazine" ? (
        <section className="container" style={{ padding: "32px 0 80px" }}>
          {filtered.map((p, i) => (
            <ProjectRow key={p.id} project={p} index={i} onClick={() => goto("project", { id: p.id })} />
          ))}
        </section>
      ) : (
        <section className="container" style={{ padding: "32px 0 80px" }}>
          <div className="work-grid-tight">
            {filtered.map(p => (
              <article key={p.id} className="work-grid-card" onClick={() => goto("project", { id: p.id })}>
                <Placeholder
                  label={p.title.toLowerCase()}
                  variant={p.cover.v}
                  code={p.cover.code}
                  src={p.cover.image}
                  video={p.cover.video}
                  poster={p.cover.poster}
                  focal={p.cover.focal || "center"}
                  fit="contain"
                  style={{ aspectRatio: "4/3", marginBottom: 14 }} />
                <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 6 }}>
                  {p.client} · {p.year}
                </div>
                <h3 className="serif" style={{ fontSize: 22, margin: 0, letterSpacing: "-0.005em" }}>{p.title}</h3>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 10 }}>
                  {p.discipline.slice(0, 2).map(d => <span key={d} className="chip chip-sm">{d}</span>)}
                </div>
              </article>
            ))}
          </div>
        </section>
      )}

      {filtered.length === 0 && (
        <section className="container" style={{ padding: "80px 0", textAlign: "center" }}>
          <p className="serif" style={{ fontSize: 28, margin: 0 }}>Nothing in that lane yet.</p>
          <p style={{ color: "var(--text-2)", marginTop: 8 }}>The studio publishes case studies as they earn it.</p>
        </section>
      )}

      <hr className="rule" />

      {/* CTA */}
      <section className="container" style={{ padding: "80px 0 96px", textAlign: "center" }}>
        <span className="eyebrow eyebrow-gold">§ Quietly available</span>
        <h2 className="serif" style={{ fontSize: "clamp(40px, 5vw, 64px)", lineHeight: 1.0, letterSpacing: "-0.02em", margin: "16px 0 12px", maxWidth: 900, marginInline: "auto" }}>
          Some of our favorite work doesn&apos;t leave the studio.
        </h2>
        <p style={{ color: "var(--text-2)", maxWidth: 580, margin: "0 auto 28px", fontSize: 15, lineHeight: 1.6 }}>
          NDA work, founder portraits, and a handful of films we&apos;ve been asked to keep private. Ask for the deck.
        </p>
        <div style={{ display: "inline-flex", gap: 12 }}>
          <button className="btn btn-gold btn-lg" onClick={() => goto("contact", { topic: "project" })}>Request the private deck <I name="arrow" size={16} /></button>
          <button className="btn btn-line btn-lg" onClick={() => goto("booking")}>Start a brief</button>
        </div>
      </section>
    </main>
  );
}

function ProjectRow({ project, index, onClick }) {
  const reverse = index % 2 === 1;
  return (
    <article className={`work-row ${reverse ? "work-row-rev" : ""}`} onClick={onClick}>
      <div className="work-row-media">
        <Placeholder
          label={project.title.toLowerCase()}
          variant={project.cover.v}
          code={project.cover.code}
          src={project.cover.image}
          video={project.cover.video}
          poster={project.cover.poster}
          focal={project.cover.focal || "center"}
          fit="contain"
          style={{ aspectRatio: "16/10" }} />
      </div>
      <div className="work-row-body">
        <div className="mono" style={{ fontSize: 10, letterSpacing: "0.18em", color: "var(--text-3)", textTransform: "uppercase", marginBottom: 14, display: "flex", justifyContent: "space-between" }}>
          <span>0{index + 1} · {project.client}</span>
          <span>{project.year}</span>
        </div>
        <h2 className="serif" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", lineHeight: 1.0, letterSpacing: "-0.015em", margin: "0 0 18px" }}>
          {project.title}
        </h2>
        <p className="serif" style={{ fontSize: 18, color: "var(--text-1)", lineHeight: 1.4, margin: "0 0 22px", maxWidth: 540, fontStyle: "italic" }}>
          {project.summary}
        </p>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 24 }}>
          {project.discipline.map(d => <span key={d} className="chip">{d}</span>)}
        </div>
        <div className="work-row-stats">
          {project.result.slice(0, 3).map(([n, l]) => (
            <div key={l}>
              <b className="serif">{n}</b>
              <span>{l}</span>
            </div>
          ))}
        </div>
        <span className="lk lk-arrow" style={{ marginTop: 28 }}>Open the case <I name="arrow" size={14} /></span>
      </div>
    </article>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Project detail, problem · approach · result
   ───────────────────────────────────────────────────────────────── */
function ProjectDetail() {
  const { route, goto } = useRoute();
  const id = route.params?.id || window.WORK[0].id;
  const p = window.WORK.find(x => x.id === id) || window.WORK[0];
  const next = window.WORK.find(x => x.id === p.nextId) || window.WORK[0];

  // When a project ships brand tokens, render the page in its palette.
  const brandStyle = p.brand ? {
    "--brand-bg":      p.brand.bg,
    "--brand-bg-soft": p.brand.bgSoft,
    "--brand-accent":  p.brand.accent,
    "--brand-accent-light": p.brand.accentLight,
    "--brand-text":    p.brand.text,
    background: `linear-gradient(180deg, ${p.brand.bg} 0%, ${p.brand.bgSoft || p.brand.bg} 60%, var(--bg) 100%)`,
  } : undefined;

  return (
    <main className="page-project" style={brandStyle} data-brand={p.brand ? "on" : undefined}>
      {/* Crumbs */}
      <section className="container" style={{ padding: "56px 0 16px" }}>
        <div className="crumbs">
          <a onClick={() => goto("home")}>Home</a>
          <I name="chev" size={11} />
          <a onClick={() => goto("work")}>Work</a>
          <I name="chev" size={11} />
          <span>{p.title}</span>
        </div>
      </section>

      {/* Title + meta strip */}
      <section className="container" style={{ padding: "24px 0 48px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 20, marginBottom: 28 }}>
          <span className="eyebrow" style={{ color: p.brand?.accent || "var(--gold)" }}>§ Case · {p.year}</span>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            {p.brand?.logo && (
              <img src={p.brand.logo} alt={`${p.client} mark`} style={{ height: 22, opacity: 0.9 }} />
            )}
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", color: "var(--text-3)", textTransform: "uppercase" }}>
              {p.client}
            </span>
          </div>
        </div>
        <h1 className="serif" style={{ fontSize: "clamp(48px, 8vw, 112px)", lineHeight: 0.95, letterSpacing: "-0.03em", margin: 0 }}>
          {p.title}
        </h1>
        <p className="serif" style={{ fontSize: "clamp(18px, 1.7vw, 22px)", color: "var(--text-1)", lineHeight: 1.5, margin: "28px 0 0", maxWidth: 820, fontStyle: "italic" }}>
          {p.summary}
        </p>
        {p.instagram && (
          <div className="mono" style={{ marginTop: 18, display: "flex", gap: 18, fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-3)", flexWrap: "wrap" }}>
            <span>Model · {p.instagram.model}</span>
            <span>· Photographer · {p.instagram.photographer}</span>
          </div>
        )}
        {p.href && (
          <div style={{ marginTop: 22 }}>
            <a className="btn btn-line" href={p.href} target="_blank" rel="noopener noreferrer">
              Visit live site <I name="ext" size={14} />
            </a>
          </div>
        )}
      </section>

      {/* Hero — horizontal landscape frame; portrait media shows full-frame letterboxed */}
      <section className="container" style={{ padding: "0 0 56px" }}>
        {p.cover?.video ? (
          <Placeholder label={p.title.toLowerCase()} variant={p.cover.v} code={p.cover.code} video={p.cover.video} poster={p.cover.poster} focal={p.cover.focal || "center"} fit="contain" style={{ aspectRatio: "16/9", width: "100%", maxHeight: 640 }} />
        ) : p.cover?.image ? (
          <Placeholder label={p.title.toLowerCase()} variant={p.cover.v} code={p.cover.code} src={p.cover.image} focal={p.cover.focal || "center"} fit="contain" style={{ aspectRatio: "16/9", width: "100%", maxHeight: 640 }} />
        ) : (
          <Placeholder label={p.title.toLowerCase()} variant={p.cover.v} code={p.cover.code} style={{ aspectRatio: "16/9" }} />
        )}
      </section>

      {/* Meta dossier */}
      <section className="container" style={{ padding: "0 0 64px" }}>
        <dl className="dossier">
          <div><dt>Year</dt><dd>{p.year}</dd></div>
          <div><dt>Discipline</dt><dd>{p.discipline.join(" · ")}</dd></div>
          <div><dt>Role</dt><dd>{p.role}</dd></div>
          <div><dt>Crew</dt><dd>{p.crew}</dd></div>
          {p.runtime && p.runtime !== "—" && <div><dt>Runtime</dt><dd>{p.runtime}</dd></div>}
        </dl>
      </section>

      <hr className="rule" />

      {/* Problem · Approach · Result */}
      <section className="container" style={{ padding: "72px 0" }}>
        <div className="case-stack">
          <article className="case-block">
            <span className="case-num mono">01 · Brief</span>
            <h2 className="serif">What needed to come back finished.</h2>
            <p>{p.problem}</p>
          </article>

          <article className="case-block case-block-flip">
            <span className="case-num mono">02 · Approach</span>
            <h2 className="serif">How the studio answered.</h2>
            <p>{p.approach}</p>
          </article>

          {/* Gallery — real shoot media */}
          {Array.isArray(p.gallery) && p.gallery.length > 0 && (
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${Math.min(p.gallery.length, 3)}, 1fr)`, gap: 16 }}>
              {p.gallery.map((g, i) => (
                <Placeholder
                  key={`${p.id}-${g.src || i}`}
                  label={g.label || `${p.title.toLowerCase()} · plate ${i + 1}`}
                  variant={p.cover.v}
                  code={`${p.cover.code}-${String.fromCharCode(65 + i)}`}
                  src={g.kind === "image" ? g.src : undefined}
                  video={g.kind === "video" ? g.src : undefined}
                  style={{ aspectRatio: g.aspect || "1/1" }}
                />
              ))}
            </div>
          )}

          <article className="case-block">
            <span className="case-num mono">03 · Output</span>
            <h2 className="serif">What came back.</h2>
            <p style={{ marginBottom: 32 }}>{p.summary}</p>
            <div className="result-grid">
              {p.result.map(([n, l]) => (
                <div key={l} className="result-card">
                  <b className="serif">{n}</b>
                  <span>{l}</span>
                </div>
              ))}
            </div>
          </article>
        </div>
      </section>

      <hr className="rule" />

      {/* Next project */}
      <section className="container" style={{ padding: "72px 0 96px" }}>
        <div className="next-project" onClick={() => goto("project", { id: next.id })} style={{ cursor: "pointer" }}>
          <div>
            <span className="eyebrow">Next case</span>
            <h3 className="serif" style={{ fontSize: "clamp(36px, 4.4vw, 64px)", lineHeight: 0.96, letterSpacing: "-0.02em", margin: "12px 0 16px" }}>
              {next.title}
            </h3>
            <p style={{ color: "var(--text-2)", fontSize: 14, lineHeight: 1.6, margin: 0, maxWidth: 540 }}>
              {next.summary}
            </p>
            <span className="lk lk-arrow" style={{ marginTop: 24, display: "inline-flex" }}>Read the case <I name="arrow" size={14} /></span>
          </div>
          {next.cover?.video ? (
            <Placeholder label={next.title.toLowerCase()} variant={next.cover.v} code={next.cover.code} video={next.cover.video} poster={next.cover.poster} focal={next.cover.focal || "center"} fit="contain" style={{ aspectRatio: "4/3", maxWidth: 480 }} />
          ) : next.cover?.image ? (
            <Placeholder label={next.title.toLowerCase()} variant={next.cover.v} code={next.cover.code} src={next.cover.image} focal={next.cover.focal || "center"} fit="contain" style={{ aspectRatio: "4/3", maxWidth: 480 }} />
          ) : (
            <Placeholder label={next.title.toLowerCase()} variant={next.cover.v} code={next.cover.code} style={{ aspectRatio: "4/3", maxWidth: 480 }} />
          )}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { Work, ProjectDetail });
