/* WPSiteBeam - Account audit log (lane BUILD-1020-G, OL-4962)
   v1.0.0.0.0 - 2026-10-20

   Authority, verbatim: "Jordan's ruling, 2026-10-20 (on Chat's recommendation)". Option (a): a
   truth fix in the current app; the full security-settings capability is built once, in v2.

   ONE module, registered as window.WPSB.accountAuditLog, shared by the Account page's Security card
   (design/Pages1.jsx) and the SA Security overview (api static/staff-ui/SecSurface.jsx since BUILD-1020-H):
     toRow, labelFor, whoFor, csvFor  - pure; the harness runs them from this file
     Panel                            - the audit log list: loading / empty / error, never invented rows

   Source: GET /account/audit-log (wpsitebeam-api server.js). The api answers
   { events:[{ created_at, actor_email, event_type, ip, ... }], total, limit, offset, has_more },
   account-scoped by the verified JWT. Rows are rendered only from that response. A failed request
   is an error state with a retry, never an empty list and never sample rows (app CLAUDE.md
   false-empty-on-error, catch #40).

   Standards: React.createElement (no JSX); ASCII source; CSS variables only; logical properties
   (RTL); every string through tx() with keys in design/i18n/_build.py; role="status" for loading,
   role="alert" for the error. */
