// AdminTransactions.jsx — F7. Read-only settlement and reserve-reconciliation
// feed (Operations nav): auction resolutions with reserve/proceeds/variance,
// plus facility/account state changes, each with a tx hash, timestamp, status.

const TX_KIND_TONE = {
  "Auction Resolution": "chip--info",
  "Facility Pause": "chip--gold",
  "Facility Shutdown": "chip--neutral",
  "Account Freeze": "chip--gold",
  "Account Pause": "chip--gold",
};

const AdminTransactions = ({ transactions, state, onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  const [page, setPage] = React.useState(1);
  const perPage = 10;
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error") return <PageError title="Couldn't load transactions" onRetry={onRetry} />;

  const counts = {
    all: transactions.length,
    settled: transactions.filter((t) => t.status === "settled").length,
    pending: transactions.filter((t) => t.status === "pending").length,
  };
  const filtered = transactions.filter((t) =>
    (filter === "all" || t.status === filter) &&
    (q === "" || [t.kind, t.target, t.facility, t.txHash, t.desc].join(" ").toLowerCase().includes(q.toLowerCase()))
  );
  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const pageRows = filtered.slice((page - 1) * perPage, page * perPage);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <PageHeader eyebrow="Operations" title="Transactions" icon="activity"
        lede="Facility liquidation settlement and reserve reconciliation records." />

      <div>
        <SectionHeader eyebrow="Records" title="Settlement records" count={filtered.length}
          action={<SearchBox placeholder="Search by account, facility, or tx hash…" value={q} onChange={(v) => { setQ(v); setPage(1); }} width={300} />} />

        <div style={{ marginBottom: "var(--space-16)" }}>
          <SegmentControl value={filter} onChange={(v) => { setFilter(v); setPage(1); }} options={[
            { value: "all", label: "All status", count: counts.all },
            { value: "settled", label: "Settled", count: counts.settled },
            { value: "pending", label: "Pending", count: counts.pending },
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "1.4fr 110px 1.4fr 1.4fr 150px 110px", gap: "var(--space-16)", padding: "var(--space-12) var(--space-20)", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Type</Th><Th>Account</Th><Th>Facility</Th><Th align="right">Detail</Th><Th>Tx hash</Th><Th>Status</Th>
            </div>
            {pageRows.length === 0 ? (
              <EmptyState icon="activity" title="No transactions match" body="Adjust the filter or search." secondary={{ label: "Show all", onClick: () => { setFilter("all"); setQ(""); } }} />
            ) : pageRows.map((t, i) => (
              <div key={t.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "1.4fr 110px 1.4fr 1.4fr 150px 110px", gap: "var(--space-16)", padding: "var(--space-16) var(--space-20)", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                <div style={{ minWidth: 0 }}>
                  <span className={`chip ${TX_KIND_TONE[t.kind] || "chip--neutral"}`} style={{ padding: "var(--space-2) var(--space-8)", fontSize: 11 }}>{t.kind}</span>
                  <div style={{ font: '400 11px/14px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: "var(--space-4)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={t.desc}>{t.desc}</div>
                </div>
                <span className="addr" style={{ font: '500 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{t.target}</span>
                <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.facility}</span>
                <div style={{ textAlign: "right" }}>
                  {t.kind === "Auction Resolution" ? (
                    <div style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-muted)" }}>
                      <span className="tnum">Reserve {fmtMoneyShort(t.reserve)}</span> · <span className="tnum">Proceeds {fmtMoneyShort(t.proceeds)}</span>
                      <div className="tnum" style={{ color: t.variance > 0 ? "var(--success)" : "var(--fg-subtle)" }}>Variance {fmtMoneyShort(t.variance)}</div>
                    </div>
                  ) : (
                    <span style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-muted)" }}>{t.note}</span>
                  )}
                </div>
                <MonoAddr full={t.txHash} />
                <div><AdminStatus status={t.status === "settled" ? "executed" : "pending"} /></div>
              </div>
            ))}
          </div>
        </section>
        {filtered.length > perPage && (
          <div style={{ marginTop: "var(--space-16)" }}>
            <Pagination total={filtered.length} page={page} perPage={perPage} onPage={setPage} perPageOptions={[10]} />
          </div>
        )}
        <div style={{ marginTop: "var(--space-12)", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }}>
          Settlement and reserve reconciliation are simulated; figures are illustrative.
        </div>
      </div>
    </div>
  );
};

window.AdminTransactions = AdminTransactions;
