// js/components/widgets/FreightNoteList.jsx
// [Wave 14 v223.39 20260520] Extraído de ReceberFrete.jsx L369-452
// View 'list' MOBILE-FIRST — filter carrier + cards notas com progress bar
//
// Props:
//   filteredNotes, items, carriers, carrierMap,
//   filterCarrier, setFilterCarrier,
//   loading, error,
//   onOpenNote (note) => void
// Deps runtime: window.FreightNoteStatusBadge, window.ZNX.lib.freight.fmtShortDate
(function(){
  'use strict';

  function FreightNoteList(props){
    const filteredNotes = props.filteredNotes || [];
    const items = props.items || [];
    const carriers = props.carriers || [];
    const carrierMap = props.carrierMap || {};
    const filterCarrier = props.filterCarrier;
    const setFilterCarrier = props.setFilterCarrier;
    const loading = props.loading;
    const error = props.error;
    const onOpenNote = props.onOpenNote;

    const Badge = window.FreightNoteStatusBadge;
    const fmtShortDate = (window.ZNX && window.ZNX.lib && window.ZNX.lib.freight && window.ZNX.lib.freight.fmtShortDate) || function(s){ return String(s || '—'); };

    if (typeof Badge !== 'function') {
      console.error('[ZNX v223.39] FreightNoteStatusBadge não carregou');
      return <div style={{padding:20,color:'#DC2626'}}>Erro: badge ausente</div>;
    }

    return (
      <div className="page-content" style={{ padding: 16, paddingBottom: 100, maxWidth: 800, margin: '0 auto' }}>
        {/* Header mobile */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 24, fontWeight: 800, color: '#1B2A4A', display: 'flex', alignItems: 'center', gap: 8 }}>
            📥 Receber Frete
          </div>
          <div style={{ fontSize: 13, color: '#6B7280', marginTop: 4 }}>
            Notas em rota disponíveis pra recebimento
          </div>
        </div>

        {/* Filter */}
        <select value={filterCarrier} onChange={e => setFilterCarrier(e.target.value)}
                style={{ width: '100%', padding: '12px 14px', borderRadius: 10, border: '1px solid #E4E7EC', fontSize: 14, marginBottom: 14, background: '#FFF' }}>
          <option value="">Todos os freteiros</option>
          {carriers.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
        </select>

        {loading && <div style={{ padding: 40, textAlign: 'center', color: '#9CA3AF' }}>Carregando...</div>}
        {error && (
          <div style={{ padding: 14, background: '#FEE2E2', border: '1px solid #FCA5A5', borderRadius: 8, color: '#DC2626' }}>
            <strong>Erro:</strong> {error}
          </div>
        )}
        {!loading && !error && filteredNotes.length === 0 && (
          <div style={{ padding: 50, textAlign: 'center', color: '#9CA3AF', background: '#F9FAFB', borderRadius: 10 }}>
            <div style={{ fontSize: 36, marginBottom: 8 }}>📭</div>
            <div style={{ fontWeight: 600 }}>Nenhuma nota em rota.</div>
            <div style={{ fontSize: 12, marginTop: 4 }}>
              {filterCarrier ? 'Tente outro freteiro' : 'Aguardando Amir confirmar pickup'}
            </div>
          </div>
        )}

        {/* Lista cards (mobile-first) */}
        {!loading && !error && filteredNotes.map(n => {
          const carrier = carrierMap[n.carrier_id];
          const noteItems = items.filter(i => i.note_id === n.id);
          const totalExpected = noteItems.reduce((s, i) => s + Number(i.expected_qty || 0), 0);
          const totalReceived = noteItems.reduce((s, i) => s + Number(i.received_qty || 0), 0);
          const pct = totalExpected > 0 ? Math.round(totalReceived / totalExpected * 100) : 0;
          return (
            <div key={n.id}
                 onClick={() => onOpenNote(n)}
                 style={{
                   background: '#FFF', border: '1px solid #E4E7EC', borderRadius: 12,
                   padding: 16, marginBottom: 12, cursor: 'pointer',
                   boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
                 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8, gap: 8 }}>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 800, fontFamily: 'monospace', color: '#1B2A4A' }}>{n.number}</div>
                  <div style={{ fontSize: 13, color: '#6B7280', marginTop: 2 }}>{(carrier && carrier.name) || '—'}</div>
                </div>
                <Badge status={n.status}/>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#6B7280', marginBottom: 8 }}>
                <span>Emitida {fmtShortDate(n.emitted_at)}</span>
                <span>{noteItems.length} item{noteItems.length !== 1 ? 's' : ''}</span>
              </div>
              <div style={{ background: '#F3F4F6', borderRadius: 999, height: 8, overflow: 'hidden' }}>
                <div style={{
                  width: pct + '%', height: '100%',
                  background: pct === 100 ? '#16A34A' : pct > 0 ? '#2563EB' : '#E5E7EB',
                  transition: 'width .3s',
                }} />
              </div>
              <div style={{ fontSize: 11, color: '#6B7280', marginTop: 6, textAlign: 'right' }}>
                {totalReceived}/{totalExpected} ({pct}%)
              </div>
            </div>
          );
        })}
      </div>
    );
  }

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