// ConfirmAction.jsx — consequence-preview modal (design.md "signature move 1").
//
// Every state-changing admin action is routed through this before it commits.
// The modal states, in plain language and computed from live data:
//   · exactly what will change and its scope ("halts 6 active accounts")
//   · when it takes effect
//   · that it is recorded, and as whom
//   · a required reason where the action is consequential
// Only on Confirm does the mutation run, the toast fire, and the audit append.
//
// This is the interaction that most expresses the thesis: an operator never
// changes a regulated facility's state without first seeing the consequence.

// ── Descriptor builder ──────────────────────────────────────────────────
// Returns null for actions that need no confirmation (navigation / view-only).
const buildConsequence = (key, payload, ctx) => {
  const D = (o) => ({ recordedAs: "admin@ascend.io", effective: "Immediately", confirmTone: "danger", ...o });

  switch (key) {
    // ----- Facilities -----
    case "pause-facility":
      return D({
        title: "Pause facility", confirmLabel: "Pause facility", confirmTone: "warning",
        target: { label: payload.name, sub: `${payload.tranche} · settles ${payload.token}` },
        consequences: [
          { icon: "pause",   text: `Halts new borrows and deposits across ${payload.accounts} active account${payload.accounts === 1 ? "" : "s"}.` },
          { icon: "check",   text: "Existing positions are untouched — repayments and withdrawals stay enabled." },
          { icon: "gavel",   text: "Liquidations continue to run, so lenders stay protected." },
        ],
        requireReason: true,
      });
    case "unpause-facility":
      return D({
        title: "Resume facility", confirmLabel: "Resume facility", confirmTone: "success",
        target: { label: payload.name, sub: `${payload.tranche} · settles ${payload.token}` },
        consequences: [
          { icon: "play",  text: `Re-enables borrows and deposits across ${payload.accounts} account${payload.accounts === 1 ? "" : "s"}.` },
          { icon: "info",  text: "Runtime compliance gates resume evaluating on every transaction." },
        ],
        requireReason: false,
      });

    // ----- Accounts -----
    case "freeze-account":
      return D({
        title: "Freeze account", confirmLabel: "Freeze account", confirmTone: "danger",
        target: { label: payload.id, sub: payload.facility, mono: true },
        consequences: [
          { icon: "snowflake", text: "Blocks all activity — borrows, deposits, withdrawals and transfers." },
          { icon: "lock",      text: `Collateral (${fmtMoney(payload.collateral)}) and debt (${fmtMoney(payload.borrowed)}) are locked in place.` },
          { icon: "alert",     text: "Health factor stops updating while the account is frozen." },
        ],
        effective: "On next block · pending on-chain confirmation",
        requireReason: true,
      });
    case "unfreeze-account":
      return D({
        title: "Unfreeze account", confirmLabel: "Unfreeze account", confirmTone: "success",
        target: { label: payload.id, sub: payload.facility, mono: true },
        consequences: [
          { icon: "play", text: "Restores borrows, deposits, withdrawals and transfers." },
          { icon: "info", text: "Health factor resumes updating from the next oracle tick." },
        ],
        requireReason: false,
      });
    case "pause-account":
      return D({
        title: "Pause account", confirmLabel: "Pause account", confirmTone: "warning",
        target: { label: payload.id, sub: payload.facility, mono: true },
        consequences: [
          { icon: "pause", text: "Halts new borrows and deposits on this account." },
          { icon: "check", text: "Withdrawals and repayments remain enabled." },
        ],
        requireReason: true,
      });
    case "unpause-account":
      return D({
        title: "Unpause account", confirmLabel: "Unpause account", confirmTone: "success",
        target: { label: payload.id, sub: payload.facility, mono: true },
        consequences: [{ icon: "play", text: "Re-enables borrows and deposits on this account." }],
        requireReason: false,
      });

    // ----- Claims -----
    case "approve-claim":
      return D({
        title: "Approve claim", confirmLabel: "Approve claim", confirmTone: "success",
        target: { label: payload.investor, sub: `${payload.type} · ${payload.facility}` },
        consequences: [
          { icon: "shieldCheck", text: `Attaches the ${payload.type} claim to OnchainID ${payload.onchainId}.` },
          { icon: "check",       text: `Investor becomes eligible to borrow against ${payload.facility}.` },
        ],
        requireReason: false,
      });
    case "reject-claim":
      return D({
        title: "Reject claim", confirmLabel: "Reject claim", confirmTone: "danger",
        target: { label: payload.investor, sub: `${payload.type} · ${payload.facility}` },
        consequences: [
          { icon: "cross", text: `Declines the ${payload.type} attestation for ${payload.investor}.` },
          { icon: "info",  text: `Investor remains ineligible for ${payload.facility}. They can re-submit.` },
        ],
        requireReason: true,
      });
    case "revoke-claim":
      return D({
        title: "Revoke claim", confirmLabel: "Revoke claim", confirmTone: "danger",
        target: { label: payload.investor, sub: `${payload.type} · ${payload.facility}` },
        consequences: [
          { icon: "shieldX", text: `Withdraws the approved ${payload.type} claim from OnchainID ${payload.onchainId}.` },
          { icon: "alert",   text: `Investor loses eligibility for ${payload.facility} immediately.` },
          { icon: "gavel",   text: "Open positions may become non-compliant and subject to resolution." },
        ],
        requireReason: true,
      });

    // ----- Compliance form (reason already supplied) -----
    case "form-pause-facility":
      return D({
        title: "Pause facility", confirmLabel: "Pause facility", confirmTone: "warning",
        target: { label: payload.targetLabel, sub: "Via compliance controls" },
        consequences: [
          { icon: "pause", text: "Halts new borrows and deposits across the facility's active accounts." },
          { icon: "gavel", text: "Liquidations continue; existing positions are untouched." },
        ],
        presetReason: payload.reason, requireReason: true,
      });
    case "form-freeze-account":
      return D({
        title: "Freeze account", confirmLabel: "Freeze account", confirmTone: "danger",
        target: { label: payload.targetLabel, sub: "Via compliance controls", mono: true },
        consequences: [
          { icon: "snowflake", text: "Blocks all activity on the account." },
          { icon: "lock",      text: "Collateral and debt are locked in place." },
        ],
        effective: "On next block · pending on-chain confirmation",
        presetReason: payload.reason, requireReason: true,
      });
    case "form-clawback":
      return D({
        title: "Initiate clawback", confirmLabel: "Initiate clawback", confirmTone: "danger",
        target: { label: payload.targetLabel, sub: "Via compliance controls", mono: true },
        consequences: [
          { icon: "clawback", text: "Force-transfers collateral from the account back to the facility treasury." },
          { icon: "alert",    text: "This is irreversible. Reserved for regulatory or default resolution." },
        ],
        effective: "On next block · multi-sig may be required",
        presetReason: payload.reason, requireReason: true,
      });

    default:
      return null; // deploy, view, etc. — no confirmation
  }
};

