/* === Power map — state-by-state primary, national roll-up secondary === */

const STRENGTH_STYLE = {
  "strong":         { bar: 0.92, fg: "var(--green)",  label: "Strong" },
  "medium":         { bar: 0.6,  fg: "var(--ink-2)",  label: "Medium" },
  "medium-late":    { bar: 0.5,  fg: "var(--yellow)", label: "Medium — late mobilization" },
  "weak":           { bar: 0.25, fg: "var(--ink-mute)", label: "Weak" },
  "weak-strategic": { bar: 0.3,  fg: "var(--ink-mute)", label: "Weak — strategic" },
  "weak-neutral":   { bar: 0.2,  fg: "var(--ink-mute)", label: "Weak — neutral" },
};

function PowerMap() {
  const states = Object.keys(window.POWER_MAP_STATES);
  const [active, setActive] = React.useState(states[0]);

  // Tab summary counts
  const allSponsors = Object.values(window.POWER_MAP_STATES).reduce((n, s) => n + s.sponsors.length, 0);
  const allSupporters = Object.values(window.POWER_MAP_STATES).reduce((n, s) => n + s.supporters.length, 0);
  const allOpposers = Object.values(window.POWER_MAP_STATES).reduce((n, s) => n + s.opposers.length, 0);
  const allCommittees = Object.values(window.POWER_MAP_STATES).reduce((n, s) => n + s.committees.length, 0);

  return (
    <div>
      <div className="tab-summary">
        <SumStat label="States with data" value={states.length} />
        <SumStat label="Sponsors tracked" value={allSponsors} muted />
        <SumStat label="Committees tracked" value={allCommittees} muted />
        <SumStat label="Supporters tracked" value={allSupporters} accent="green" />
        <SumStat label="Opposers tracked" value={allOpposers} accent="red" />
      </div>

      <div className="card" style={{ padding: 0, marginBottom: 28 }}>
        <PowerMapState abbr={active} allStates={states} setActive={setActive} />
      </div>

      <div className="section-head">
        <div>
          <div className="section-title">National roll-up</div>
          <div className="section-sub">Shared entities — each org/figure exists once, referenced from many states.</div>
        </div>
      </div>
      <NationalRollup />
    </div>
  );
}

function programPillStyle(program) {
  if (program === "live")    return { color: "white",         background: "var(--navy)" };
  if (program === "enacted") return { color: "white",         background: "var(--navy-soft)" };
  return                            { color: "var(--ink-2)",  background: "var(--surface-3)" };
}

function StatePickerHeader({ abbr, allStates, setActive }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState("");
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDoc); document.removeEventListener("keydown", onKey); };
  }, [open]);

  const j = window.JURISDICTIONS[abbr];
  const name = window.STATE_NAMES[abbr];
  const pillStyle = programPillStyle(j?.program);

  const filtered = allStates.filter((s) => {
    if (!q) return true;
    const ql = q.toLowerCase();
    const nm = (window.STATE_NAMES[s] || s).toLowerCase();
    const lb = (window.JURISDICTIONS[s]?.label || "").toLowerCase();
    return s.toLowerCase().includes(ql) || nm.includes(ql) || lb.includes(ql);
  });

  return (
    <div ref={ref} style={{ position: "relative", minWidth: 0, flex: "0 1 460px" }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          display: "flex", alignItems: "center", gap: 14,
          padding: "6px 12px 6px 6px", borderRadius: 6,
          border: "1px solid transparent", background: "transparent",
          cursor: "pointer", textAlign: "left", width: "100%",
          transition: "background .12s, border-color .12s",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-2)"; e.currentTarget.style.borderColor = "var(--border)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.borderColor = "transparent"; }}
      >
        <span style={{
          fontFamily: "var(--mono)", fontWeight: 700, fontSize: 18,
          padding: "8px 12px", borderRadius: 5,
          letterSpacing: ".02em",
          minWidth: 52, textAlign: "center",
          ...pillStyle,
        }}>{abbr}</span>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 600, letterSpacing: "-.012em", lineHeight: 1.1 }}>{name}</div>
          <div className="mono faint" style={{ fontSize: 12, marginTop: 4 }}>
            {j?.label || "—"}
          </div>
        </div>
        <span style={{ color: "var(--ink-mute)", fontSize: 14, marginLeft: 4 }}>▾</span>
      </button>

      {open ? (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, width: "min(440px, 100%)",
          background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 6,
          boxShadow: "var(--shadow-pop)", zIndex: 30, overflow: "hidden",
        }}>
          <div style={{ padding: 10, borderBottom: "1px solid var(--rule)" }}>
            <input
              autoFocus
              type="text"
              value={q}
              placeholder="Filter by state name or program label…"
              onChange={(e) => setQ(e.target.value)}
              style={{
                width: "100%", padding: "7px 10px", borderRadius: 4,
                border: "1px solid var(--border)", background: "var(--surface-2)",
                font: "500 12px/1.2 var(--mono)", color: "var(--ink)",
                outline: "none",
              }}
            />
          </div>
          <div style={{ maxHeight: 360, overflowY: "auto" }}>
            {filtered.length === 0 ? (
              <div style={{ padding: 12, color: "var(--ink-mute)", fontSize: 12 }}>No states match.</div>
            ) : filtered.map((s) => {
              const jj = window.JURISDICTIONS[s];
              const ps = programPillStyle(jj?.program);
              return (
                <button key={s}
                        onClick={() => { setActive(s); setOpen(false); setQ(""); }}
                        style={{
                          width: "100%", display: "flex", alignItems: "center", gap: 10,
                          padding: "8px 12px",
                          background: s === abbr ? "var(--surface-2)" : "transparent",
                          border: 0, textAlign: "left", cursor: "pointer",
                          borderBottom: "1px solid var(--rule)",
                        }}>
                  <span style={{
                    fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600,
                    padding: "2px 6px", borderRadius: 3,
                    minWidth: 32, textAlign: "center",
                    ...ps,
                  }}>{s}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{window.STATE_NAMES[s]}</div>
                    <div className="mono faint" style={{ fontSize: 11 }}>{jj?.label || "—"}</div>
                  </div>
                  {jj?.trifecta ? <Chip kind={jj.trifecta === "R" ? "red" : "navy"}>{jj.trifecta}-trifecta</Chip> : null}
                </button>
              );
            })}
          </div>
        </div>
      ) : null}
    </div>
  );
}

