// js/components/widgets/freteiros/Ficha360Modal.jsx
// [Wave 31 v224.12 NUCLEAR EXTRACT 2026-05-24] Modal Ficha 360° freteiro (3 tabs: Notas + Extrato + Score)
// Extract LITERAL de Freteiros.jsx L425-562
//
// Props:
//   - selectedCarrier — carrier obj (null se modal fechado)
//   - selectedCarrierNotes — array
//   - selectedCarrierTxns — array
//   - selectedCarrierScore — score obj
//   - activeTab, setActiveTab — tab state (vem do main pra preservar)
//   - onClose — handler que limpa selectedCarrierId
// Deps lazy: window.Modal (global), SharedComponents.{Th, FichaStat, NoteStatusBadge}
//            ZNX.freteiros.calcs.{fmtUSD, fmtPct, fmtShortDate, scoreColor, txnTypeLabel}
(function(){
  'use strict';
  function Ficha360Modal(props){
    const Modal = window.Modal;
    const SC = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.freteiros && window.ZNX.widgets.freteiros.SharedComponents;
    const calcs = window.ZNX && window.ZNX.freteiros && window.ZNX.freteiros.calcs;
    const { selectedCarrier, selectedCarrierNotes, selectedCarrierTxns, selectedCarrierScore,
            activeTab, setActiveTab, onClose } = props;
    if(!selectedCarrier || !Modal || !SC || !calcs) return null;
    const Th = SC.Th;
    const FichaStat = SC.FichaStat;
    const NoteStatusBadge = SC.NoteStatusBadge;
    const fmtUSD = calcs.fmtUSD;
    const fmtPct = calcs.fmtPct;
    const fmtShortDate = calcs.fmtShortDate;
    const scoreColor = calcs.scoreColor;
    const txnTypeLabel = calcs.txnTypeLabel;

    return (
      <Modal
        title={`🚚 ${selectedCarrier.name}`}
        onClose={onClose}
        large
      >
        {/* Header da ficha [LITERAL L432-440] */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10, marginBottom: 16 }}>
          <FichaStat label="Saldo conta corrente" value={fmtUSD(selectedCarrier.current_balance_usd)}
                     color={Number(selectedCarrier.current_balance_usd) >= 0 ? '#16A34A' : '#DC2626'} />
          <FichaStat label="Garantia depositada" value={fmtUSD(selectedCarrier.guarantee_usd)} color="#7C3AED" />
          <FichaStat label="Comissão %" value={fmtPct(selectedCarrier.commission_pct)} color="#2563EB" />
          <FichaStat label="Score" value={(selectedCarrierScore?.score || 0) + '/100'}
                     color={scoreColor(selectedCarrierScore?.score || 0)} />
        </div>

        {/* Tabs [LITERAL L442-460] */}
        <div style={{ borderBottom: '1px solid #E4E7EC', marginBottom: 12, display: 'flex', gap: 4 }}>
          {[['notes', '📋 Notas (' + selectedCarrierNotes.length + ')'],
            ['extrato', '📊 Extrato (' + selectedCarrierTxns.length + ')'],
            ['score', '⭐ Score']].map(([id, lbl]) => (
            <div key={id}
                 onClick={() => setActiveTab(id)}
                 style={{
                   padding: '8px 16px',
                   cursor: 'pointer',
                   borderBottom: activeTab === id ? '2px solid #2563EB' : '2px solid transparent',
                   color: activeTab === id ? '#2563EB' : '#6B7280',
                   fontWeight: activeTab === id ? 700 : 500,
                   fontSize: 13,
                 }}>
              {lbl}
            </div>
          ))}
        </div>

        {/* TAB: Notas [LITERAL L462-494] */}
        {activeTab === 'notes' && (
          <div style={{ maxHeight: '50vh', overflowY: 'auto' }}>
            {selectedCarrierNotes.length === 0 ? (
              <div style={{ padding: 30, textAlign: 'center', color: '#9CA3AF' }}>Nenhuma nota emitida pra este freteiro ainda.</div>
            ) : (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    <Th>Número</Th>
                    <Th>Status</Th>
                    <Th right>Custo USD</Th>
                    <Th right>Câmbio</Th>
                    <Th>Emitida</Th>
                    <Th>Fechada</Th>
                  </tr>
                </thead>
                <tbody>
                  {selectedCarrierNotes.map(n => (
                    <tr key={n.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                      <td style={{ padding: '8px 10px', fontFamily: 'monospace', fontWeight: 600 }}>{n.number}</td>
                      <td style={{ padding: '8px 10px' }}><NoteStatusBadge status={n.status} /></td>
                      <td style={{ padding: '8px 10px', textAlign: 'right' }}>{fmtUSD(n.total_cost_usd)}</td>
                      <td style={{ padding: '8px 10px', textAlign: 'right', color: '#6B7280' }}>{Number(n.exchange_rate_usd_brl).toFixed(4)}</td>
                      <td style={{ padding: '8px 10px', color: '#6B7280' }}>{fmtShortDate(n.emitted_at)}</td>
                      <td style={{ padding: '8px 10px', color: '#6B7280' }}>{n.closed_at ? fmtShortDate(n.closed_at) : '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {/* TAB: Extrato [LITERAL L496-532] */}
        {activeTab === 'extrato' && (
          <div style={{ maxHeight: '50vh', overflowY: 'auto' }}>
            {selectedCarrierTxns.length === 0 ? (
              <div style={{ padding: 30, textAlign: 'center', color: '#9CA3AF' }}>Nenhuma transação ainda.</div>
            ) : (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    <Th>Data</Th>
                    <Th>Tipo</Th>
                    <Th>Descrição</Th>
                    <Th right>Valor USD</Th>
                    <Th right>Saldo após</Th>
                  </tr>
                </thead>
                <tbody>
                  {selectedCarrierTxns.map(t => (
                    <tr key={t.id} style={{ borderBottom: '1px solid #F3F4F6' }}>
                      <td style={{ padding: '8px 10px', color: '#6B7280' }}>{fmtShortDate(t.created_at)}</td>
                      <td style={{ padding: '8px 10px', fontSize: 11 }}>{txnTypeLabel(t.type)}</td>
                      <td style={{ padding: '8px 10px', fontSize: 11, color: '#374151', maxWidth: 250, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {t.description}
                      </td>
                      <td style={{ padding: '8px 10px', textAlign: 'right', fontWeight: 700, color: Number(t.amount_usd) >= 0 ? '#16A34A' : '#DC2626' }}>
                        {Number(t.amount_usd) >= 0 ? '+' : ''}{fmtUSD(t.amount_usd)}
                      </td>
                      <td style={{ padding: '8px 10px', textAlign: 'right', color: '#6B7280' }}>
                        {fmtUSD(t.balance_after_usd)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {/* TAB: Score breakdown [LITERAL L534-560] */}
        {activeTab === 'score' && selectedCarrierScore && (
          <div style={{ padding: 12 }}>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <div style={{
                fontSize: 64, fontWeight: 800,
                color: scoreColor(selectedCarrierScore.score),
                lineHeight: 1,
              }}>
                {selectedCarrierScore.score}
              </div>
              <div style={{ fontSize: 13, color: '#6B7280', marginTop: 4 }}>de 100</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 }}>
              <FichaStat label="Notas COMPLETAS" value={selectedCarrierScore.completas} color="#16A34A" />
              <FichaStat label="Notas com perda" value={selectedCarrierScore.com_perda} color="#DC2626" />
              <FichaStat label="Total movimentado" value={fmtUSD(selectedCarrierScore.valor_transp)} color="#7C3AED" />
              <FichaStat label="Perda acumulada" value={fmtUSD(selectedCarrierScore.perda_usd)} color="#EA580C" />
              <FichaStat label="% perda" value={fmtPct(selectedCarrierScore.perda_pct)} color="#DC2626" />
            </div>
            <div style={{ marginTop: 16, padding: 12, background: '#F0F9FF', border: '1px solid #BAE6FD', borderRadius: 8, fontSize: 12, color: '#0C4A6E' }}>
              <strong>Como o score é calculado:</strong><br/>
              <code style={{ fontSize: 11 }}>100 − (perda% × 5) − (notas_com_perda × 2), clamp 0..100</code><br/>
              Score &lt;60: revisar contrato. Score 60-85: monitorar. Score ≥85: confiável.
            </div>
          </div>
        )}
      </Modal>
    );
  }
  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.freteiros = window.ZNX.widgets.freteiros || {};
  window.ZNX.widgets.freteiros.Ficha360Modal = Ficha360Modal;
  // [Wave 31 marker v224.12] confirma Ficha360Modal executado
  window.FreteirosFicha360_v224_12_wave31 = true;
})();
