/* === Jurisdiction side panel (right-side drawer when a state is clicked) === */

/* Engagement types per stakeholder feedback: indicates HOW the project is
   engaged in a jurisdiction. A tag, not a lobbying record — the LDA system
   of record stays in Salesforce (spec §12). */
const ENGAGEMENT_TYPES = [
  { id: "ta",          label: "Technical assistance",            short: "TA" },
  { id: "lobbying",    label: "Lobbying",                        short: "LOB" },
  { id: "lobbying-ga", label: "Lobbying — contractor / GA firm", short: "LOB·GA" },
  { id: "events",      label: "Events / other",                  short: "EVT" },
];

function EngagementChips({ list, small = false }) {
  if (!list || !list.length) return <span className="mono faint" style={{ fontSize: 11 }}>—</span>;
  return (
    <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
      {list.map((id) => {
        const t = ENGAGEMENT_TYPES.find((x) => x.id === id);
        return <Chip key={id} kind="accent" title={t ? t.label : id}>{small ? (t ? t.short : id) : (t ? t.label : id)}</Chip>;
      })}
    </div>
  );
}

function JurisdictionPanel({ abbr, onClose }) {
  if (!abbr) return <div className="scrim"></div>;
  const j = window.JURISDICTIONS[abbr];
  const name = window.STATE_NAMES[abbr] || abbr;
  if (!j) return null;

  const billsHere = window.BILLS.filter(b => b.state === abbr);

  const programLabel = { live: "Active program (live)", enacted: "Enacted — implementing", none: "No program" }[j.program];
  const legLabel = {
    "enacted-session": "Enacted this session",
    "active":          "Active legislation",
    "recent":          "Recent legislation",
    "none":            "No legislation this session",
  }[j.legActivity];

  // Program: 2 segments (enacted → live), hide if none
  const programIdx = { none: 0, enacted: 1, live: 2 }[j.program];
  // Legislation: 3 segments (recent → active → enacted), hide if none
  const legIdx = { none: 0, recent: 1, active: 2, "enacted-session": 3 }[j.legActivity];

  // Find related milestones (numeric — first 3 mentions feasible)
  const relMilestones = window.MILESTONES.filter(m => {
    if (m.id === "M-01" && (j.program === "live" || j.legActivity === "enacted-session" || j.legActivity === "active")) return true;
    if (m.id === "M-06" && j.redLed && j.legActivity !== "none") return true;
    if (m.id === "M-10" && j.program === "live") return true;
    return false;
  });

  // Power map sliver — orgs that reference this state
  const relOrgs = window.ORGS.filter(o => o.states.includes(abbr)).slice(0, 6);

  return (
    <>
      <div className={`scrim is-open`} onClick={onClose}></div>
      <aside className={`side-panel is-open`}>
        <div className="side-panel__head">
          <button className="side-panel__close" onClick={onClose} title="Close">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" /></svg>
          </button>
          <div className="side-panel__eyebrow">Jurisdiction · {abbr}</div>
          <div className="side-panel__title">{name}</div>
          <div className="side-panel__subtitle">{j.label || "—"}</div>
          <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span className="eyebrow">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>

        {/* Two-axis status block */}
        <div className="side-panel__section">
          <h4>Status</h4>
          <div className="status-block">
            <div className="status-block__cell">
              <div className="status-block__label">Program maturity</div>
              <div className="status-block__value">{programLabel}</div>
              {j.program !== "none" ? (
                <>
                  <div className="status-block__rail">
                    <span className={programIdx >= 1 ? "is-on" : ""}></span>
                    <span className={programIdx >= 2 ? "is-on" : ""}></span>
                  </div>
                  <div className="mono faint" style={{ fontSize: 10, marginTop: 6 }}>enacted → live</div>
                </>
              ) : null}
            </div>
            <div className="status-block__cell">
              <div className="status-block__label">Legislative activity (this session)</div>
              <div className="status-block__value">{legLabel}</div>
              {j.legActivity !== "none" ? (
                <>
                  <div className="status-block__rail">
                    <span className={legIdx >= 1 ? "is-on" : ""}></span>
                    <span className={legIdx >= 2 ? "is-on" : ""}></span>
                    <span className={legIdx >= 3 ? "is-on" : ""}></span>
                  </div>
                  <div className="mono faint" style={{ fontSize: 10, marginTop: 6 }}>recent → active → enacted</div>
                </>
              ) : null}
            </div>
          </div>
        </div>

        {/* Engagement type */}
        <div className="side-panel__section">
          <h4>Project engagement</h4>
          <EngagementChips list={j.engagement} />
        </div>

        {/* Admin editing */}
        <JurisdictionEditSection abbr={abbr} j={j} />

        {/* Bills */}
        <div className="side-panel__section">
          <h4>Legislative items ({billsHere.length})</h4>
          {billsHere.length === 0 && <div className="muted" style={{ fontSize: 12 }}>No tracked bills this session.</div>}
          {billsHere.map(b => (
            <div className="bill-row" key={b.id}>
              <div className="bill-row__hd">
                <span className="bill-row__id">{b.state} {b.bill}</span>
                <span className="bill-row__status">{b.status}</span>
              </div>
              <div className="bill-row__title">{b.title}</div>
              <div className="bill-row__meta">
                <Chip kind="soft"><span className="chip__dot" style={{ background: b.party === "R" ? "var(--red)" : b.party === "D" ? "var(--navy)" : "var(--ink-mute)" }}></span>{b.party === "R" ? "Republican" : b.party === "D" ? "Democrat" : "Non-designated"}</Chip>
                <Chip kind="ghost">intro {b.intro}</Chip>
                <span className="mono faint" style={{ fontSize: 11 }}>Quorum · {b.id}</span>
              </div>
            </div>
          ))}
        </div>

        {/* Linked milestones / ODA */}
        <div className="side-panel__section">
          <h4>Linked milestones & ODA</h4>
          {relMilestones.length === 0 ? (
            <div className="muted" style={{ fontSize: 12 }}>No primary milestone links for this jurisdiction yet.</div>
          ) : relMilestones.map(m => (
            <div key={m.id} style={{ padding: "8px 0", borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", gap: 8 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)", display: "flex", gap: 6, alignItems: "baseline" }}>
                  <span className="mono faint" style={{ fontSize: 11 }}>{m.id}</span>
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.title}</span>
                </div>
                <div style={{ marginTop: 4, display: "flex", gap: 4, flexWrap: "wrap" }}>
                  {m.oda.map(id => <ODAChip key={id} id={id} />)}
                </div>
              </div>
              <RagBadge rag={m.rag} />
            </div>
          ))}
        </div>

        {/* Power map sliver */}
        <div className="side-panel__section">
          <h4>Power map — actors</h4>
          {relOrgs.length === 0 ? (
            <div className="muted" style={{ fontSize: 12 }}>No tracked actors here yet.</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {relOrgs.map(o => (
                <div key={o.id} className={`pm-org pm-org--${o.kind === "supporter" ? "support" : o.kind === "opposer" ? "oppose" : o.kind}`} 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>
                    </div>
                    <span className="mono faint" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".1em" }}>{o.kind}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          <div style={{ marginTop: 10 }}>
            <a className="btn btn--ghost" style={{ padding: "4px 8px", fontSize: 12 }}>Open full power map for {abbr} →</a>
          </div>
        </div>
      </aside>
    </>
  );
}

/* Admin-only editor: both status axes, program label, engagement tags.
   Saves as one event; history visible below. */
function JurisdictionEditSection({ abbr, j }) {
  const me = window.Store.session();
  const canEdit = !!(me && me.role === "admin");

  const [program, setProgram] = React.useState(j.program);
  const [leg, setLeg] = React.useState(j.legActivity);
  const [label, setLabel] = React.useState(j.label || "");
  const [engagement, setEngagement] = React.useState(j.engagement || []);
  const [gaFirm, setGaFirm] = React.useState(j.gaFirm || "");
  const [grNote, setGrNote] = React.useState(j.grNote || "");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  React.useEffect(() => {
    setProgram(j.program); setLeg(j.legActivity);
    setLabel(j.label || ""); setEngagement(j.engagement || []);
    setGaFirm(j.gaFirm || ""); setGrNote(j.grNote || ""); setErr(null);
  }, [abbr]);

  if (!canEdit) {
    return (
      <div className="side-panel__section">
        <EntityHistory type="jurisdiction" id={abbr} label="Change history" />
      </div>
    );
  }

  const dirty = program !== j.program || leg !== j.legActivity ||
    label !== (j.label || "") || gaFirm !== (j.gaFirm || "") || grNote !== (j.grNote || "") ||
    JSON.stringify(engagement) !== JSON.stringify(j.engagement || []);

  const toggleEng = (id) =>
    setEngagement(engagement.includes(id) ? engagement.filter((x) => x !== id) : [...engagement, id]);

  async function save() {
    setBusy(true); setErr(null);
    const patch = {}, prev = {};
    if (program !== j.program) { patch.program = program; prev.program = j.program; }
    if (leg !== j.legActivity) { patch.legActivity = leg; prev.legActivity = j.legActivity; }
    if (label !== (j.label || "")) { patch.label = label || null; prev.label = j.label || null; }
    if (JSON.stringify(engagement) !== JSON.stringify(j.engagement || [])) {
      patch.engagement = engagement; prev.engagement = j.engagement || [];
    }
    if (gaFirm !== (j.gaFirm || "")) { patch.gaFirm = gaFirm || null; prev.gaFirm = j.gaFirm || null; }
    if (grNote !== (j.grNote || "")) { patch.grNote = grNote || null; prev.grNote = j.grNote || null; }
    try {
      await window.Store.commit({ entityType: "jurisdiction", entityId: abbr, action: "update", patch, prev });
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setBusy(false);
    }
  }

  const sel = {
    width: "100%", padding: "6px 8px", borderRadius: 4, border: "1px solid var(--border)",
    background: "var(--surface)", font: "500 12px/1.2 var(--mono)", outline: "none",
  };

  return (
    <div className="side-panel__section">
      <h4>Edit jurisdiction (admin)</h4>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Program maturity</div>
          <select style={sel} value={program} onChange={(e) => setProgram(e.target.value)}>
            <option value="none">none</option>
            <option value="enacted">enacted · implementing</option>
            <option value="live">active program (live)</option>
          </select>
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 4 }}>Legislative activity</div>
          <select style={sel} value={leg} onChange={(e) => setLeg(e.target.value)}>
            <option value="none">none</option>
            <option value="recent">recent (prior session)</option>
            <option value="active">active this session</option>
            <option value="enacted-session">enacted this session</option>
          </select>
        </div>
      </div>
      <div style={{ marginTop: 10 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>Program label</div>
        <input style={{ ...sel, fontFamily: "var(--sans)", fontSize: 13 }} value={label}
               onChange={(e) => setLabel(e.target.value)} placeholder="e.g. OregonSaves" />
      </div>
      <div style={{ marginTop: 10 }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>Engagement type</div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {ENGAGEMENT_TYPES.map((t) => (
            <button key={t.id} type="button" onClick={() => toggleEng(t.id)}
              className={`chip ${engagement.includes(t.id) ? "chip--accent" : "chip--ghost"}`}
              style={{ cursor: "pointer" }} title={t.label}>
              {t.label}
            </button>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 10 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>GA firm (drives GR lane; contract status matched from CAPS by vendor name)</div>
        <input style={{ ...sel, fontFamily: "var(--sans)", fontSize: 13 }} value={gaFirm}
               onChange={(e) => setGaFirm(e.target.value)} placeholder="e.g. Dykema" />
      </div>
      <div style={{ marginTop: 10 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>GR status note (the narrative line for the GR check-in report)</div>
        <textarea rows={3} value={grNote} onChange={(e) => setGrNote(e.target.value)}
          placeholder="e.g. Bills passed Senate in June; potential lame duck strategy after mid-terms."
          style={{ ...sel, fontFamily: "var(--sans)", fontSize: 13, lineHeight: 1.5, resize: "vertical" }} />
      </div>
      {err ? (
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 4, background: "var(--red-bg)", color: "var(--red)", fontSize: 12 }}>{err}</div>
      ) : null}
      {dirty ? (
        <div className="row" style={{ marginTop: 12, gap: 8 }}>
          <button className="btn btn--primary" disabled={busy} onClick={save}>{busy ? "Saving…" : "Save changes"}</button>
          <button className="btn btn--ghost" onClick={() => {
            setProgram(j.program); setLeg(j.legActivity); setLabel(j.label || ""); setEngagement(j.engagement || []);
          }}>Cancel</button>
        </div>
      ) : null}
      <div style={{ marginTop: 14 }}>
        <EntityHistory type="jurisdiction" id={abbr} label="Change history" />
      </div>
    </div>
  );
}

Object.assign(window, { JurisdictionPanel, ENGAGEMENT_TYPES, EngagementChips });
