// Audit Trail — read-only view for SCB auditors. Every row is immutable.
// Lock icon in header, "Read-only audit view" banner, no edit buttons anywhere.
// Filterable by date range, user, reviewer, action type. Export CSV + signed PDF.

function AuditTrail({ audit, auditorMode }) {
  const [filterActor, setFilterActor]   = React.useState("Any");
  const [filterAction, setFilterAction] = React.useState("Any");
  const [filterRange, setFilterRange]   = React.useState("Today");

  const rows = React.useMemo(() => {
    let r = audit;
    if (filterActor  !== "Any") r = r.filter(a => a.actor === filterActor);
    if (filterAction !== "Any") r = r.filter(a => a.action.startsWith(filterAction));
    if (filterRange === "Today") r = r.filter(a => a.ts.startsWith("2026-05-19"));
    return r;
  }, [audit, filterActor, filterAction, filterRange]);

  const cycle = (cur, set, opts) => () => {
    const i = opts.indexOf(cur);
    set(opts[(i + 1) % opts.length]);
  };

  const actionTone = (act) => {
    if (act.endsWith("approved") || act === "wd.auto_approved") return "is-approved";
    if (act.endsWith("rejected")) return "is-rejected";
    if (act.endsWith("escalated") || act === "kyt.alert" || act === "kyc.expired") return "is-escalated";
    return "";
  };

  return (
    <>
      <div className="app-subheader">
        <div className="subheader-title" style={{display:"flex",alignItems:"center",gap:8}}>
          <ILock size={14} style={{color:"var(--red-fg)"}} />
          Audit Trail
        </div>
        <div className="subheader-meta">Immutable · <Term id="SCB">SCB</Term>-filing-grade · last write 14s ago</div>
        <div className="subheader-spacer" />
        <Btn variant="outlined" icon={IDownload}>Export CSV</Btn>
        <Btn variant="filled" icon={IDownload}>Export signed PDF</Btn>
      </div>

      <div className="audit-banner">
        <ILock size={14} className="audit-banner-icon" />
        Read-only audit view. No row may be edited or deleted. All access is itself audit-logged.
        <span className="audit-banner-hint">Session · SCB-2026-Q2 · {auditorMode ? "auditor.scb@gov.bs" : "alva.brennan@agio"} · {new Date().toISOString().slice(0,10)}</span>
      </div>

      <div className="fbar">
        <FilterChip label="Range"  value={filterRange}  active={filterRange !== "All"}  onClick={cycle(filterRange,  setFilterRange,  ["Today","Last 7d","Last 30d","All"])} />
        <FilterChip label="Actor"  value={filterActor}  active={filterActor !== "Any"}  onClick={cycle(filterActor,  setFilterActor,  ["Any","alva.brennan@agio","carlos.gomes@agio","elena.thomas@agio","system"])} />
        <FilterChip label="Action" value={filterAction} active={filterAction !== "Any"} onClick={cycle(filterAction, setFilterAction, ["Any","kyc","kyb","wd","kyt","review","settings"])} />
        <span className="fbar-spacer" />
        <span className="fbar-result"><b>{rows.length}</b> events</span>
      </div>

      <div className="tbl-wrap">
        <div className="tbl-scroll">
          <table className="tbl">
            <thead>
              <tr>
                <th className="sticky-first" style={{paddingLeft:16, width: 165}}>Timestamp (UTC)</th>
                <th style={{width: 200}}>Actor</th>
                <th style={{width: 180}}>Action</th>
                <th>Subject</th>
                <th>Note</th>
                <th className="col-narrow" style={{paddingRight:16}}>Trace</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((a, i) => (
                <tr key={i}>
                  <td className="sticky-first mono" style={{paddingLeft:16, color:"var(--fg-2)", fontSize:11.5}}>
                    {a.ts}
                  </td>
                  <td><span className="audit-actor">{a.actor}</span></td>
                  <td><span className={`audit-action ${actionTone(a.action)} ${a.actor === "system" ? "is-system" : ""}`}>{a.action}</span></td>
                  <td><span className="audit-subject">{a.subject}</span></td>
                  <td><span className="audit-note">{a.note}</span></td>
                  <td className="col-narrow" style={{paddingRight:16}}>
                    <ActionIcon icon={IExternal} label="Open trace" />
                  </td>
                </tr>
              ))}
              {rows.length === 0 && (
                <tr><td colSpan={6}>
                  <Empty title="No events match" hint="Widen the range or change actor / action filter." />
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="tbl-foot">
          <span><b>{rows.length}</b> events · <b className="mono">sha256: 9f4c…a18b</b> (Merkle root, last 1h)</span>
          <span className="tbl-foot-spacer" />
          <span className="fg-4" style={{fontSize:11, display:"flex", gap:6, alignItems:"center"}}>
            <ILock size={11} /> Records are append-only. Hash chain verified.
          </span>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AuditTrail });
