// js/components/widgets/notas_frete/NotasFreteList.jsx
// [Wave NotasFrete 2026-05-19 v223.23] Extraído de pages/NotasFrete.jsx L376-470 (filtros + tabela).
// Props (4 objetos agregados): data, filters, actions, helpers.
// Usa Primitives.statusBadge + Primitives.Th do mesmo namespace.
// Padrão: IIFE + window.ZNX.widgets.notas_frete.NotasFreteList.
(function() {
  'use strict';

  function NotasFreteList({ data, filters, actions, helpers }) {
    const { filteredNotes, items, carriers, carrierMap, loading, error, canManage } = data;
    const { filterCarrierId, setFilterCarrierId, filterStatus, setFilterStatus, searchQ, setSearchQ } = filters;
    const { openViewModal, handleConfirmPickup, handleMarkInTransit, actionInFlight } = actions;
    const { fmtUSD, fmtShortDate, Th, statusBadge } = helpers;

    return (
      <>
        {/* Filtros */}
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 12 }}>
          <select value={filterCarrierId} onChange={e => setFilterCarrierId(e.target.value)}
                  style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid #E4E7EC', fontSize: 13 }}>
            <option value="">Todos os freteiros</option>
            {carriers.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
          </select>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
                  style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid #E4E7EC', fontSize: 13 }}>
            <option value="all">Todos os status</option>
            <option value="abertas">Em aberto (5 status)</option>
            <option value="fechadas">Fechadas (4 status)</option>
          </select>
          <input type="text" placeholder="Buscar por número, freteiro ou modelo..."
                 value={searchQ} onChange={e => setSearchQ(e.target.value)}
                 style={{ flex: 1, minWidth: 200, padding: '8px 12px', borderRadius: 8, border: '1px solid #E4E7EC', fontSize: 13 }} />
        </div>

        {/* Tabela */}
        {loading && <div style={{ padding: 40, textAlign: 'center', color: '#9CA3AF' }}>Carregando notas...</div>}
        {error && (
          <div style={{ padding: 16, background: '#FEE2E2', border: '1px solid #FCA5A5', borderRadius: 8, color: '#DC2626', marginBottom: 12 }}>
            <strong>Erro ao carregar:</strong> {error}
          </div>
        )}
        {!loading && !error && filteredNotes.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: '#9CA3AF', background: '#F9FAFB', borderRadius: 8 }}>
            {searchQ || filterCarrierId || filterStatus !== 'all' ? 'Nenhuma nota encontrada com os filtros aplicados.' : 'Nenhuma nota criada ainda. Clique em "Nova Nota" pra começar.'}
          </div>
        )}
        {!loading && !error && filteredNotes.length > 0 && (
          <div style={{ overflowX: 'auto', background: '#FFF', borderRadius: 8, border: '1px solid #E4E7EC' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#F9FAFB', borderBottom: '1px solid #E4E7EC' }}>
                  <Th>Número</Th>
                  <Th>Freteiro</Th>
                  <Th>Status</Th>
                  <Th right>Custo USD</Th>
                  <Th right>Câmbio</Th>
                  <Th right>Items</Th>
                  <Th>Emitida</Th>
                  <Th>Ações</Th>
                </tr>
              </thead>
              <tbody>
                {filteredNotes.map(n => {
                  const carrier = carrierMap[n.carrier_id];
                  const noteItems = items.filter(i => i.note_id === n.id);
                  const totalReceived = noteItems.reduce((s, i) => s + Number(i.received_qty || 0), 0);
                  const totalExpected = noteItems.reduce((s, i) => s + Number(i.expected_qty || 0), 0);
                  return (
                    <tr key={n.id} style={{ borderBottom: '1px solid #F3F4F6', cursor: 'pointer', transition: 'background .15s' }}
                        onClick={() => openViewModal(n)}
                        onMouseEnter={e => e.currentTarget.style.background = '#F9FAFB'}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <td style={{ padding: '10px 14px', fontFamily: 'monospace', fontWeight: 700 }}>{n.number}</td>
                      <td style={{ padding: '10px 14px' }}>{carrier?.name || '—'}</td>
                      <td style={{ padding: '10px 14px' }}>{statusBadge(n.status)}</td>
                      <td style={{ padding: '10px 14px', textAlign: 'right' }}>{fmtUSD(n.total_cost_usd)}</td>
                      <td style={{ padding: '10px 14px', textAlign: 'right', color: '#6B7280', fontSize: 12 }}>
                        {Number(n.exchange_rate_usd_brl).toFixed(4)}
                      </td>
                      <td style={{ padding: '10px 14px', textAlign: 'right', fontSize: 12, color: '#374151' }}>
                        {totalReceived}/{totalExpected}
                      </td>
                      <td style={{ padding: '10px 14px', color: '#6B7280', fontSize: 12 }}>{fmtShortDate(n.emitted_at)}</td>
                      <td style={{ padding: '10px 14px' }}>
                        {/* Buttons inline action conditional por status */}
                        <div style={{ display: 'flex', gap: 6 }} onClick={e => e.stopPropagation()}>
                          {n.status === 'EMITIDA' && canManage && (
                            <button className="btn-gold btn-sm" disabled={actionInFlight}
                                    onClick={() => handleConfirmPickup(n.id)}
                                    title="Freteiro pegou mercadoria"
                                    style={{ padding: '4px 8px', fontSize: 11 }}>
                              {actionInFlight ? '⏳' : '✓ Pickup'}
                            </button>
                          )}
                          {n.status === 'CONFIRMADA_FRETEIRO' && canManage && (
                            <button className="btn-outline btn-sm" disabled={actionInFlight}
                                    onClick={() => handleMarkInTransit(n.id)}
                                    title="Freteiro saiu pra rota"
                                    style={{ padding: '4px 8px', fontSize: 11 }}>
                              {actionInFlight ? '⏳' : '🚚 Em Trânsito'}
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.notas_frete = window.ZNX.widgets.notas_frete || {};
  window.ZNX.widgets.notas_frete.NotasFreteList = NotasFreteList;
})();
