// AdminClaims.jsx — global claim queue. Real approve / reject / revoke actions
// mutate the claim, fire a toast, and append to the audit log.
//   · C-4: pending (the actionable bucket) is the hero; others support it.
//   · C-2: rows read distinctly via investor + facility + type.
//   · C-5: issuer is "Ascend Protocol" (never "Ascend Governance").

const ClaimActions = ({ claim, onAction }) => {
  if (claim.status === "under-review") {
    return (
      <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
        <button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("reject-claim", claim)} style={{ color: "var(--danger)" }}>Reject</button>
        <button className="btn btn--primary btn--sm" type="button" onClick={() => onAction("approve-claim", claim)}>Approve</button>
      </div>
    );
  }
  if (claim.status === "approved") {
    return <div style={{ display: "flex", justifyContent: "flex-end" }}><button className="btn btn--secondary btn--sm" type="button" onClick={() => onAction("revoke-claim", claim)} style={{ color: "var(--danger)" }}>Revoke</button></div>;
  }
  return <div style={{ textAlign: "right", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-faint)" }}>—</div>;
};

const AdminClaims = ({ claims, onAction, state, onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load the claim queue" onRetry={onRetry} />;

  const by = (s) => claims.filter(c => c.status === s).length;
  const counts = { all: claims.length, "under-review": by("under-review"), approved: by("approved"), rejected: by("rejected"), revoked: by("revoked") };
  const filtered = claims.filter(c =>
    (filter === "all" || c.status === filter) &&
    (q === "" || [c.type, c.investor, c.wallet, c.onchainId, c.jurisdiction, c.provider, c.facility].join(" ").toLowerCase().includes(q.toLowerCase()))
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Identity & claims" title="Claims" icon="clipboard"
        lede="Operator view of every claim attached to an Ascend OnchainID. Ascend Protocol is the issuer; providers (Sumsub, Onfido) supply attestation data. Use the row actions to approve, reject, or revoke."
        annot="C-5 'Ascend Protocol', not 'Ascend Governance'" />

      <HeroStrip
        hero={{ label: "Awaiting review", value: counts["under-review"], sub: "Claims that need an operator decision", tone: counts["under-review"] > 0 ? "warning" : undefined }}
        supports={[
          { label: "Approved", value: counts.approved, sub: "Verified & attached", tone: "success" },
          { label: "Rejected", value: counts.rejected, sub: "Attestation declined", tone: "danger" },
          { label: "Revoked", value: counts.revoked, sub: "Previously approved, withdrawn" },
        ]}
      />

      <div>
        <SectionHeader eyebrow="Queue" title="Credit facility claims" count={filtered.length}
          annot="C-2 investor + facility + type"
          action={<SearchBox placeholder="Search by type, investor, wallet, onchain ID…" value={q} onChange={setQ} width={320} />} />

        <div style={{ marginBottom: 16 }}>
          <SegmentControl value={filter} onChange={setFilter} options={[
            { value: "all", label: "All", count: counts.all },
            { value: "under-review", label: "Under review", count: counts["under-review"] },
            { value: "approved", label: "Approved", count: counts.approved },
            { value: "rejected", label: "Rejected", count: counts.rejected },
            { value: "revoked", label: "Revoked", count: counts.revoked },
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "90px 160px 1.2fr 1.4fr 120px 60px 90px 130px 150px", gap: 14, padding: "10px 20px", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Case</Th><Th sortable>Type</Th><Th sortable>Facility</Th><Th sortable>Investor</Th>
              <Th>Wallet</Th><Th>Region</Th><Th>Provider</Th><Th>Status</Th><Th align="right">Actions</Th>
            </div>
            {filtered.length === 0 ? (
              <EmptyState icon="clipboard" title="No claims match" body="Adjust the filter or search to see other claims." secondary={{ label: "Show all", onClick: () => { setFilter("all"); setQ(""); } }} />
            ) : filtered.map((c, i) => (
              <div key={c.caseId} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "90px 160px 1.2fr 1.4fr 120px 60px 90px 130px 150px", gap: 14, padding: "14px 20px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                <span className="addr" style={{ font: '500 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{c.caseId}</span>
                <span><span style={{
                  display: "inline-block",
                  padding: "3px 10px",
                  borderRadius: 4,
                  background: "var(--bg-alt)",
                  border: "1px solid var(--border-strong)",
                  font: '500 12px/18px "Inter", sans-serif',
                  color: "var(--fg-muted)",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  maxWidth: "100%",
                }}>{c.type}</span></span>
                <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.facility}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.investor}</div>
                  <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.email}</div>
                </div>
                <MonoAddr full={c.wallet} />
                <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-muted)" }}>{c.jurisdiction}</span>
                <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-muted)" }}>{c.provider}</span>
                <div><AdminStatus status={c.status} /></div>
                <ClaimActions claim={c} onAction={onAction} />
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

window.AdminClaims = AdminClaims;
