// State Detail page — human-first reframe.
// Hero: state name (moderate scale) + ONE editorial finding.
// Summary card: visual at-a-glance — top lenses + party split + count.
// Lens spectrum: ALL lenses with data, no overflow.
// Featured bills: cards with evidence.
{
const { LENSES, STATES, scoreFor, lensMetaFor, billsFor, billCountFor } = window.PL_DATA;

function StatePage({ go, setLensId }) {
  const code = window.__plSelectedState || "TX";
  const st = STATES.find(s => s[0] === code);
  if (!st) return <div style={{ padding: 48 }}>Missing state.</div>;
  const [, name] = st;

  // Lenses where this state has actually-scored data
  const lensRows = LENSES
    .map(l => {
      const meta = lensMetaFor(code, l.id);
      const passed = scoreFor(code, l.id, "passed");
      const pressure = scoreFor(code, l.id, "pressure");
      return { ...l, passed, pressure, meta, billCount: meta?.bill_count || 0, nPassed: meta?.n_passed || 0 };
    })
    .filter(l => l.billCount > 0)
    .sort((a, b) => b.billCount - a.billCount);

  const totalBills = lensRows.reduce((s, l) => s + l.billCount, 0);
  const totalPassed = lensRows.reduce((s, l) => s + l.nPassed, 0);

  // Top 3 most-active lenses, used to drive the headline finding
  const topLenses = lensRows.slice(0, 3);

  // Default active lens = the most-scored one
  const [activeLens, setActiveLens] = React.useState(topLenses[0]?.id || "reproductive");
  const activeRow = lensRows.find(l => l.id === activeLens) || topLenses[0];

  // Editorial finding driven by the data
  const finding = buildFinding(name, lensRows);

  return (
    <div className="pl-page pl-state-page">
      {/* HERO — state name + editorial finding */}
      <section style={{
        padding: "40px clamp(24px, 4vw, 64px) 32px",
        borderBottom: "1px solid var(--rule)",
        display: "grid",
        gridTemplateColumns: "minmax(0, 1.4fr) minmax(280px, 1fr)",
        gap: 48,
        alignItems: "start",
      }}>
        <div style={{ minWidth: 0 }}>
          <button onClick={() => go("landing")} className="mono"
            style={{ background: "transparent", border: "none", color: "var(--ink-3)",
              fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase",
              cursor: "pointer", padding: 0, marginBottom: 16, }}>
            ← Back to atlas
          </button>
          <div style={{ display: "flex", gap: 18, alignItems: "baseline", flexWrap: "wrap" }}>
            <h1 className="display" style={{ fontSize: "clamp(56px, 7vw, 96px)", margin: 0, letterSpacing: "-0.025em", lineHeight: 0.95 }}>
              {name}
            </h1>
            <div className="mono" style={{ fontSize: 12, color: "var(--ink-3)", letterSpacing: "0.08em" }}>
              {code} · 2025–26 SESSION
            </div>
          </div>
          <p style={{ fontSize: 18, color: "var(--ink-2)", maxWidth: 620, marginTop: 18, lineHeight: 1.5 }}>
            {finding}
          </p>
        </div>

        {/* Summary card — compact visual at-a-glance */}
        <SummaryCard code={code} name={name} totalBills={totalBills} totalPassed={totalPassed} topLenses={topLenses} />
      </section>

      {/* LENS SPECTRUM — every lens with data, sorted by activity */}
      <section style={{ padding: "32px clamp(24px, 4vw, 64px)" }}>
        <div style={{ marginBottom: 20 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>The {name} lens spectrum</div>
          <p style={{ fontSize: 14, color: "var(--ink-3)", margin: 0, maxWidth: 640 }}>
            Each row is one policy lens with at least one scored bill in this state.
            <strong style={{ color: "var(--ink-2)" }}> Filled bar </strong> = bills that became law.
            <strong style={{ color: "var(--ink-2)" }}> Dashed outline </strong> = all bills introduced (the pressure).
            Click a row to see its bills below.
          </p>
        </div>

        {lensRows.length === 0 ? (
          <div style={{ padding: 32, textAlign: "center", color: "var(--ink-3)", border: "1px dashed var(--rule)" }}>
            No bills scored for this state yet.
          </div>
        ) : (
          <div style={{ borderTop: "1px solid var(--rule)" }}>
            {lensRows.map(l => (
              <LensRow
                key={l.id}
                lens={l}
                isActive={activeLens === l.id}
                onSelect={() => setActiveLens(l.id)}
              />
            ))}
          </div>
        )}
      </section>

      {/* BILLS for the active lens */}
      {activeRow && (
        <BillsForLens code={code} lens={activeRow} go={go} setLensId={setLensId} />
      )}
    </div>
  );
}

// --- Summary card — visual data at-a-glance ------------------------------
function SummaryCard({ code, name, totalBills, totalPassed, topLenses }) {
  // Compute aggregate party split across top 3 lenses
  const partyTotals = { D: 0, R: 0, other: 0 };
  let directionRestrict = 0;
  let directionExpand = 0;
  topLenses.forEach(l => {
    const sp = l.meta?.sponsor_party_by_direction || {};
    Object.entries(sp).forEach(([dir, parties]) => {
      Object.entries(parties).forEach(([p, n]) => {
        if (p === "D") partyTotals.D += n;
        else if (p === "R") partyTotals.R += n;
        else partyTotals.other += n;
      });
      if (dir === "expand") directionExpand += Object.values(parties).reduce((s,n)=>s+n,0);
      if (dir === "restrict") directionRestrict += Object.values(parties).reduce((s,n)=>s+n,0);
    });
  });
  const partyTotal = partyTotals.D + partyTotals.R + partyTotals.other;
  const dPct = partyTotal ? Math.round(100 * partyTotals.D / partyTotal) : 0;
  const rPct = partyTotal ? Math.round(100 * partyTotals.R / partyTotal) : 0;
  const oPct = Math.max(0, 100 - dPct - rPct);

  return (
    <div className="pl-summary-card">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <div>
          <div className="eyebrow">Bills tracked</div>
          <div className="display" style={{ fontSize: 36, marginTop: 4 }}>{totalBills.toLocaleString()}</div>
        </div>
        <div>
          <div className="eyebrow">Became law</div>
          <div className="display" style={{ fontSize: 36, marginTop: 4, color: "var(--accent)" }}>{totalPassed.toLocaleString()}</div>
        </div>
      </div>

      {topLenses.length > 0 && (
        <div style={{ marginTop: 18, paddingTop: 18, borderTop: "1px solid var(--rule)" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Most-active lenses</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {topLenses.map(l => {
              const color = window.PL_COLOR(l.passed).color;
              return (
                <div key={l.id} style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                    <span style={{ width: 8, height: 8, background: color, flexShrink: 0 }}></span>
                    <span style={{ fontSize: 13, fontFamily: "var(--display)", fontWeight: 600 }}>{l.label}</span>
                  </div>
                  <span className="mono tnum" style={{ fontSize: 11, color: "var(--ink-3)" }}>
                    {l.billCount} bills · {l.nPassed} passed
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {partyTotal > 0 && (
        <div style={{ marginTop: 18, paddingTop: 18, borderTop: "1px solid var(--rule)" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Bill sponsorship · top lenses</div>
          <div style={{ display: "flex", height: 8, overflow: "hidden" }}>
            {dPct > 0 && <div style={{ width: `${dPct}%`, background: "#3b82f6" }}></div>}
            {rPct > 0 && <div style={{ width: `${rPct}%`, background: "#dc2626" }}></div>}
            {oPct > 0 && <div style={{ width: `${oPct}%`, background: "var(--ink-4)" }}></div>}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6,
              fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.06em" }}>
            <span>D&nbsp;{dPct}%</span>
            <span>R&nbsp;{rPct}%</span>
            {oPct > 0 && <span>OTHER&nbsp;{oPct}%</span>}
          </div>
        </div>
      )}
    </div>
  );
}

// --- Single lens spectrum row --------------------------------------------
function LensRow({ lens, isActive, onSelect }) {
  const passedColor = window.PL_COLOR(lens.passed).color;
  return (
    <button onClick={onSelect}
      style={{
        display: "grid",
        gridTemplateColumns: "minmax(140px, 1.4fr) minmax(0, 3fr) minmax(70px, auto) minmax(60px, auto)",
        gap: 16, alignItems: "center",
        width: "100%",
        padding: "14px 10px",
        border: "none", borderBottom: "1px solid var(--rule)",
        background: isActive ? "var(--bg-2)" : "transparent",
        cursor: "pointer",
        textAlign: "left", color: "inherit", fontFamily: "inherit",
      }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
        <span style={{ fontFamily: "var(--display)", fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {lens.label}
        </span>
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.06em" }}>
          {lens.billCount} bills · {lens.nPassed} became law
        </span>
      </div>
      <div style={{ position: "relative", height: 22, background: "var(--bg-3)", minWidth: 0 }}>
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0,
          width: `${Math.max(2, lens.passed)}%`, background: passedColor,
          transition: "width 220ms ease" }}></div>
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0,
          width: `${Math.max(2, lens.pressure)}%`,
          border: "1.5px dashed var(--ink)",
          boxSizing: "border-box", pointerEvents: "none" }}></div>
        <div style={{ position: "absolute", left: "50%", top: -3, bottom: -3, width: 1,
          background: "var(--ink-4)" }}></div>
      </div>
      <div className="mono tnum" style={{ fontSize: 15, fontWeight: 600, textAlign: "right", color: passedColor }}>
        {lens.passed.toFixed(0)}
      </div>
      <div className="mono tnum" style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "right" }}>
        Δ{lens.pressure - lens.passed >= 0 ? "+" : ""}{(lens.pressure - lens.passed).toFixed(0)}
      </div>
    </button>
  );
}

// --- Featured bills for a lens (real data when available) ----------------
function BillsForLens({ code, lens, go, setLensId }) {
  const [bills, setBills] = React.useState(null);
  React.useEffect(() => {
    setBills(null);
    billsFor(code, lens.id, { limit: 20 }).then(setBills);
  }, [code, lens.id]);

  return (
    <section style={{ padding: "32px clamp(24px, 4vw, 64px) 64px", borderTop: "1px solid var(--rule)" }}>
      <div style={{ display: "flex", gap: 16, marginBottom: 24, alignItems: "baseline", flexWrap: "wrap" }}>
        <div className="eyebrow">{code} · {lens.label}</div>
        <h2 className="display" style={{ fontSize: 32, margin: 0 }}>
          {lens.billCount} bills · {lens.nPassed} became law
        </h2>
        <button className="btn btn-ghost" style={{ marginLeft: "auto" }}
          onClick={() => { setLensId(lens.id); go("lens"); }}>
          Compare across all states →
        </button>
      </div>

      {bills === null && <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>Loading bills…</div>}
      {bills && bills.length === 0 && (
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>No bills available for this lens yet.</div>
      )}
      {bills && bills.length > 0 && (
        <div className="pl-bill-cards">
          {bills.slice(0, 12).map(b => <BillCard key={b.bill_number} bill={b} />)}
        </div>
      )}
    </section>
  );
}

function BillCard({ bill }) {
  const lensScores = bill.lens_scores || [];
  const primaryDirection = lensScores[0]?.direction || "neutral";
  const dirColor = primaryDirection === "expand" ? "#2a6b66" : primaryDirection === "restrict" ? "#b85a4a" : "var(--ink-4)";
  return (
    <div className="pl-bill-card">
      <div style={{ display: "flex", gap: 8, alignItems: "baseline", marginBottom: 8 }}>
        <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{bill.bill_number}</span>
        <span className={`pill pill-${(bill.status_label || "").toLowerCase()}`}>{bill.status_label}</span>
        {bill.legislative_character && (
          <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: "0.04em",
            textTransform: "uppercase" }}>
            {bill.legislative_character.replace(/_/g, " ")}
          </span>
        )}
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.4, color: "var(--ink)", marginBottom: 8 }}>
        {bill.title}
      </div>
      {bill.summary && (
        <div style={{ fontSize: 12, lineHeight: 1.5, color: "var(--ink-2)", marginBottom: 10, fontStyle: "italic" }}>
          {bill.summary}
        </div>
      )}
      {lensScores.length > 0 && (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {lensScores.slice(0, 4).map((ls, i) => (
            <span key={i} style={{
              fontFamily: "var(--mono)", fontSize: 10,
              padding: "3px 7px",
              border: "1px solid var(--rule)",
              color: "var(--ink-2)",
            }}>
              <span>{ls.lens.replace(/_/g, " ")}</span>
              <span style={{ color: dirColor, marginLeft: 6, fontWeight: 600 }}>
                {ls.direction === "expand" ? "↑" : ls.direction === "restrict" ? "↓" : "·"}
                {(ls.magnitude || "")[0]?.toUpperCase() || ""}
              </span>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// --- Editorial finding builder (data-driven, simple) ---------------------
function buildFinding(stateName, lensRows) {
  if (lensRows.length === 0) {
    return `${stateName} has no scored bills yet for the lenses we track. Pipeline is filling in — check back as more states are added.`;
  }
  const top = lensRows[0];
  const score = top.passed;
  const direction = score >= 60 ? "expanding" : score < 40 ? "restricting" : "evenly split on";
  const verb = top.nPassed === 0 ? "introduced" : "passed";
  return `${stateName}'s most-active lens this session is ${top.label.toLowerCase()} — ${top.billCount} bills tracked, ${top.nPassed} became law. The lawmaking is ${direction} ${top.label.toLowerCase()}.`;
}

window.PL_StatePage = StatePage;
}
