function Chart({ data, labels }) {
  const w = 720, h = 220, pad = 32;
  const max = Math.max(...data.flat());
  const stepX = (w - pad * 2) / (data[0].length - 1);
  const toPts = arr => arr.map((v, i) => [pad + i * stepX, h - pad - (v / max) * (h - pad * 2)]);
  const line = arr => "M " + toPts(arr).map(p => p.join(",")).join(" L ");
  return (
    <div className="chart">
      <div className="chart__head">
        <span>Revenue vs baseline · last 6 mo</span>
        <span>indexed, month 0 = 100</span>
      </div>
      <svg className="chart__svg" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
        {/* grid */}
        {[0, 1, 2, 3].map(i => (
          <line key={i} x1={pad} x2={w - pad} y1={pad + i * ((h - pad * 2) / 3)} y2={pad + i * ((h - pad * 2) / 3)} stroke="var(--line)" strokeWidth="1" />
        ))}
        {/* baseline */}
        <path d={line(data[1])} fill="none" stroke="var(--muted)" strokeWidth="1.5" strokeDasharray="4 4" />
        {/* revenue */}
        <path d={line(data[0])} fill="none" stroke="var(--accent)" strokeWidth="2.5" />
        {/* dots */}
        {toPts(data[0]).map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="4" fill="var(--accent)" />
        ))}
        {/* x labels */}
        {labels.map((l, i) => (
          <text key={i} x={pad + i * stepX} y={h - 8} fontSize="10" fontFamily="var(--mono)" fill="var(--muted)" textAnchor="middle">{l}</text>
        ))}
      </svg>
      <div className="chart__legend">
        <span><i style={{background: "var(--accent)"}} />Post-engagement revenue</span>
        <span><i style={{background: "var(--muted)"}} />Projected baseline</span>
      </div>
    </div>
  );
}

