// AdminAuditLog.jsx — full-page audit log (Move 3: first-class nav item).
// Extracted from AdminCompliance so attribution is always one glance away,
// not buried inside a sub-section. The compliance page keeps a 5-row strip.

const AdminAuditLog = ({ auditLog, state, onRetry }) => {
  const [actionFilter, setActionFilter] = React.useState("all");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  const [dateFrom, setDateFrom] = React.useState("");

  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load the audit log" onRetry={onRetry} />;

  const filtered = auditLog.filter(e =>
    (actionFilter === "all" || e.action === actionFilter) &&
    (statusFilter === "all" || e.status === statusFilter) &&
    (q === "" || [e.target, e.description, e.actor].join(" ").toLowerCase().includes(q.toLowerCase())) &&
    (dateFrom === "" || new Date(e.ts) >= new Date(dateFrom))
  );

  const byAction = (a) => auditLog.filter(e => e.action === a).length;
  const latestActor = auditLog[0]?.actor;
  const latestTs = auditLog[0]?.ts;

  const ACTION_BADGE_STYLE = {
    FREEZE:      { bg: "var(--red-10)",   fg: "var(--red-80)" },
    UNFREEZE:    { bg: "var(--green-10)", fg: "var(--green-80)" },
    PAUSE:       { bg: "var(--gold-10)",  fg: "var(--gold-80)" },
    UNPAUSE:     { bg: "var(--green-10)", fg: "var(--green-80)" },
    CLAWBACK:    { bg: "var(--red-10)",   fg: "var(--red-80)" },
    APPROVE:     { bg: "var(--green-10)", fg: "var(--green-80)" },
    REJECT:      { bg: "var(--red-10)",   fg: "var(--red-80)" },
    REVOKE:      { bg: "var(--red-10)",   fg: "var(--red-80)" },
    LIQUIDATION: { bg: "var(--red-10)",   fg: "var(--red-80)" },
    RATE_UPDATE: { bg: "var(--blue-10)",  fg: "var(--blue-80)" },
    SHUTDOWN:    { bg: "var(--red-10)",   fg: "var(--red-80)" },
    DEPLOY:      { bg: "var(--blue-10)",  fg: "var(--blue-80)" },
  };
  const AB = ({ action }) => {
    const c = ACTION_BADGE_STYLE[action] || { bg: "var(--black-10)", fg: "var(--black-80)" };
    return <span style={{ display: "inline-block", padding: "2px 9px", borderRadius: 999, background: c.bg, color: c.fg, font: '600 11px/16px "Inter", sans-serif', letterSpacing: "0.03em" }}>{action}</span>;
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Audit" title="Audit log" icon="docs"
        lede="Complete record of every operator action — who, when, and what changed. Immutable once written."
        annot="Move 3 first-class nav" />

      <HeroStrip
        hero={{ label: "Total entries", value: auditLog.length, sub: latestTs ? `Last action: ${fmtRelative(latestTs)} by ${latestActor}` : "No entries yet" }}
        supports={[
          { label: "Freeze / unfreeze", value: byAction("FREEZE") + byAction("UNFREEZE"), sub: `${byAction("FREEZE")} freeze · ${byAction("UNFREEZE")} unfreeze` },
          { label: "Pause / resume",    value: byAction("PAUSE") + byAction("UNPAUSE"),   sub: `${byAction("PAUSE")} pause · ${byAction("UNPAUSE")} resume` },
          { label: "Claims",            value: byAction("APPROVE") + byAction("REJECT") + byAction("REVOKE"), sub: "Approve + reject + revoke" },
        ]}
      />

      <section className="card" style={{ padding: 0 }} data-annot-note="Move 3 provenance inline">
        <div style={{ padding: "20px 24px 16px" }}>
          <SectionHeader eyebrow="Full record" title="All entries" count={filtered.length} />

          {/* Filters */}
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", marginTop: 12 }}>
            <SegmentControl value={actionFilter} onChange={setActionFilter} options={[
              { value: "all",    label: "All" },
              { value: "FREEZE", label: "Freeze" },
              { value: "PAUSE",  label: "Pause" },
              { value: "APPROVE",label: "Approve" },
              { value: "REJECT", label: "Reject" },
              { value: "REVOKE", label: "Revoke" },
            ]} />
            <SegmentControl value={statusFilter} onChange={setStatusFilter} options={[
              { value: "all",      label: "All statuses" },
              { value: "executed", label: "Executed" },
              { value: "pending",  label: "Pending" },
              { value: "reverted", label: "Reverted" },
            ]} />
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
            <SearchBox placeholder="Search by target, description, actor…" value={q} onChange={setQ} width={320} />
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ font: '400 12px "Inter", sans-serif', color: "var(--fg-subtle)" }}>From</span>
              <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
                title="Filter entries from this date (MMM D, YYYY)"
                style={{ height: 34, padding: "0 10px", borderRadius: 8, border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 13px/1 "Inter", sans-serif', fontVariantNumeric: "tabular-nums", colorScheme: "light dark" }} />
              {dateFrom && <button className="btn btn--ghost btn--sm" onClick={() => setDateFrom("")}>Clear</button>}
            </div>
          </div>
        </div>

        <div className="adm-scroll">
          <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "130px 110px 160px 1fr 220px 180px", gap: 14, padding: "10px 24px", background: "var(--bg-alt)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)" }}>
            <Th sortable>Action</Th><Th sortable>Status</Th><Th sortable>Target</Th>
            <Th sortable>Description</Th><Th align="right" sortable>Timestamp</Th><Th align="right" sortable>Actor</Th>
          </div>

          {filtered.length === 0 ? (
            <EmptyState icon="docs" title="No matching entries" body="Adjust the filters or search above." secondary={{ label: "Clear filters", onClick: () => { setActionFilter("all"); setStatusFilter("all"); setQ(""); setDateFrom(""); } }} />
          ) : filtered.map((e, i) => (
            <div key={e.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "130px 110px 160px 1fr 220px 180px", gap: 14, padding: "13px 24px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
              <div><AB action={e.action} /></div>
              <div><AdminStatus status={e.status} /></div>
              <span className="addr" style={{ font: '500 12px/16px "JetBrains Mono", monospace', color: "var(--fg)" }}>{e.target}</span>
              <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{e.description}</span>
              <div style={{ textAlign: "right" }}>
                <div className="tnum" style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-muted)" }} title={fmtRelative(e.ts)}>{fmtDateTime(e.ts)}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ font: '500 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{e.actor}</div>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

window.AdminAuditLog = AdminAuditLog;
