/* auditoria.jsx — historial operativo visible únicamente para Gerencia. */
(function () {
  window.CR = window.CR || {};
  window.CR.screens = window.CR.screens || {};
  var React = window.React;
  var h = React.createElement;
  var useEffect = React.useEffect, useState = React.useState;
  var PAGE_SIZE = 50;

  var ACCIONES = {
    confirmar: 'Confirmó', notificar: 'Notificó', editar: 'Editó',
    activar: 'Activó un grupo', marcar_manual: 'Marcó un ACK manual',
    atribuir_existente: 'Atribuyó un ACK'
  };

  function fechaArt(value) {
    if (!value) return 'Sin fecha';
    return new Intl.DateTimeFormat('es-AR', {
      timeZone: 'America/Argentina/Buenos_Aires', dateStyle: 'short', timeStyle: 'medium'
    }).format(new Date(value));
  }

  function resumen(evento) {
    var diff = evento.diff || {};
    var partes = Object.keys(diff).filter(function (key) {
      return diff[key] !== null && diff[key] !== undefined && typeof diff[key] !== 'object';
    }).slice(0, 3).map(function (key) { return key + ': ' + String(diff[key]); });
    return partes.join(' · ');
  }

  function Auditoria(props) {
    var rowsState = useState([]); var rows = rowsState[0], setRows = rowsState[1];
    var loadingState = useState(true); var loading = loadingState[0], setLoading = loadingState[1];
    var moreState = useState(false); var loadingMore = moreState[0], setLoadingMore = moreState[1];
    var errorState = useState(''); var error = errorState[0], setError = errorState[1];

    function cargar(mas) {
      var cursor = mas && rows.length ? rows[rows.length - 1].ts : null;
      (mas ? setLoadingMore : setLoading)(true); setError('');
      return window.CR.backend.auditoria(cursor, PAGE_SIZE).then(function (nuevos) {
        setRows(function (actuales) { return mas ? actuales.concat(nuevos) : nuevos; });
      }).catch(function () { setError('No pudimos cargar el historial. Reintentá.'); })
        .finally(function () { (mas ? setLoadingMore : setLoading)(false); });
    }

    useEffect(function () { cargar(false); }, []);

    if (props.rol !== 'gerente_logistica') return h('div', { className: 'empty' },
      h('h3', null, 'Acceso restringido'), h('p', { className: 'muted' }, 'La auditoría está disponible únicamente para Gerencia.'));
    if (loading) return h('div', { className: 'empty', role: 'status' }, h('p', null, 'Cargando auditoría…'));

    return h('section', null,
      h('div', { className: 'section-head' }, h('div', null,
        h('h2', null, 'Historial de actividad'),
        h('p', { className: 'muted' }, 'Confirmaciones, notificaciones, ediciones y activaciones de grupos · horario de Argentina'))),
      error ? h('div', { className: 'alerta alerta--alta', role: 'alert' }, error,
        h('button', { className: 'btn btn--ghost btn--sm', onClick: function () { cargar(false); } }, 'Reintentar')) : null,
      !rows.length && !error ? h('div', { className: 'card empty' }, h('h3', null, 'Todavía no hay actividad auditada'),
        h('p', { className: 'muted' }, 'Las acciones operativas aparecerán acá cuando se registren.')) : null,
      rows.length ? h('div', { className: 'card', style: { overflowX: 'auto' } },
        h('table', { className: 'table' }, h('thead', null, h('tr', null,
          h('th', null, 'Fecha (ART)'), h('th', null, 'Persona'), h('th', null, 'Acción'), h('th', null, 'Detalle'))),
        h('tbody', null, rows.map(function (evento) {
          var actor = evento.actor || {};
          return h('tr', { key: evento.id },
            h('td', null, fechaArt(evento.ts)),
            h('td', null, h('b', null, actor.nombre || actor.email || 'Usuario sin identificar'), actor.nombre && actor.email ? h('div', { className: 'muted' }, actor.email) : null),
            h('td', null, ACCIONES[evento.accion] || evento.accion || 'Acción registrada'),
            h('td', null, h('span', null, evento.entidad || '—'), evento.entidad_id ? h('span', { className: 'muted' }, ' · ' + evento.entidad_id) : null,
              resumen(evento) ? h('div', { className: 'muted' }, resumen(evento)) : null));
        }))),
        rows.length % PAGE_SIZE === 0 ? h('div', { style: { marginTop: 16, textAlign: 'center' } },
          h('button', { className: 'btn btn--ghost', disabled: loadingMore, onClick: function () { cargar(true); } }, loadingMore ? 'Cargando…' : 'Cargar más')) : null) : null);
  }

  window.CR.screens.Auditoria = Auditoria;
})();
