/* ============================================================
   FOODMAP — mismatch chart + interactive country explorer
   ============================================================ */

/* ---------- MISMATCH: diverging net-trade bars (reveal) ---------- */
function MismatchChart() {
  const [ref, seen] = useInView();
  const rows = F.MISMATCH;
  const max = Math.max(...rows.map((r) => Math.abs(r.net)));
  const W = 760,rowH = 30,padTop = 16,padBot = 8;
  const H = padTop + rows.length * rowH + padBot;
  const cx = W * 0.52; // zero line
  const scale = (Math.min(cx, W - cx) - 110) / max;

  return (
    <figure ref={ref} className="chart-frame" style={{ background: "#fff" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 8 }}>
        <div>
          <div className="chart-title">Sells it vs. buys it</div>
          <div className="chart-sub">net food trade, 2024 · US$ billion</div>
        </div>
        <div style={{ display: "flex", gap: 14 }}>
          <span className="label" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 11, height: 11, background: "var(--c-green)", border: "1.5px solid var(--ink)" }}></span> net exporter</span>
          <span className="label" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 11, height: 11, background: "var(--c-orange)", border: "1.5px solid var(--ink)" }}></span> net importer</span>
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 14, overflow: "visible" }}>
        <line x1={cx} y1={4} x2={cx} y2={H - 2} stroke="var(--ink)" strokeWidth="2" />
        <text x={cx} y={H} textAnchor="middle" className="annot-soft" style={{ fontSize: 8 }}>balanced</text>
        {rows.map((r, i) => {
          const y = padTop + i * rowH;
          const len = Math.abs(r.net) * scale * (seen ? 1 : 0);
          const pos = r.net >= 0;
          const bx = pos ? cx : cx - len;
          return (
            <g key={r.c}>
              <rect x={bx} y={y} width={len} height={rowH - 11} rx={2.5}
              fill={r.color} stroke="var(--ink)" strokeWidth="1.5"
              style={{ transition: "width 0.9s cubic-bezier(.2,.7,.2,1)", transitionDelay: `${i * 55}ms` }} />
              <text x={pos ? cx - 8 : cx + 8} y={y + (rowH - 11) / 2 + 3.5} textAnchor={pos ? "end" : "start"}
              className="annot" style={{ fontSize: 10, fontWeight: 700 }}>{r.c}</text>
              <text x={pos ? bx + len + 6 : bx - 6} y={y + (rowH - 11) / 2 + 3.5} textAnchor={pos ? "start" : "end"}
              className="annot-soft" style={{ fontSize: 9, opacity: seen ? 1 : 0, transition: "opacity .6s ease", transitionDelay: `${i * 55 + 300}ms` }}>
                {pos ? "+" : "−"}{Math.abs(r.net)}</text>
            </g>);

        })}
      </svg>
      <figcaption>A country on the right ships out more food than it brings in; on the left, the reverse. Brazil alone runs a net food surplus of well over US$100&nbsp;billion, while China, Japan and even the United States (the world's biggest gross exporter by value) end the year buying more than they sell. <strong>Net food trade (HS&nbsp;chapters 01-24), UN Comtrade, 2024.</strong></figcaption>
    </figure>);

}

/* ---------- EXPLORER: pick a country ---------- */
function gaugeColor(v) {
  if (v >= 100) return "var(--c-green)";
  if (v >= 70) return "var(--c-teal)";
  if (v >= 45) return "var(--c-yellow)";
  return "var(--c-orange)";
}
function Explorer() {
  const E = F.EXPLORER;
  const [key, setKey] = useState("japan");
  const d = E.data[key];
  // gauge geometry (top half-donut, swept left→right over the top)
  const pct = Math.min(d.selfSufficiency, 160) / 160;
  const R = 78,CX = 100,CY = 100;
  const ptAt = (frac) => {
    const ang = Math.PI * (1 - frac);
    return [CX + R * Math.cos(ang), CY - R * Math.sin(ang)];
  };
  const [x0, y0] = ptAt(0);
  const [x1, y1] = ptAt(pct);
  const arc = `M${x0},${y0} A${R},${R} 0 0 1 ${x1},${y1}`;
  const trackEnd = CX + R * Math.cos(0);

  return (
    <div className="chart-frame explorer" style={{ padding: "24px 26px 28px" }}>
      <div className="chart-title">Does your country sell or buy more food?</div>
      <div className="chart-sub">food exports as a share of food imports · 2024 · pick a country</div>

      <div className="pill-row" style={{ margin: "18px 0 22px" }}>
        {E.order.map((k) =>
        <button key={k} className={"pill" + (k === key ? " on" : "")} onClick={() => setKey(k)}>{E.data[k].name}</button>
        )}
      </div>

      <div className="explorer-body">
        <div style={{ textAlign: "center" }}>
          <svg viewBox="0 0 200 118" style={{ width: "100%", maxWidth: 200 }}>
            <path d={`M${CX - R},${CY} A${R},${R} 0 0 1 ${trackEnd},${CY}`} fill="none" stroke="var(--bg-warm)" strokeWidth="16" strokeLinecap="round" />
            {/* 100% marker */}
            {(() => {const am = Math.PI * (1 - 100 / 160);const mx = CX + (R + 11) * Math.cos(am),my = CY - (R + 11) * Math.sin(am);const ix = CX + (R - 11) * Math.cos(am),iy = CY - (R - 11) * Math.sin(am);return <line x1={ix} y1={iy} x2={mx} y2={my} stroke="var(--ink)" strokeWidth="2" strokeDasharray="2 2" />;})()}
            <path key={key} d={arc} fill="none" stroke={gaugeColor(d.selfSufficiency)} strokeWidth="16" strokeLinecap="round"
            style={{ transition: "stroke 0.4s ease" }} />
            <text x={CX} y={CY - 8} textAnchor="middle" className="bignum" style={{ fontSize: 34, fill: gaugeColor(d.selfSufficiency) }}>{d.selfSufficiency}%</text>
            <text x={CX} y={CY + 10} textAnchor="middle" className="annot-soft" style={{ fontSize: 9 }}>export cover</text>
          </svg>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 2 }}>dashed mark = 100% (exports = imports)</div>
        </div>

        <div>
          <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: "1.5rem", marginBottom: 4 }}>{d.name}</div>
          <p style={{ fontSize: "1.05rem", lineHeight: 1.5, color: "var(--ink-soft)", margin: "0 0 16px" }}>{d.blurb}</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
            <div>
              <div className="label" style={{ color: "var(--c-green)", marginBottom: 8 }}>↗ ships out</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {d.exports.map((x) => <span key={x} className="tag"><span className="sq" style={{ background: "var(--c-green)" }}></span>{x}</span>)}
              </div>
            </div>
            <div>
              <div className="label" style={{ color: "var(--c-orange)", marginBottom: 8 }}>↘ brings in</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {d.imports.map((x) => <span key={x} className="tag"><span className="sq" style={{ background: "var(--c-orange)" }}></span>{x}</span>)}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="credit" style={{ marginTop: 18, borderTop: "2px solid var(--line)", paddingTop: 10 }}>Food trade by country (HS&nbsp;chapters 01-24), UN Comtrade, 2024. Tags list each country's largest traded products.</div>
    </div>);

}

Object.assign(window, { MismatchChart, Explorer });