/* === Admin — cycle metadata, bulk import, data reset ===
   Visible to admins only. The reset exists to clear placeholder/seed data
   before real population: entities are cleared selectively, jurisdictions
   are blanked (not deleted), users and the event log always survive. */

const CLEARABLE = [
  { type: "work",      label: "Work items",                hint: "recreate via + New work item" },
  { type: "milestone", label: "Milestones",                hint: "recreate via + New milestone or JSON import" },
  { type: "oda",       label: "ODA tree",                  hint: "no in-app editor yet — repopulate via JSON import" },
  { type: "bill",      label: "Bills",                     hint: "repopulate via Quorum upload" },
  { type: "powermap",  label: "Power map — state records", hint: "editor coming" },
  { type: "org",       label: "Power map — shared orgs",   hint: "editor coming" },
  { type: "contract",  label: "Contracts (executed)",      hint: "CAPS refresh coming" },
  { type: "pending",   label: "Contracts (pending in CAPS)", hint: "" },
  { type: "changes",   label: "What's-changed items",      hint: "live feed coming" },
];

function AdminPanel() {
  const me = window.Store.session();
  if (!me || me.role !== "admin") {
    return <div className="muted" style={{ fontSize: 13 }}>Admins only.</div>;
  }
  // The destructive reset is deliberately NOT reachable by clicking around:
  // it only renders with ?danger=1 in the URL (plus the typed confirmation),
  // so it can't be hit by accident. Documented in DEPLOY.md.
  const showDanger = new URLSearchParams(location.search).get("danger") === "1";
  return (
    <div style={{ maxWidth: 760 }}>
      <CycleMeta />
      <ImportBox />
      {showDanger ? <ResetBox /> : null}
    </div>
  );
}

function CycleMeta() {
  const [fy, setFy] = React.useState(window.FY || "");
  const [asof, setAsof] = React.useState(window.ASOF || "");
  const [busy, setBusy] = React.useState(false);
  const dirty = fy !== (window.FY || "") || asof !== (window.ASOF || "");
  const input = {
    width: "100%", padding: "7px 10px", borderRadius: 4, border: "1px solid var(--border)",
    background: "var(--surface-2)", font: "500 13px/1.3 var(--sans)", outline: "none",
  };
  async function save() {
    setBusy(true);
    try {
      await window.Store.commit({
        entityType: "meta", entityId: "app", action: "update",
        patch: { FY: fy, ASOF: asof }, prev: { FY: window.FY, ASOF: window.ASOF },
      });
    } finally { setBusy(false); }
  }
  return (
    <div className="card" style={{ marginBottom: 20 }}>
      <div className="card__head"><h3>Cycle</h3></div>
      <div className="card__body">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Fiscal year label</div>
            <input style={input} value={fy} onChange={(e) => setFy(e.target.value)} placeholder="FY 2027" />
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>"As of" date line</div>
            <input style={input} value={asof} onChange={(e) => setAsof(e.target.value)} placeholder="July 16, 2026" />
          </div>
        </div>
        {dirty ? (
          <button className="btn btn--primary" style={{ marginTop: 12 }} disabled={busy} onClick={save}>
            {busy ? "Saving…" : "Save"}
          </button>
        ) : null}
      </div>
    </div>
  );
}

function ImportBox() {
  const [text, setText] = React.useState("");
  const [msg, setMsg] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  async function run() {
    setBusy(true); setMsg(null);
    try {
      const n = await window.Store.importEntities(JSON.parse(text));
      setMsg({ ok: true, text: `Imported ${n} entities.` });
      setText("");
    } catch (e) {
      setMsg({ ok: false, text: String(e.message || e) });
    } finally { setBusy(false); }
  }
  return (
    <div className="card" style={{ marginBottom: 20 }}>
      <div className="card__head">
        <div>
          <h3>Bulk import (JSON)</h3>
          <div className="section-sub">For structured loads — e.g. the current ODA tree + milestone set encoded from the board docs. Format: {"{ \"entities\": { \"milestone\": [{ \"id\": \"M-01\", \"data\": { … } }] } }"}</div>
        </div>
      </div>
      <div className="card__body">
        <textarea rows={5} value={text} onChange={(e) => setText(e.target.value)}
          placeholder='{"entities": {"oda": [...], "milestone": [...]}}'
          style={{ width: "100%", padding: "8px 10px", borderRadius: 4, border: "1px solid var(--border)", background: "var(--surface-2)", font: "400 12px/1.5 var(--mono)", outline: "none", resize: "vertical" }} />
        {msg ? (
          <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 4, fontSize: 12, background: msg.ok ? "var(--green-bg)" : "var(--red-bg)", color: msg.ok ? "var(--green)" : "var(--red)" }}>{msg.text}</div>
        ) : null}
        <button className="btn" style={{ marginTop: 10 }} disabled={busy || !text.trim()} onClick={run}>
          {busy ? "Importing…" : "Import"}
        </button>
      </div>
    </div>
  );
}

