/* ============================================================
   Audit trail — immutable activity log (FR-14)
   Live from Supabase audit_events when logged in, else mock.
   ============================================================ */

const AUDIT_MOCK = [
  { actor: "Nguyễn Minh", action: "publish",         target_type: "container", target_id: "INF-Drainage-L3", time: "2 giờ" },
  { actor: "Phạm Tuấn",   action: "approve",         target_type: "container", target_id: "ARC-Facade-GaC",  time: "Hôm qua" },
  { actor: "Trần Đức",    action: "issue_open",      target_type: "issue",     target_id: "ISS-112",         time: "3 giờ" },
  { actor: "Lê Hồng",     action: "status:shared",   target_type: "container", target_id: "STR-Frame-Station-C", time: "5 giờ" },
  { actor: "Bùi An",      action: "transmittal_send",target_type: "transmittal", target_id: "TR-050",        time: "Hôm qua" },
];

function auditMeta(action) {
  const a = action || "";
  if (a.startsWith("status:") || a === "publish" || a === "approve") return { color: "var(--ok)", icon: "checkCircle" };
  if (a === "upload") return { color: "var(--accent)", icon: "upload" };
  if (a.startsWith("issue")) return { color: "var(--warn)", icon: "flag" };
  if (a.startsWith("transmittal")) return { color: "var(--str)", icon: "send" };
  return { color: "var(--ink-3)", icon: "clock" };
}
const ACTION_VI = {
  publish: "Phát hành", approve: "Phê duyệt", upload: "Nạp tệp", issue_open: "Tạo issue",
  transmittal_send: "Gửi transmittal",
};
function actionLabel(a) {
  if (ACTION_VI[a]) return ACTION_VI[a];
  if ((a || "").startsWith("status:")) return "Đổi trạng thái → " + a.split(":")[1];
  if ((a || "").startsWith("issue:")) return "Issue → " + a.split(":")[1];
  return a || "—";
}
function fmtAuditTime(iso) {
  if (!iso) return "—";
  const d = new Date(iso); const p = (n) => String(n).padStart(2, "0");
  return p(d.getDate()) + "/" + p(d.getMonth() + 1) + " · " + p(d.getHours()) + ":" + p(d.getMinutes());
}

function Audit() {
  const auth = (typeof useAuthCtx === "function") ? useAuthCtx() : null;
  const live = !!(auth && auth.user && window.CDE_READY);
  const [rows, setRows] = useState(AUDIT_MOCK);
  React.useEffect(() => {
    let alive = true;
    if (live) cdeData.audit(100).then(d => { if (alive) setRows(d); }).catch(e => { console.warn("audit live:", e.message); if (alive) setRows([]); });
    else setRows(AUDIT_MOCK);
    return () => { alive = false; };
  }, [live]);

  return (
    <div className="content">
      <PageHead title="Nhật ký kiểm toán" sub="Bản ghi bất biến mọi hành động · ISO 19650 §3.14">
        <button className="btn sm"><Icon.filter size={14} /> Lọc</button>
        <button className="btn sm" onClick={() => downloadCSV("audit-log.csv",
          ["Thời gian", "Người thực hiện", "Hành động", "Loại", "Đối tượng"],
          rows.map(r => [r.created_at ? fmtAuditTime(r.created_at) : (r.time || ""), r.actor, actionLabel(r.action), r.target_type, r.target_id]))}>
          <Icon.download size={14} /> Xuất log</button>
      </PageHead>
      <div className="card" style={{ padding: "8px 10px" }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ paddingLeft: 14 }}>Thời gian</th><th>Người thực hiện</th><th>Hành động</th><th>Đối tượng</th>
          </tr></thead>
          <tbody>
            {rows.map((r, i) => {
              const m = auditMeta(r.action); const Ico = Icon[m.icon] || Icon.clock;
              return (
                <tr key={r.id || i}>
                  <td className="tnum" style={{ color: "var(--ink-3)", whiteSpace: "nowrap" }}>{r.created_at ? fmtAuditTime(r.created_at) : (r.time || "—")}</td>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span className="avatar" style={{ width: 28, height: 28, fontSize: 11 }}>{(r.actor || "?").trim().split(/\s+/).pop()[0]}</span>
                      <span className="t-strong">{r.actor || "—"}</span>
                    </div>
                  </td>
                  <td>
                    <span className="chip" style={{ background: `${m.color}1c`, color: m.color }}>
                      <Ico size={12} /> {actionLabel(r.action)}
                    </span>
                  </td>
                  <td>
                    <span style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 600 }}>{r.target_type}</span>{" "}
                    <span className="tag-mono">{r.target_id}</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {rows.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Chưa có sự kiện</div>}
      </div>
    </div>
  );
}

window.Audit = Audit;