function Funnel({ rows }) {
  const max = rows[0].v;
  return (
    <div className="chart">
      <div className="chart__head">
        <span>Funnel breakdown</span>
        <span>last 30 days</span>
      </div>
      <div className="funnel">
        {rows.map((r, i) => (
          <div className="funnel__row" key={i}>
            <div className="funnel__label">{r.label}</div>
            <div className="funnel__bar" style={{width: `${(r.v / max) * 100}%`}} />
            <div className="funnel__val">{r.display}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function WorkPage({ onGo }) {
  const D = window.DATA;
  const [expanded, setExpanded] = useState("koyo");
  return (
    <>
      <section className="wrap">
        <div style={{padding: "clamp(40px, 6vw, 80px) 0 clamp(32px, 4vw, 60px)"}}>
          <Reveal>
            <span className="hero__kicker">Work · case studies</span>
          </Reveal>
          <Reveal delay={80}>
            <h1 className="about-hero__title" style={{marginTop: 24, maxWidth: 1200}}>
              Engagements where the <em>numbers</em> did the talking.
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p style={{color: "var(--fg-2)", fontSize: 18, maxWidth: 640, lineHeight: 1.55}}>
              Selected engagements from the last three years. Click any row to open the full teardown.
            </p>
          </Reveal>
        </div>
      </section>

      <section className="wrap">
        <div className="work-index">
          {D.cases.map((c, i) => (
            <Reveal key={c.id} delay={i * 60} className="work-row" as="div">
              <div className="work-row__num">[{String(i + 1).padStart(2, "0")}]</div>
              <div>
                <div className="work-row__name" onClick={() => setExpanded(expanded === c.id ? null : c.id)}>{c.name}</div>
              </div>
              <div className="work-row__tag">{c.industry}</div>
              <div className="work-row__metric">{c.hero}</div>
              <div className="work-row__year">{c.year}</div>
              <div className="work-row__arr" onClick={() => setExpanded(expanded === c.id ? null : c.id)}>{expanded === c.id ? "−" : "↗"}</div>
            </Reveal>
          ))}
        </div>
      </section>

      {/* Expanded case */}
      {expanded && (() => {
        const c = D.cases.find(x => x.id === expanded);
        // Generate a chart per case, deterministic-ish
        const chartData = {
          koyo:   [[100, 112, 128, 148, 168, 192, 221], [100, 103, 106, 108, 109, 111, 113]],
          northwind: [[100, 118, 141, 172, 205, 248, 310], [100, 104, 108, 112, 116, 119, 123]],
          paperline: [[100, 108, 118, 132, 151, 174, 204], [100, 105, 109, 114, 118, 121, 125]],
          atlas:  [[100, 140, 185, 230, 280, 335, 398], [100, 101, 103, 105, 107, 108, 110]],
        }[expanded];
        const funnelRows = {
          koyo: [
            { label: "Impressions", v: 12400000, display: "12.4M" },
            { label: "Clicks", v: 186000, display: "186k" },
            { label: "Landing page", v: 142000, display: "142k" },
            { label: "Add to cart", v: 11200, display: "11.2k" },
            { label: "Checkout", v: 6800, display: "6.8k" },
            { label: "Purchase", v: 4820, display: "4,820" },
          ],
          northwind: [
            { label: "Impressions", v: 3200000, display: "3.2M" },
            { label: "Sessions", v: 94000, display: "94k" },
            { label: "Account created", v: 8400, display: "8.4k" },
            { label: "Demo booked", v: 1240, display: "1,240" },
            { label: "Demo attended", v: 860, display: "860" },
            { label: "Closed-won", v: 142, display: "142" },
          ],
          paperline: [
            { label: "Impressions", v: 8600000, display: "8.6M" },
            { label: "Clicks", v: 128000, display: "128k" },
            { label: "Landing page", v: 94000, display: "94k" },
            { label: "Add to cart", v: 7200, display: "7.2k" },
            { label: "Checkout", v: 4400, display: "4.4k" },
            { label: "Purchase", v: 3180, display: "3,180" },
          ],
          atlas: [
            { label: "Impressions", v: 4400000, display: "4.4M" },
            { label: "Clicks", v: 72000, display: "72k" },
            { label: "Landing page", v: 54000, display: "54k" },
            { label: "Form started", v: 6200, display: "6.2k" },
            { label: "Form complete", v: 2840, display: "2,840" },
            { label: "Consult booked", v: 2052, display: "2,052" },
          ],
        }[expanded];

        return (
          <section className="case-detail">
            <div className="wrap">
              <div className="case-detail__head">
                <div>
                  <div className="section__num" style={{marginBottom: 12}}>
                    Case detail · {c.tag} · {c.year}
                  </div>
                  <h2 className="case-detail__title">{c.name}</h2>
                </div>
                <dl className="case-detail__meta">
                  <dt>Industry</dt><dd>{c.industry}</dd>
                  <dt>Role</dt><dd>Growth partner</dd>
                  <dt>Engagement</dt><dd>6 months retainer</dd>
                  <dt>Team</dt><dd>Solo + 1 creative contractor</dd>
                </dl>
              </div>

              <div className="case-detail__grid">
                <div><h4>Problem</h4><p>{c.problem}</p></div>
                <div><h4>Hypothesis</h4><p>{c.hypothesis}</p></div>
                <div><h4>Strategy</h4><p>{c.strategy}</p></div>
              </div>

              <div className="case-detail__grid" style={{gridTemplateColumns: "1fr"}}>
                <div><h4>Execution</h4><p>{c.execution}</p></div>
              </div>

              <Chart data={chartData} labels={["M0", "M1", "M2", "M3", "M4", "M5", "M6"]} />

              <Funnel rows={funnelRows} />

              <div className="case-detail__results">
                {c.metrics.map((m, i) => (
                  <div key={i}>
                    <div className="num">{m.num}</div>
                    <div className="lbl">{m.lbl}</div>
                  </div>
                ))}
              </div>
            </div>
          </section>
        );
      })()}

      <section className="cta-big">
        <div className="wrap">
          <Reveal><h2 className="cta-big__title">Your case study is <em>next.</em></h2></Reveal>
          <Reveal delay={120}>
            <div className="cta-big__row">
              <button className="btn btn--primary" onClick={() => onGo("contact")}>Start a project <span className="arr">↗</span></button>
            </div>
          </Reveal>
        </div>
      </section>
    </>
  );
}

window.WorkPage = WorkPage;