function ResetBox() {
  const [checked, setChecked] = React.useState({});
  const [resetJur, setResetJur] = React.useState(false);
  const [confirm, setConfirm] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState(null);

  const types = CLEARABLE.filter((c) => checked[c.type]).map((c) => c.type);
  const anything = types.length > 0 || resetJur;
  const armed = confirm.trim().toUpperCase() === "RESET";

  const counts = {
    work: window.WORK_ITEMS.length, milestone: window.MILESTONES.length,
    oda: window.ODA.length, bill: window.BILLS.length,
    powermap: Object.keys(window.POWER_MAP_STATES).length, org: window.ORGS.length,
    contract: window.CONTRACTS.length, pending: (window.PENDING_CONTRACTS || []).length,
    changes: window.CHANGES.wins.length + window.CHANGES.risks.length + window.CHANGES.blocked.length,
  };

  async function run() {
    setBusy(true); setMsg(null);
    try {
      await window.Store.resetData({ types, resetJurisdictions: resetJur });
      setMsg({ ok: true, text: "Cleared. Users and the edit history are untouched — start populating." });
      setChecked({}); setResetJur(false); setConfirm("");
    } catch (e) {
      setMsg({ ok: false, text: String(e.message || e) });
    } finally { setBusy(false); }
  }

  return (
    <div className="card" style={{ borderColor: "oklch(0.78 0.08 26)" }}>
      <div className="card__head">
        <div>
          <h3 style={{ color: "var(--red)" }}>Data reset</h3>
          <div className="section-sub">Clear placeholder/seed data before real population. Accounts and the edit history always survive; jurisdictions are blanked, never deleted. This cannot be undone.</div>
        </div>
        <button className="btn btn--ghost" style={{ fontSize: 11 }}
          onClick={() => setChecked(Object.fromEntries(CLEARABLE.map((c) => [c.type, true]))) || setResetJur(true)}>
          Select everything
        </button>
      </div>
      <div className="card__body">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 20px" }}>
          {CLEARABLE.map((c) => (
            <label key={c.type} className="row" style={{ gap: 8, fontSize: 13, cursor: "pointer", userSelect: "none", alignItems: "baseline" }}>
              <input type="checkbox" checked={!!checked[c.type]}
                     onChange={(e) => setChecked({ ...checked, [c.type]: e.target.checked })} />
              <span>
                {c.label} <span className="mono faint" style={{ fontSize: 10 }}>({counts[c.type]})</span>
                {c.hint ? <span className="muted" style={{ fontSize: 11, display: "block" }}>{c.hint}</span> : null}
              </span>
            </label>
          ))}
          <label className="row" style={{ gap: 8, fontSize: 13, cursor: "pointer", userSelect: "none", alignItems: "baseline" }}>
            <input type="checkbox" checked={resetJur} onChange={(e) => setResetJur(e.target.checked)} />
            <span>
              Reset all jurisdiction statuses to blank
              <span className="muted" style={{ fontSize: 11, display: "block" }}>program, legislation, engagement, labels, notes → none; the 50 states + DC remain</span>
            </span>
          </label>
        </div>

        {anything ? (
          <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--rule)" }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Type RESET to confirm</div>
            <div className="row" style={{ gap: 10 }}>
              <input value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="RESET"
                style={{ width: 120, padding: "7px 10px", borderRadius: 4, border: "1px solid var(--border)", background: "var(--surface-2)", font: "600 13px/1 var(--mono)", letterSpacing: ".15em", outline: "none", textAlign: "center" }} />
              <button className="btn" disabled={!armed || busy}
                style={armed ? { background: "var(--red)", color: "white", borderColor: "var(--red)" } : null}
                onClick={run}>
                {busy ? "Clearing…" : "Clear selected data"}
              </button>
            </div>
          </div>
        ) : null}

        {msg ? (
          <div style={{ marginTop: 12, padding: "8px 12px", borderRadius: 4, fontSize: 12, background: msg.ok ? "var(--green-bg)" : "var(--red-bg)", color: msg.ok ? "var(--green)" : "var(--red)" }}>{msg.text}</div>
        ) : null}
      </div>
    </div>
  );
}

Object.assign(window, { AdminPanel });