const TONE_STYLE = {
  danger:  { fg: "var(--danger)", bg: "var(--red-10)",  btnBg: "var(--danger)",  btnFg: "var(--white-100)" },
  warning: { fg: "var(--gold-70)", bg: "var(--gold-10)", btnBg: "var(--gold-60)", btnFg: "var(--white-100)" },
  success: { fg: "var(--success)", bg: "var(--green-10)", btnBg: "var(--accent)", btnFg: "var(--white-100)" },
};

const ConfirmAction = ({ request, onCancel, onConfirm }) => {
  const [reason, setReason] = React.useState("");
  const open = !!request;
  const desc = request ? request.descriptor : null;

  React.useEffect(() => {
    if (open) {
      setReason(desc.presetReason || "");
      const id = setTimeout(() => {
        const el = document.getElementById("confirm-reason") || document.getElementById("confirm-btn");
        if (el) el.focus();
      }, 60);
      return () => clearTimeout(id);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onCancel(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  if (!open) return null;
  const tone = TONE_STYLE[desc.confirmTone] || TONE_STYLE.danger;
  const reasonOk = !desc.requireReason || reason.trim().length > 0;
  const presetLocked = !!desc.presetReason;

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="confirm-title"
      onClick={onCancel}
      style={{ position: "fixed", inset: 0, zIndex: 200, display: "grid", placeItems: "center",
        background: "var(--overlay-dim, rgba(17,17,17,0.5))", animation: "cfade 150ms ease-out", padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--surface)", width: 520, maxWidth: "100%", borderRadius: 16,
        boxShadow: "var(--shadow-1)", overflow: "hidden", animation: "crise 150ms ease-out",
      }}>
        {/* Header */}
        <div style={{ display: "flex", gap: 14, alignItems: "flex-start", padding: "24px 24px 18px" }}>
          <span style={{ width: 40, height: 40, borderRadius: 12, background: tone.bg, color: tone.fg, display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name="alert" size={20} stroke={1.7} />
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 id="confirm-title" style={{ margin: 0, font: '700 20px/26px "Figtree", sans-serif', letterSpacing: "-0.01em", color: "var(--fg)" }}>{desc.title}</h2>
            <div style={{ marginTop: 3, display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
              <span className={desc.target.mono ? "addr" : undefined} style={{ font: desc.target.mono ? '600 14px/20px "JetBrains Mono", monospace' : '600 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{desc.target.label}</span>
              {desc.target.sub && <span style={{ font: '400 12px/18px "Inter", sans-serif', color: "var(--fg-subtle)" }}>{desc.target.sub}</span>}
            </div>
          </div>
          <button onClick={onCancel} aria-label="Cancel" style={{ all: "unset", cursor: "pointer", padding: 6, color: "var(--fg-subtle)" }}>
            <Icon name="cross" size={16} stroke={1.6} />
          </button>
        </div>

        {/* Consequence list */}
        <div style={{ padding: "0 24px" }}>
          <div style={{ font: '500 11px/16px "Inter", sans-serif', letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-subtle)", marginBottom: 10 }}>
            What this does
          </div>
          <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
            {desc.consequences.map((c, i) => (
              <li key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
                <span style={{ color: tone.fg, marginTop: 1, flexShrink: 0 }}><Icon name={c.icon} size={15} stroke={1.6} /></span>
                <span style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg)" }}>{c.text}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* Effect + recorded meta */}
        <div style={{ margin: "18px 24px 0", padding: "12px 14px", background: "var(--bg-alt)", borderRadius: 8, display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 14, rowGap: 6, font: '400 12px/16px "Inter", sans-serif' }}>
          <span style={{ color: "var(--fg-subtle)" }}>Takes effect</span>
          <span style={{ color: "var(--fg)", fontWeight: 500 }}>{desc.effective}</span>
          <span style={{ color: "var(--fg-subtle)" }}>Recorded as</span>
          <span className="addr" style={{ color: "var(--fg)", fontWeight: 500, fontFamily: "var(--font-mono)" }}>{desc.recordedAs}</span>
        </div>

        {/* Reason */}
        {desc.requireReason && (
          <div style={{ padding: "16px 24px 0" }}>
            <label htmlFor="confirm-reason" style={{ display: "block", font: '500 12px/16px "Inter", sans-serif', color: "var(--fg)", marginBottom: 6 }}>
              Reason {presetLocked && <span style={{ color: "var(--fg-subtle)", fontWeight: 400 }}>· recorded in the audit log</span>}
            </label>
            {presetLocked ? (
              <div style={{ padding: "10px 12px", borderRadius: 8, background: "var(--bg-alt)", border: "1px solid var(--border)", font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{desc.presetReason}</div>
            ) : (
              <input id="confirm-reason" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="State why this action is being taken…"
                style={{ width: "100%", height: 38, padding: "0 12px", boxSizing: "border-box", borderRadius: 8, border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 13px "Inter", sans-serif' }} />
            )}
          </div>
        )}

        {/* Footer */}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", padding: "20px 24px 22px", marginTop: 4 }}>
          <button className="btn btn--secondary" type="button" onClick={onCancel}>Cancel</button>
          <button id="confirm-btn" type="button" disabled={!reasonOk}
            onClick={() => onConfirm(request.key, request.payload, reason.trim())}
            style={{ height: 36, padding: "0 16px", borderRadius: 8, border: "none", cursor: reasonOk ? "pointer" : "not-allowed",
              font: '600 13px "Inter", sans-serif', opacity: reasonOk ? 1 : 0.5, display: "inline-flex", alignItems: "center", gap: 8,
              background: tone.btnBg, color: tone.btnFg, transition: "opacity var(--motion-fast)" }}>
            {desc.confirmLabel}
          </button>
        </div>
      </div>
      <style>{`@keyframes cfade{from{opacity:0}to{opacity:1}}@keyframes crise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}`}</style>
    </div>
  );
};

Object.assign(window, { buildConsequence, ConfirmAction });
