// js/components/widgets/notas_frete/NotaFreteViewModal.jsx
// [Wave NotasFrete 2026-05-19 v223.23] Extraído de pages/NotasFrete.jsx L619-709 (modal VIEW read-only).
// Props (5 objetos agregados): note, items, carrier, productMap, actions, helpers.
// Padrão: IIFE + window.ZNX.widgets.notas_frete.NotaFreteViewModal.
(function() {
  'use strict';

  function NotaFreteViewModal({ note, items, carrier, productMap, canManage, actions, helpers }) {
    const { onClose, onEdit, handleConfirmPickup, handleMarkInTransit, actionInFlight } = actions;
    const { fmtUSD, fmtShortDate, ViewStat, Th, statusBadge } = helpers;

    return (
      <Modal title={`📋 ${note.number}`} onClose={onClose} large>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* Cabeçalho com stats */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 8 }}>
            <ViewStat label="Status" value={statusBadge(note.status)} />
            <ViewStat label="Freteiro" value={carrier?.name || '—'} />
            <ViewStat label="Câmbio" value={Number(note.exchange_rate_usd_brl).toFixed(4)} />
            <ViewStat label="Custo Frete USD" value={fmtUSD(note.total_cost_usd)} />
            <ViewStat label="Emitida" value={fmtShortDate(note.emitted_at)} />
            <ViewStat label="Pickup" value={note.confirmed_carrier_at ? fmtShortDate(note.confirmed_carrier_at) : '—'} />
            <ViewStat label="Fechada" value={note.closed_at ? fmtShortDate(note.closed_at) : '—'} />
            <ViewStat label="Modelo" value={note.freight_model || '—'} />
          </div>

          {note.notes && (
            <div style={{ background: '#FEF9E7', border: '1px solid #FDE68A', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: '#92400E' }}>
              <strong>Notas:</strong> {note.notes}
            </div>
          )}

          {/* Items */}
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#374151', marginBottom: 8 }}>
              Items ({items.length})
            </div>
            {items.length === 0 ? (
              <div style={{ padding: 20, textAlign: 'center', color: '#9CA3AF' }}>Sem items.</div>
            ) : (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    <Th>Produto</Th>
                    <Th right>Esperado</Th>
                    <Th right>Recebido</Th>
                    <Th right>Custo USD/un.</Th>
                    <Th right>Sub-total USD</Th>
                  </tr>
                </thead>
                <tbody>
                  {items.map(it => {
                    const p = productMap[it.product_id];
                    const sub = Number(it.expected_qty) * Number(it.unit_cost_usd);
                    const allReceived = Number(it.received_qty) >= Number(it.expected_qty);
                    return (
                      <tr key={it.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                        <td style={{ padding: '8px 10px', fontWeight: 500 }}>
                          {p?.name || it.product_id}
                          {p?.volume && <span style={{ color: '#9CA3AF' }}> · {p.volume}</span>}
                        </td>
                        <td style={{ padding: '8px 10px', textAlign: 'right' }}>{it.expected_qty}</td>
                        <td style={{ padding: '8px 10px', textAlign: 'right', color: allReceived ? '#16A34A' : '#EA580C', fontWeight: 600 }}>
                          {it.received_qty}
                          {!allReceived && <span style={{ fontSize: 10, color: '#9CA3AF', marginLeft: 4 }}>(faltam {it.expected_qty - it.received_qty})</span>}
                        </td>
                        <td style={{ padding: '8px 10px', textAlign: 'right' }}>{fmtUSD(it.unit_cost_usd)}</td>
                        <td style={{ padding: '8px 10px', textAlign: 'right', fontWeight: 600 }}>{fmtUSD(sub)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>

          {/* Action buttons */}
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', flexWrap: 'wrap', marginTop: 8, paddingTop: 12, borderTop: '1px solid #E4E7EC' }}>
            <button className="btn-outline" onClick={onClose}>Fechar</button>
            {note.status === 'EMITIDA' && canManage && (
              <>
                <button className="btn-outline" onClick={onEdit}>
                  ✏️ Editar
                </button>
                <button className="btn-gold" disabled={actionInFlight}
                        onClick={() => handleConfirmPickup(note.id)}>
                  {actionInFlight ? '⏳ Aguarde...' : '✓ Confirmar Pickup'}
                </button>
              </>
            )}
            {note.status === 'CONFIRMADA_FRETEIRO' && canManage && (
              <button className="btn-gold" disabled={actionInFlight}
                      onClick={() => handleMarkInTransit(note.id)}>
                {actionInFlight ? '⏳ Aguarde...' : '🚚 Marcar Em Trânsito'}
              </button>
            )}
            {/* Após EM_TRANSITO: a ação é do Abbes (start_receiving via FRT-C3) */}
          </div>
        </div>
      </Modal>
    );
  }

  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.NotaFreteViewModal = NotaFreteViewModal;
})();
