// js/components/widgets/auditoria/LogsTable.jsx
// [Wave W1 PLAN 2026-05-18 v223.21] Extraído de AuditoriaAdmin.jsx L453-515 (tabela principal + footer).
// Props (8): filtered, logs, loading, userName, actionLabel, actionColor, fmtDateSafe, setSelectedRowId.
// Padrão: IIFE + window.ZNX.widgets.auditoria.LogsTable.
(function() {
  'use strict';

  function LogsTable({filtered, logs, loading, userName, actionLabel, actionColor, fmtDateSafe, setSelectedRowId}) {
    return (
      <>
        <div className="card" style={{padding:0}}>
          {filtered.length === 0 ? (
            <div style={{padding:40,textAlign:'center',color:'#9CA3AF'}}>
              <div style={{fontSize:36,marginBottom:8}}>📋</div>
              <div style={{fontSize:14,fontWeight:600}}>{loading ? 'Carregando...' : 'Nenhuma ação registrada no período'}</div>
              {!loading && logs.length === 0 && (
                <div style={{fontSize:12,marginTop:6}}>Triggers automáticos vão começar a logar quando admin/financeiro fizer ações sensíveis (cancelar venda, aprovar desconto, etc).</div>
              )}
            </div>
          ) : (
            <table>
              <thead>
                <tr>
                  <th style={{width:130}}>Quando</th>
                  <th>Ação</th>
                  <th style={{width:160}}>Quem</th>
                  <th>Alvo</th>
                  <th style={{width:80}}>Detalhes</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(log => {
                  const cor = actionColor(log.action);
                  return (
                    <tr key={log.id} style={{cursor:'pointer'}} onClick={()=>setSelectedRowId(log.id)}>
                      <td style={{fontSize:11,color:'#6B7280',whiteSpace:'nowrap'}}>
                        {/* [ONDA1-A 2026-05-11] regra_fmtdate_aceita_string_iso — created_at é ISO timestamp completo,
                            fmtDate só aceita 'YYYY-MM-DD'. Usar fmtDateSafe (já existe local, normaliza ISO→date). */}
                        {fmtDateSafe(log.created_at)}
                        <div style={{fontSize:10,color:'#9CA3AF'}}>{new Date(log.created_at).toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit',second:'2-digit'})}</div>
                      </td>
                      <td>
                        <span style={{padding:'3px 10px',borderRadius:6,background:cor+'22',color:cor,fontSize:11,fontWeight:700}}>{actionLabel(log.action)}</span>
                        {log.reason && <div style={{fontSize:11,color:'#6B7280',marginTop:3,fontStyle:'italic'}}>"{log.reason.slice(0,60)}{log.reason.length>60?'...':''}"</div>}
                      </td>
                      <td>
                        <div style={{fontWeight:600,fontSize:12}}>{userName(log.actor_id)}</div>
                        {log.actor_role && <div style={{fontSize:10,color:'#9CA3AF',textTransform:'capitalize'}}>{log.actor_role}</div>}
                      </td>
                      <td style={{fontSize:11}}>
                        <span style={{color:'#374151',fontWeight:600,textTransform:'capitalize'}}>{log.target_type}</span>
                        {log.target_id && <div style={{color:'#9CA3AF',fontSize:10,fontFamily:'monospace'}}>{log.target_id.slice(0,16)}...</div>}
                        {log.metadata && Object.keys(log.metadata).length>0 && (
                          <div style={{fontSize:10,color:'#7C3AED',marginTop:2}}>{Object.entries(log.metadata).slice(0,2).map(([k,v])=>`${k}: ${String(v).slice(0,20)}`).join(' · ')}</div>
                        )}
                      </td>
                      <td style={{textAlign:'center'}}>
                        <button onClick={(e)=>{e.stopPropagation();setSelectedRowId(log.id);}} className="btn-outline btn-sm" style={{background:'#FEF9E7',borderColor:'#B89840',color:'#B89840'}}>👁</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>

        {filtered.length > 0 && (
          <div style={{marginTop:10,fontSize:11,color:'#9CA3AF',textAlign:'right'}}>
            {filtered.length} de {logs.length} ações · Limite 500 mais recentes do período
          </div>
        )}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.auditoria = window.ZNX.widgets.auditoria || {};
  window.ZNX.widgets.auditoria.LogsTable = LogsTable;
})();
