// js/components/widgets/AprovacaoFreteList.jsx
// [Wave 13 v223.38 20260520] Extraído de AprovacoesFrete.jsx L346-466
// Lista de cards request + filtros (status + tipo) + empty state
//
// Props:
//   filteredRequests, filterStatus, setFilterStatus, filterType, setFilterType,
//   noteMap, carrierMap, productMap, userMap,
//   loading, error, isAdmin, user, canApprove, inFlight,
//   onApprove (req) => void, onDeny (req) => void
//
// Deps runtime: window.FreightTypeBadge, window.FreightStatusBadge, window.ZNX.lib.freight
(function(){
  'use strict';

  function AprovacaoFreteList(props){
    const filteredRequests = props.filteredRequests || [];
    const filterStatus = props.filterStatus;
    const setFilterStatus = props.setFilterStatus;
    const filterType = props.filterType;
    const setFilterType = props.setFilterType;
    const noteMap = props.noteMap || {};
    const carrierMap = props.carrierMap || {};
    const productMap = props.productMap || {};
    const userMap = props.userMap || {};
    const loading = props.loading;
    const error = props.error;
    const isAdmin = props.isAdmin;
    const user = props.user;
    const canApprove = props.canApprove;
    const inFlight = props.inFlight;
    const onApprove = props.onApprove;
    const onDeny = props.onDeny;

    const TypeBadge = window.FreightTypeBadge;
    const StatusBadge = window.FreightStatusBadge;
    const fmtUSD = (window.ZNX && window.ZNX.lib && window.ZNX.lib.freight && window.ZNX.lib.freight.fmtUSD) || function(v){ return 'US$ ' + v; };
    const fmtShortDate = (window.ZNX && window.ZNX.lib && window.ZNX.lib.freight && window.ZNX.lib.freight.fmtShortDate) || function(s){ return String(s); };

    if (typeof TypeBadge !== 'function' || typeof StatusBadge !== 'function') {
      console.error('[ZNX v223.38] Freight badges não carregaram');
      return <div style={{padding:20,color:'#DC2626'}}>Erro: componentes de badge ausentes</div>;
    }

    return (
      <>
        {/* Filtros */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 12, flexWrap: 'wrap' }}>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
                  style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid #E4E7EC', fontSize: 13 }}>
            <option value="pending">Pendentes</option>
            <option value="approved">Aprovadas</option>
            <option value="denied">Negadas</option>
            <option value="all">Todas</option>
          </select>
          <select value={filterType} onChange={e => setFilterType(e.target.value)}
                  style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid #E4E7EC', fontSize: 13 }}>
            <option value="all">Todos os tipos</option>
            <option value="close_with_loss">Fechar com perda</option>
            <option value="sku_surprise">SKU surpresa</option>
            <option value="qty_extra">Qty extra</option>
          </select>
        </div>

        {/* States */}
        {loading && <div style={{ padding: 40, textAlign: 'center', color: '#9CA3AF' }}>Carregando...</div>}
        {error && (
          <div style={{ padding: 16, background: '#FEE2E2', border: '1px solid #FCA5A5', borderRadius: 8, color: '#DC2626' }}>
            <strong>Erro:</strong> {error}
          </div>
        )}
        {!loading && !error && filteredRequests.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: '#9CA3AF', background: '#F9FAFB', borderRadius: 8 }}>
            <div style={{ fontSize: 36, marginBottom: 8 }}>📭</div>
            <div style={{ fontWeight: 600 }}>Nenhuma solicitação {filterStatus === 'pending' ? 'pendente' : ''}.</div>
          </div>
        )}

        {/* Cards */}
        {filteredRequests.map(r => {
          const note = noteMap[r.note_id];
          const carrier = note ? carrierMap[note.carrier_id] : null;
          const requester = userMap[r.requested_by];
          const evidenceCount = Array.isArray(r.evidence_photos) ? r.evidence_photos.length : 0;
          return (
            <div key={r.id} style={{
              background: '#FFF', border: '1px solid #E4E7EC', borderRadius: 10,
              padding: 16, marginBottom: 10, display: 'flex', gap: 14,
              alignItems: 'flex-start', flexWrap: 'wrap',
            }}>
              <div style={{ flex: 1, minWidth: 280 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8, flexWrap: 'wrap' }}>
                  <TypeBadge type={r.type}/>
                  <StatusBadge status={r.status}/>
                  <span style={{ fontFamily: 'monospace', fontSize: 13, fontWeight: 700, color: '#1B2A4A' }}>
                    {(note && note.number) || r.note_id}
                  </span>
                  <span style={{ fontSize: 12, color: '#6B7280' }}>{(carrier && carrier.name) || '—'}</span>
                </div>
                <div style={{ fontSize: 12, color: '#6B7280', marginBottom: 6 }}>
                  Solicitado por <strong>{(requester && requester.name) || '—'}</strong> · {fmtShortDate(r.created_at)}
                </div>
                {r.type === 'close_with_loss' && (
                  <div style={{ fontSize: 13, color: '#374151', marginBottom: 6 }}>
                    <strong>{r.loss_qty_total} un. faltando</strong>
                    {(isAdmin || (user && user.role === 'financeiro')) && (
                      <span style={{ marginLeft: 8, color: '#DC2626' }}>· perda {fmtUSD(r.loss_value_usd)}</span>
                    )}
                  </div>
                )}
                {r.type === 'sku_surprise' && (
                  <div style={{ fontSize: 13, color: '#374151', marginBottom: 6 }}>
                    SKU não cadastrado: <strong>{(productMap[((r.reason || '').match(/[a-f0-9-]{36}/) || [])[0]] || {}).name || 'desconhecido'}</strong>
                    {' '}· qty <strong>{r.loss_qty_total}</strong>
                  </div>
                )}
                {r.type === 'qty_extra' && (
                  <div style={{ fontSize: 13, color: '#374151', marginBottom: 6 }}>
                    Qty extra: <strong>{r.loss_qty_total} un.</strong>
                  </div>
                )}
                {r.reason && (
                  <div style={{ fontSize: 12, color: '#6B7280', fontStyle: 'italic', marginBottom: 6, padding: 8, background: '#F9FAFB', borderRadius: 6 }}>
                    "{r.reason}"
                  </div>
                )}
                {evidenceCount > 0 && (
                  <div style={{ fontSize: 11, color: '#7C3AED', marginBottom: 4 }}>
                    📎 {evidenceCount} evidência{evidenceCount > 1 ? 's' : ''}: {(r.evidence_photos || []).slice(0, 2).map(e => e.slice(0, 40)).join(' · ')}
                  </div>
                )}
                {r.status !== 'pending' && r.admin_notes && (
                  <div style={{ fontSize: 12, color: r.status === 'denied' ? '#DC2626' : '#16A34A', marginTop: 8, padding: 8, background: r.status === 'denied' ? '#FEE2E2' : '#DCFCE7', borderRadius: 6 }}>
                    <strong>Admin:</strong> "{r.admin_notes}"
                    <div style={{ fontSize: 11, color: '#9CA3AF', marginTop: 2 }}>
                      Resolvido por {(userMap[r.resolved_by] || {}).name || '—'} em {fmtShortDate(r.resolved_at)}
                    </div>
                  </div>
                )}
              </div>

              {r.status === 'pending' && canApprove && (
                <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                  <button className="btn-gold" onClick={() => onApprove(r)} disabled={inFlight}
                          style={{ padding: '8px 14px', fontSize: 13 }}>
                    ✓ Aprovar
                  </button>
                  <button className="btn-danger" onClick={() => onDeny(r)} disabled={inFlight}
                          style={{ padding: '8px 14px', fontSize: 13 }}>
                    ✗ Negar
                  </button>
                </div>
              )}
              {r.status === 'pending' && !canApprove && (
                <div style={{ fontSize: 11, color: '#9CA3AF', alignSelf: 'center' }}>
                  (admin only)
                </div>
              )}
            </div>
          );
        })}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.AprovacaoFreteList = AprovacaoFreteList;
  window.AprovacaoFreteList = AprovacaoFreteList;
})();
