/* Save Our Family Farms — impact map section (tile-grid cartogram). */
const { TILE, NAME, TARGETS } = window.SOFF_DATA;

function initials(fullName) {
  return fullName.split(" ").map((w) => w[0]).slice(0, 2).join("");
}

// Sign-aware percent, dropping a trailing ".0" (e.g. 220 → "+220%", -4.5 → "−4.5%").
function fmtPct(n) {
  const r = Math.round(n * 10) / 10;
  const s = (Number.isInteger(r) ? r.toString() : r.toFixed(1)).replace("-", "");
  return (n < 0 ? "−" : "+") + s + "%";
}
const METRIC = {
  farm: { badge: "Farm Ch. 12", capUp: "Rise in farm bankruptcies (Ch. 12) · 2024–25", capDown: "Change in farm bankruptcies (Ch. 12) · 2024–25" },
  total: { badge: "All filings", capUp: "Rise in all bankruptcy filings · 2024–25", capDown: "Change in all bankruptcy filings · 2024–25" }
};

function MapPanel({ code, onCall }) {
  if (!code) {
    return (
      <aside className="panel empty">
        <div className="roof-top"><Roofline color="#9c3a2a" height={11} stroke={2.4} /></div>
        <div className="pad">
          <div className="prompt-ico">
            <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0Z" /><circle cx="12" cy="10" r="3" /></svg>
          </div>
          <p className="prompt">Select a highlighted state</p>
          <p className="prompt-sub">Eight states hold the votes that decide this. Tap a navy tile to see how hard rural communities there are being hit — and which senator needs to hear from you.</p>
        </div>
      </aside>);

  }
  const d = TARGETS[code];
  const m = METRIC[d.metric];
  const down = d.bk < 0;
  return (
    <aside className="panel" key={code}>
      <div className="roof-top"><Roofline color="#9c3a2a" height={11} stroke={2.4} /></div>
      <div className="pad">
        <p className="st-name">{NAME[code]}</p>
        <div className={"bk" + (down ? " down" : "")}><span className="arrow">{down ? "▼" : "▲"}</span><b>{fmtPct(d.bk)}</b><span className={"bk-badge" + (d.metric === "farm" ? " ok" : "")}>{m.badge}</span></div>
        <p className="bk-cap">{down ? m.capDown : m.capUp}</p>
        <p className="hook">{d.hook}</p>
        <div className="sen-list">
          {d.senators.map((s) =>
          <div className="sen" key={s.name}>
              <div className="av">{initials(s.name)}</div>
              <div>
                <p className="nm">Sen. {s.name} ({s.party})</p>
                <p className="nt">{s.note}</p>
              </div>
            </div>
          )}
        </div>
        <div className="pbtn">
          <button className="btn btn-primary" onClick={() => onCall && onCall(code)}>
            Get talking points →
          </button>
        </div>
      </div>
    </aside>);

}

function MapSection({ selected, onSelect, onCall }) {
  const tiles = Object.keys(TILE).map((code) => {
    const [x, y] = TILE[code];
    const isTarget = !!TARGETS[code];
    const style = { gridColumn: x + 1, gridRow: y + 1 };
    if (!isTarget) {
      return <div key={code} className="tile other" style={style} aria-hidden="true">{code}</div>;
    }
    const sel = selected === code;
    const t = TARGETS[code];
    const metricWord = t.metric === "farm" ? "farm bankruptcies" : "bankruptcy filings";
    return (
      <button
        key={code}
        className={"tile target" + (sel ? " sel" : "") + (t.bk < 0 ? " neg" : "")}
        style={style}
        aria-pressed={sel}
        aria-label={`${NAME[code]} — ${metricWord} ${t.bk < 0 ? "down" : "up"} ${Math.abs(t.bk)}% (2024–25)`}
        onClick={() => onSelect(sel ? null : code)}>
        
        <span className="ab">{code}</span>
        <span className="pct">{fmtPct(t.bk)}</span>
      </button>);

  });

  return (
    <section className="mapsec" id="map">
      <div className="wrap">
        <div className="head">
          <p className="eyebrow">The impact map</p>
          <h2 className="h2">FIND YOUR STATE. SEE THE SQUEEZE.</h2>
          <p className="lead">Nine Senators across eight states hold the swing votes on Farm Bill programs and relief. Here's how hard communities in each are being hit.</p>
        </div>

        <div className="map-layout">
          <div>
            <div className="board-wrap">
              <div className="board" role="group" aria-label="United States impact map">{tiles}</div>
            </div>
            <div className="legend">
              <span className="item"><span className="sw" style={{ background: "var(--color-brand)" }}></span>Target state</span>
              <span className="item"><span className="sw" style={{ background: "var(--color-accent)" }}></span>Selected</span>
              <span className="item"><span className="sw" style={{ background: "var(--sand-200)" }}></span>Other state</span>
              <em className="ph">Farm-specific (Ch. 12) where marked; otherwise all filings · 2024–25</em>
            </div>
          </div>
          <MapPanel code={selected} onCall={onCall} />
        </div>
      </div>
    </section>);

}

Object.assign(window, { MapSection });