function PowerMapState({ abbr, allStates, setActive }) {
  const data = window.POWER_MAP_STATES[abbr];
  const j = window.JURISDICTIONS[abbr];
  if (!data) return null;

  return (
    <div style={{ padding: 18 }}>
      {/* State header — abbreviation pill + state name lead the picker; party control to the right */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, marginBottom: 18 }}>
        <StatePickerHeader abbr={abbr} allStates={allStates} setActive={setActive} />
        <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
          <span className="eyebrow" style={{ marginRight: 4 }}>Party control</span>
          <PartyChip label="Gov" party={j.govParty} />
          <PartyChip label="House" party={j.houseParty} />
          <PartyChip label="Senate" party={j.senateParty} />
          {j.trifecta ? <Chip kind={j.trifecta === "R" ? "red" : "navy"}>{j.trifecta}-trifecta</Chip> : <Chip kind="ghost">Divided</Chip>}
        </div>
      </div>

      {data.summary ? (
        <div style={{
          padding: "12px 14px", borderLeft: "3px solid var(--accent)",
          background: "var(--surface-2)", fontFamily: "var(--serif)", fontSize: 14,
          lineHeight: 1.5, color: "var(--ink-2)", borderRadius: "0 4px 4px 0",
          marginBottom: 18,
        }}>
          {data.summary}
        </div>
      ) : null}

      <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 22 }}>
        {/* Left: Sponsors + Committees */}
        <div>
          <PMSection title="Sponsors" count={data.sponsors.length}>
            {data.sponsors.map((s, i) => <SponsorCard key={i} s={s} />)}
          </PMSection>
          <div style={{ marginTop: 18 }}>
            <PMSection title="Committees of jurisdiction" count={data.committees.length}>
              {data.committees.map((c, i) => <CommitteeRow key={i} c={c} />)}
            </PMSection>
          </div>
        </div>

        {/* Right: Supporters / Opposers */}
        <div>
          <PMSection title="Supporters" count={data.supporters.length} accent="green">
            {data.supporters.map((o, i) => <ActorCard key={i} o={o} kind="support" />)}
          </PMSection>
          <div style={{ marginTop: 18 }}>
            <PMSection title="Opposers" count={data.opposers.length} accent="red">
              {data.opposers.map((o, i) => <ActorCard key={i} o={o} kind="oppose" />)}
            </PMSection>
          </div>
        </div>
      </div>
    </div>
  );
}

function PMSection({ title, count, accent, children }) {
  const dotColor = accent === "green" ? "var(--green)" : accent === "red" ? "var(--red)" : "var(--ink-mute)";
  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 10, paddingBottom: 6, borderBottom: "1px solid var(--rule)" }}>
        <span style={{ width: 6, height: 6, borderRadius: 99, background: dotColor }}></span>
        <span style={{ fontFamily: "var(--serif)", fontSize: 14, fontWeight: 600 }}>{title}</span>
        <span className="mono faint" style={{ fontSize: 11 }}>{count}</span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{children}</div>
    </div>
  );
}

