/* Task 8 — Audit log */
const { useState: useStateAudit, useMemo: useMemoAudit } = React;

function orderCountry(ref) {
  const o = window.CardOps.ORDERS.find((x) => x.ref === ref);
  return o ? o.country : null;
}

function AuditLog({ role, globalCountry, loading, addToast }) {
  const [user, setUser] = useStateAudit("all");
  const [action, setAction] = useStateAudit("all");
  const [date, setDate] = useStateAudit("all");

  const entries = window.CardOps.AUDIT;
  const users = useMemoAudit(() => Array.from(new Set(entries.map((e) => e.user))), []);
  const actionTypes = useMemoAudit(() => Array.from(new Set(entries.map((e) => e.action))), []);

  const rows = useMemoAudit(() => entries.filter((e) =>
    (user === "all" || e.user === user) &&
    (action === "all" || e.action === action) &&
    (date === "all" || e.time.startsWith(date)) &&
    (globalCountry === "all" || orderCountry(e.target) === globalCountry)
  ), [user, action, date, globalCountry]);

  const canExport = window.CardOps.can(role, "export_csv");
  const exportCsv = () => {
    if (!canExport) return;
    const head = ["Timestamp", "User", "Role", "Action", "Target", "Details"];
    const esc = (s) => '"' + String(s).replace(/"/g, '""') + '"';
    const lines = [head.map(esc).join(",")].concat(rows.map((e) =>
      [e.time, e.user, (window.CardOps.ROLES[e.role] ? window.CardOps.ROLES[e.role].label : e.role), e.action, e.target, e.details].map(esc).join(",")));
    const blob = new Blob([lines.join("\n")], { type: "text/csv" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "cardops-audit-" + Date.now() + ".csv";
    document.body.appendChild(a); a.click(); a.remove();
    addToast && addToast({ icon: "download", title: "Audit log exported", body: rows.length + " rows written to CSV." });
  };

  return React.createElement("div", { className: "co-page" },
    React.createElement("div", { className: "co-page-head" },
      React.createElement("div", null,
        React.createElement("h1", { className: "co-page-title" }, "Audit log"),
        React.createElement("p", { className: "co-page-sub" },
          React.createElement("span", { style: { display: "inline-flex", alignItems: "center", gap: 6 } },
            React.createElement(window.Icon, { name: "lock", size: 13 }), "Immutable · ", rows.length, " events"))),
      React.createElement(window.GatedButton, { perm: "export_csv", role, variant: "secondary", icon: "download", onClick: exportCsv }, "Export CSV")),

    React.createElement("div", { className: "co-filterbar" },
      React.createElement(window.FilterDropdown, { icon: "user", label: "User", value: user, options: users.map((u) => ({ v: u, label: u })), onChange: setUser, allLabel: "All users" }),
      React.createElement(window.FilterDropdown, { icon: "zap", label: "Action", value: action, options: actionTypes.map((a) => ({ v: a, label: a })), onChange: setAction, allLabel: "All actions" }),
      React.createElement(window.FilterDropdown, { icon: "calendar", label: "Date", value: date, options: [{ v: "Jun 22", label: "Jun 22" }, { v: "Jun 21", label: "Jun 21" }, { v: "Jun 20", label: "Jun 20" }, { v: "Jun 19", label: "Jun 19" }], onChange: setDate, allLabel: "All dates" })),

    loading
      ? React.createElement("div", { className: "co-table-wrap" }, React.createElement(window.SkeletonRows, { rows: 8, cols: 5 }))
      : rows.length === 0
        ? React.createElement("div", { className: "co-card" }, React.createElement(window.EmptyState, { icon: "log", title: "No matching events", sub: "Adjust the filters above." }))
        : React.createElement("div", { className: "co-table-wrap" },
            React.createElement("table", { className: "co-table" },
              React.createElement("thead", null, React.createElement("tr", null,
                ["Timestamp", "Ops user", "Role", "Action", "Target", "Details"].map((h) => React.createElement("th", { key: h, className: "no-sort" }, h)))),
              React.createElement("tbody", null,
                rows.map((e, i) => React.createElement("tr", { key: i, style: { cursor: "default" } },
                  React.createElement("td", { className: "co-cell-mono co-cell-muted" }, e.time),
                  React.createElement("td", { className: "co-cell-strong" }, e.user),
                  React.createElement("td", null, e.role === "—" ? React.createElement("span", { className: "co-cell-muted" }, "System") : React.createElement(window.RoleBadge, { role: e.role })),
                  React.createElement("td", null,
                    React.createElement("span", { style: { color: /FAIL|block/i.test(e.action) ? "var(--co-red)" : (/activat|passed|capt/i.test(e.action) ? "var(--co-green)" : "var(--co-text)"), fontWeight: 600 } }, e.action)),
                  React.createElement("td", { className: "co-cell-mono co-cell-muted" }, e.target),
                  React.createElement("td", { className: "co-cell-muted", style: { whiteSpace: "normal", minWidth: 240 } }, e.details)))))));
}

window.AuditLog = AuditLog;
