/** Audit-log pattern — populate table-ui via [columns] with col.render functions. */

const VERB_TONE = {
  create:  'primary',
  update:  'primary',
  delete:  'danger',
  revoke:  'danger',
  rotate:  'warning',
  export:  'muted',
  read:    'muted',
  login:   'muted',
};

const ROWS = [
  { time: '2 minutes ago',  actor: 'kim@example.com',    verb: 'delete',  resource: 'api_key_sk_live_…A4F2',   ip: '10.0.4.21' },
  { time: '14 minutes ago', actor: 'alex@example.com',   verb: 'update',  resource: 'workspace_settings',     ip: '10.0.4.88' },
  { time: '47 minutes ago', actor: 'automation-bot',     verb: 'export',  resource: 'invoices.2024-q4.csv',   ip: '127.0.0.1' },
  { time: '1 hour ago',     actor: 'alex@example.com',   verb: 'create',  resource: 'webhook_evt_92h2k',      ip: '10.0.4.88' },
  { time: '2 hours ago',    actor: 'kim@example.com',    verb: 'rotate',  resource: 'api_key_sk_live_…9821',  ip: '10.0.4.21' },
  { time: '4 hours ago',    actor: 'kim@example.com',    verb: 'login',   resource: 'session_a4e8f0',         ip: '10.0.4.21' },
  { time: 'Yesterday',      actor: 'alex@example.com',   verb: 'revoke',  resource: 'invite_inv_3kf02',       ip: '10.0.4.88' },
  { time: '2 days ago',     actor: 'automation-bot',     verb: 'read',    resource: 'audit_log',              ip: '127.0.0.1' },
];

const escape = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
  { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
));

export default function setup(router) {
  const root = (router?.querySelector?.('#audit-log-table')) || document.querySelector('#audit-log-table');
  if (!root) return;
  root.columns = [
    { key: 'time',  label: 'When',  align: 'left' },
    {
      key: 'actor', label: 'Actor', align: 'left',
      render: (v) => {
        const initial = (v[0] || '?').toUpperCase();
        return `<span style="display:inline-flex;align-items:center;gap:.5rem;">
          <avatar-ui size="sm" text="${escape(initial)}" color="muted"></avatar-ui>
          <span>${escape(v)}</span>
        </span>`;
      },
    },
    {
      key: 'verb', label: 'Action', align: 'left',
      render: (v) => {
        const tone = VERB_TONE[v] || 'muted';
        return `<tag-ui size="sm" variant="${tone}">${escape(v)}</tag-ui>`;
      },
    },
    {
      key: 'resource', label: 'Resource', align: 'left',
      // Native <code> for inline monospace — code-ui is the BLOCK component
      // (CODE label + Copy header chrome) which is wrong for a table cell.
      render: (v) => `<code>${escape(v)}</code>`,
    },
    { key: 'ip', label: 'IP', align: 'left' },
  ];
  root.data = ROWS;
}