function SponsorCard({ s }) {
  return (
    <div style={{
      padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 5,
      background: "var(--surface)",
      borderLeft: `3px solid ${s.party === "R" ? "var(--red)" : "var(--navy)"}`,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{s.name}</div>
          <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 2 }}>{s.role}</div>
        </div>
        <PartyChip label="" party={s.party} />
      </div>
      <div style={{ marginTop: 8, display: "grid", gridTemplateColumns: "auto auto auto", gap: "4px 14px", alignItems: "center" }}>
        <Stat label="Terms" value={s.terms} />
        <Stat label="Passage rate" value={`${Math.round(s.passRate * 100)}%`} />
        <Stat label="Bills" value={s.bills.join(", ")} />
      </div>
      {s.strength ? (
        <div style={{ marginTop: 8 }}>
          <StrengthBar strength={s.strength} label="Influence" />
        </div>
      ) : null}
      {s.note ? (
        <div style={{ marginTop: 8, fontSize: 12, color: "var(--ink-2)", fontStyle: "italic", lineHeight: 1.5 }}>
          {s.note}
        </div>
      ) : null}
    </div>
  );
}

function CommitteeRow({ c }) {
  return (
    <div style={{ padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 5, background: "var(--surface)" }}>
      <div style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</div>
      <div style={{ marginTop: 6, display: "flex", gap: 14, flexWrap: "wrap", fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)" }}>
        <span><span className="eyebrow" style={{ marginRight: 4 }}>Chair</span>{c.chair}</span>
        <span><span className="eyebrow" style={{ marginRight: 4 }}>Ranking</span>{c.rankingMember}</span>
      </div>
      {c.role ? <div style={{ marginTop: 6, fontSize: 12, color: "var(--ink-2)", fontStyle: "italic" }}>{c.role}</div> : null}
    </div>
  );
}

function ActorCard({ o, kind }) {
  return (
    <div style={{
      padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 5,
      background: "var(--surface)",
      borderLeft: `3px solid ${kind === "support" ? "var(--green)" : "var(--red)"}`,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
        <div style={{ fontWeight: 600, fontSize: 13 }}>{o.name}</div>
      </div>
      {o.lead ? <div style={{ fontSize: 11, color: "var(--ink-2)", marginTop: 2 }}>Lead: {o.lead}</div> : null}
      <div style={{ marginTop: 8 }}>
        <StrengthBar strength={o.strength} label="Strength in state" />
      </div>
      {o.note ? <div style={{ marginTop: 8, fontSize: 12, color: "var(--ink-2)", fontStyle: "italic", lineHeight: 1.5 }}>{o.note}</div> : null}
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <>
      <span className="eyebrow">{label}</span>
      <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)", fontWeight: 500, gridColumn: "span 2" }}>{value}</span>
    </>
  );
}

function StrengthBar({ strength, label }) {
  const map = STRENGTH_STYLE[strength] || STRENGTH_STYLE.medium;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
        <span className="eyebrow">{label}</span>
        <span className="mono" style={{ fontSize: 10, color: map.fg, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".1em" }}>{map.label}</span>
      </div>
      <div style={{ height: 4, background: "var(--surface-3)", borderRadius: 99, overflow: "hidden" }}>
        <div style={{ width: `${map.bar * 100}%`, height: "100%", background: map.fg }}></div>
      </div>
    </div>
  );
}

function NationalRollup() {
  const orgs = window.ORGS;
  const byKind = {
    supporter: orgs.filter(o => o.kind === "supporter"),
    opposer:   orgs.filter(o => o.kind === "opposer"),
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
      <RollupCol title="Supporters" items={byKind.supporter} cls="support" />
      <RollupCol title="Opposers"    items={byKind.opposer}   cls="oppose"  />
    </div>
  );
}
function RollupCol({ title, items, cls }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 14, fontWeight: 600 }}>{title}</div>
        <div className="mono faint" style={{ fontSize: 11 }}>{items.length} shared entities</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {items.map(o => (
          <div key={o.id} className={`pm-org pm-org--${cls}`} style={{ marginBottom: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
              <div>
                <div className="pm-org__name">{o.name}</div>
                <div className="pm-org__role">{o.role}</div>
                {o.lead ? <div style={{ fontSize: 11, color: "var(--ink-2)", marginTop: 2 }}>Lead: {o.lead}</div> : null}
              </div>
              <div className="mono faint" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".1em" }}>{o.states.length} states</div>
            </div>
            <div className="pm-org__states">
              {o.states.slice(0, 10).map(s => <span className="pm-org__state" key={s}>{s}</span>)}
              {o.states.length > 10 ? <span className="pm-org__state">+{o.states.length - 10}</span> : null}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { PowerMap });