(function () {
  'use strict';
  var h = React.createElement;
  var tx = function (k, v, f) { return (window.WPSB && window.WPSB.t) ? window.WPSB.t(k, v, f) : (f != null ? f : k); };

  /* event_type -> label. Only types the api writes to account_security_events (core/audit.js
     logSecurityEvent callers). An unknown type is shown as its raw value, never hidden. */
  var EVENT_LABELS = {
    login_success:       ['page.account.audit.event.login_success',       'Signed in'],
    member_joined:       ['page.account.audit.event.member_joined',       'Joined the team'],
    api_key_issued:      ['page.account.audit.event.api_key_issued',      'Created an API key'],
    api_key_regenerated: ['page.account.audit.event.api_key_regenerated', 'Regenerated an API key'],
    api_key_revoked:     ['page.account.audit.event.api_key_revoked',     'Revoked an API key'],
    account_closed:      ['page.account.audit.event.account_closed',      'Closed the account'],
    site_limit_reached:  ['page.account.audit.event.site_limit_reached',  'Reached the site limit'],
    site_deactivated:    ['page.account.audit.event.site_deactivated',    'Deactivated a site'],
    'site.deactivated':  ['page.account.audit.event.site_deactivated',    'Deactivated a site']
  };

  function labelFor(type) {
    var e = Object.prototype.hasOwnProperty.call(EVENT_LABELS, type) ? EVENT_LABELS[type] : null;
    if (e) return tx(e[0], null, e[1]);
    return type ? String(type) : tx('page.account.audit.event.unknown', null, 'Unknown event');
  }

  function currentEmail() {
    var e = (window.WPSBD && window.WPSBD.getUserEmail) ? window.WPSBD.getUserEmail() : (window.currentUser && window.currentUser.email);
    return e ? String(e).toLowerCase() : '';
  }

  function whoFor(actorEmail, me) {
    if (!actorEmail) return tx('page.account.audit.who_system', null, 'System');
    var a = String(actorEmail).toLowerCase();
    if (me && a === me) return tx('page.account.audit.who_you', null, 'You');
    return String(actorEmail);
  }

  function lang() {
    return (typeof document !== 'undefined' && document.documentElement && document.documentElement.lang) || undefined;
  }

  function relTime(iso, now) {
    var ms = Date.parse(iso);
    if (isNaN(ms)) return '';
    var diff = (ms - (now == null ? Date.now() : now)) / 1000;
    var abs = Math.abs(diff);
    var units = [['year', 31536000], ['month', 2592000], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60]];
    try {
      var rtf = new Intl.RelativeTimeFormat(lang(), { numeric: 'auto' });
      for (var i = 0; i < units.length; i++) {
        if (abs >= units[i][1]) return rtf.format(Math.round(diff / units[i][1]), units[i][0]);
      }
      return rtf.format(0, 'second');
    } catch (_) { return absTime(iso); }
  }

  function absTime(iso) {
    var d = new Date(iso);
    if (isNaN(d.getTime())) return '';
    try { return d.toLocaleString(lang()); } catch (_) { return d.toISOString(); }
  }

  /* one api event -> one display row; nothing is filled in that the api did not send */
  function toRow(ev, me, now) {
    ev = ev || {};
    return {
      iso:  ev.created_at || '',
      t:    relTime(ev.created_at, now),
      abs:  absTime(ev.created_at),
      who:  whoFor(ev.actor_email, me),
      what: labelFor(ev.event_type),
      ip:   ev.ip == null ? '' : String(ev.ip)
    };
  }

  function csvCell(v) { return '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"'; }
  function csvFor(rows) {
    return 'time,user,action,ip\n' + rows.map(function (r) { return [r.iso, r.who, r.what, r.ip].map(csvCell).join(','); }).join('\n');
  }

  /* status: 'loading' | 'ready' | 'error' */
  function useAuditLog(limit) {
    var st = React.useState({ status: 'loading', events: [], error: '' });
    var state = st[0], setState = st[1];
    var nonce = React.useState(0);
    React.useEffect(function () {
      var alive = true;
      setState({ status: 'loading', events: [], error: '' });
      var token = window.WPSBD && window.WPSBD.getToken ? window.WPSBD.getToken() : null;
      if (!token) { setState({ status: 'error', events: [], error: 'no_session' }); return; }
      var apiBase = (window.WPSBD && window.WPSBD.apiBase) || 'https://api.wpsitebeam.io';
      fetch(apiBase + '/account/audit-log?limit=' + (limit || 8), { headers: { Authorization: 'Bearer ' + token } })
        .then(function (r) {
          if (!r.ok) throw new Error('http_' + r.status);
          return r.json();
        })
        .then(function (d) {
          if (!d || !Array.isArray(d.events)) throw new Error('bad_shape');
          if (alive) setState({ status: 'ready', events: d.events, error: '' });
        })
        .catch(function (e) { if (alive) setState({ status: 'error', events: [], error: (e && e.message) || 'failed' }); });
      return function () { alive = false; };
    }, [nonce[0]]);
    return { state: state, retry: function () { nonce[1](nonce[0] + 1); } };
  }

  function Panel(props) {
    var limit = (props && props.limit) || 8;
    var log = useAuditLog(limit);
    var state = log.state;
    var me = currentEmail();
    var rows = state.status === 'ready' ? state.events.map(function (ev) { return toRow(ev, me); }) : [];
    var muted = { fontSize: '.78rem', color: 'var(--dim)', padding: '14px 18px' };

    var head = h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 18px 8px', borderBottom: '1px solid var(--border)' } },
      h('span', { style: { fontWeight: 600, fontSize: '.84rem' } }, tx('page.account.security.audit_log', null, 'Audit log')),
      h('button', {
        type: 'button', className: 'btn btn-ghost btn-sm', disabled: rows.length === 0,
        onClick: function () { if (rows.length && window.wpsbDownload) window.wpsbDownload('audit-log.csv', csvFor(rows), 'text/csv'); }
      }, window.Icon ? h(window.Icon, { name: 'download', size: 12 }) : null, tx('page.account.audit.export_csv', null, 'Export CSV')));

    var body;
    if (state.status === 'loading') {
      body = h('div', { role: 'status', style: muted }, tx('page.account.audit.loading', null, 'Loading security events\u2026'));
    } else if (state.status === 'error') {
      body = h('div', { role: 'alert', style: { padding: '14px 18px', fontSize: '.78rem', color: 'var(--text-2)' } },
        h('div', { style: { marginBottom: 8 } }, tx('page.account.audit.error', null, 'Could not load the audit log. Nothing is shown because nothing could be read.')),
        h('button', { type: 'button', className: 'btn btn-ghost btn-sm', onClick: log.retry }, tx('page.account.audit.retry', null, 'Try again')));
    } else if (rows.length === 0) {
      body = h('div', { style: muted }, tx('page.account.audit.empty', null, 'No security events recorded yet.'));
    } else {
      body = h('ul', { style: { listStyle: 'none', margin: 0, padding: 0 } }, rows.map(function (r, i) {
        return h('li', { key: i, style: { display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 18px', borderBottom: i < rows.length - 1 ? '1px solid var(--border)' : 'none' } },
          h('time', { dateTime: r.iso, title: r.abs, style: { fontFamily: 'var(--font-mono)', fontSize: '.7rem', color: 'var(--dim)', flexShrink: 0, minInlineSize: 72, paddingTop: 1 } }, r.t),
          h('div', { style: { flex: 1, fontSize: '.82rem', lineHeight: 1.4, minWidth: 0, overflowWrap: 'anywhere' } },
            h('strong', { style: { color: 'var(--text)' } }, r.who), ' ',
            h('span', { style: { color: 'var(--dim)' } }, r.what)),
          h('span', { style: { fontFamily: 'var(--font-mono)', fontSize: '.68rem', color: 'var(--dim)', flexShrink: 0 } }, r.ip));
      }));
    }
    return h('div', null, head, body);
  }

  window.WPSB = window.WPSB || {};
  window.WPSB.accountAuditLog = { toRow: toRow, labelFor: labelFor, whoFor: whoFor, csvFor: csvFor, Panel: Panel, EVENT_LABELS: EVENT_LABELS };
})();
