// js/components/widgets/ReceiveBatchView.jsx
// [Wave 14 v223.39 20260520] Extraído de ReceberFrete.jsx L458-608
// View 'receive' MOBILE-FIRST — items + FAB sticky bottom + atalhos (SKU surprise, perda)
//
// Props:
//   selectedNote, selectedItems, productMap, carrierMap,
//   qtyToAdd, setQtyToAdd, batchTotal, totalMissing,
//   actionInFlight, submitting,
//   onBack () => void,
//   onStartReceiving () => Promise,
//   onSubmitBatch () => Promise,
//   onOpenSurprise () => void,
//   onOpenLoss () => void
// Deps runtime: window.FreightNoteStatusBadge
(function(){
  'use strict';

  function ReceiveBatchView(props){
    const selectedNote = props.selectedNote;
    const selectedItems = props.selectedItems || [];
    const productMap = props.productMap || {};
    const carrierMap = props.carrierMap || {};
    const qtyToAdd = props.qtyToAdd || {};
    const setQtyToAdd = props.setQtyToAdd;
    const batchTotal = props.batchTotal || 0;
    const totalMissing = props.totalMissing || 0;
    const actionInFlight = props.actionInFlight;
    const submitting = props.submitting;
    const onBack = props.onBack;
    const onStartReceiving = props.onStartReceiving;
    const onSubmitBatch = props.onSubmitBatch;
    const onOpenSurprise = props.onOpenSurprise;
    const onOpenLoss = props.onOpenLoss;

    const Badge = window.FreightNoteStatusBadge;

    if (!selectedNote) return null;
    const carrier = carrierMap[selectedNote.carrier_id];
    const isInTransit = selectedNote.status === 'EM_TRANSITO';

    return (
      <div className="page-content" style={{ padding: 0, paddingBottom: 120, maxWidth: 800, margin: '0 auto' }}>
        {/* Header sticky */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 10,
          background: '#FFF', borderBottom: '1px solid #E4E7EC',
          padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <button onClick={onBack}
                  style={{
                    background: '#F3F4F6', border: 'none', borderRadius: 8,
                    width: 40, height: 40, fontSize: 20, cursor: 'pointer',
                  }}>
            ←
          </button>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 800, fontFamily: 'monospace', color: '#1B2A4A' }}>{selectedNote.number}</div>
            <div style={{ fontSize: 12, color: '#6B7280' }}>{carrier && carrier.name}</div>
          </div>
          {Badge && <Badge status={selectedNote.status}/>}
        </div>

        {/* Banner EM_TRANSITO */}
        {isInTransit && (
          <div style={{ padding: 16, background: '#FEF3C7', border: '1px solid #FDE68A', margin: 14, borderRadius: 10 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#92400E', marginBottom: 6 }}>
              🚚 Nota em trânsito
            </div>
            <div style={{ fontSize: 12, color: '#78350F', marginBottom: 10 }}>
              Antes de registrar entradas, marca que começou o recebimento.
              (ou já registra direto: o sistema flipa automático ao primeiro item.)
            </div>
            <button className="btn-gold" onClick={onStartReceiving} disabled={actionInFlight}
                    style={{ width: '100%', padding: '12px', fontSize: 14, fontWeight: 700 }}>
              {actionInFlight ? '⏳ Iniciando...' : '✓ Iniciar recebimento'}
            </button>
          </div>
        )}

        {/* Items */}
        <div style={{ padding: 16 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 0.5 }}>
            Items da nota ({selectedItems.length})
          </div>

          {selectedItems.map(it => {
            const p = productMap[it.product_id];
            const expected = Number(it.expected_qty || 0);
            const received = Number(it.received_qty || 0);
            const missing = Math.max(0, expected - received);
            const inputVal = qtyToAdd[it.id] || '';
            const isComplete = missing === 0;
            return (
              <div key={it.id} style={{
                background: isComplete ? '#F0FDF4' : '#FFF',
                border: '1px solid ' + (isComplete ? '#BBF7D0' : '#E4E7EC'),
                borderRadius: 12, padding: 14, marginBottom: 10,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8, gap: 8 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: '#1B2A4A' }}>
                      {(p && p.name) || it.product_id}
                    </div>
                    {p && p.volume && <div style={{ fontSize: 12, color: '#9CA3AF', marginTop: 2 }}>{p.volume}</div>}
                  </div>
                  {isComplete && <span style={{ fontSize: 18 }}>✅</span>}
                </div>

                <div style={{ display: 'flex', gap: 8, fontSize: 12, color: '#6B7280', marginBottom: 10 }}>
                  <span>📋 Esperado: <strong style={{ color: '#374151' }}>{expected}</strong></span>
                  <span>·</span>
                  <span>📦 Recebido: <strong style={{ color: received >= expected ? '#16A34A' : '#EA580C' }}>{received}</strong></span>
                  {missing > 0 && (<>
                    <span>·</span>
                    <span style={{ color: '#DC2626' }}>Faltam: <strong>{missing}</strong></span>
                  </>)}
                </div>

                {!isComplete && (
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <input
                      type="number" inputMode="numeric" min="0" max={missing * 2}
                      placeholder={'+' + missing + ' un.'}
                      value={inputVal}
                      onChange={e => setQtyToAdd(q => Object.assign({}, q, { [it.id]: e.target.value }))}
                      style={{
                        flex: 1, padding: '12px 14px', fontSize: 16, fontWeight: 600,
                        border: '1px solid #E4E7EC', borderRadius: 10,
                      }}
                    />
                    <button
                      onClick={() => setQtyToAdd(q => Object.assign({}, q, { [it.id]: String(missing) }))}
                      className="btn-outline"
                      style={{ padding: '10px 14px', fontSize: 12, whiteSpace: 'nowrap' }}>
                      Tudo ({missing})
                    </button>
                  </div>
                )}
              </div>
            );
          })}

          {/* Atalhos secundários */}
          <div style={{ marginTop: 18, padding: 14, background: '#F9FAFB', borderRadius: 10 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#6B7280', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Casos especiais
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 8 }}>
              <button className="btn-outline" onClick={onOpenSurprise} disabled={isInTransit}
                      style={{ padding: 12, fontSize: 13, textAlign: 'left' }}>
                🆕 SKU surpresa (SKU não estava na nota)
              </button>
              <button className="btn-outline" onClick={onOpenLoss} disabled={isInTransit || totalMissing === 0}
                      style={Object.assign({ padding: 12, fontSize: 13, textAlign: 'left' }, totalMissing === 0 ? { opacity: 0.5 } : {})}>
                ❌ Solicitar fechamento com perda
                {totalMissing === 0 && <span style={{ fontSize: 11, color: '#9CA3AF' }}> (sem itens faltando)</span>}
              </button>
            </div>
          </div>
        </div>

        {/* FAB sticky bottom */}
        {batchTotal > 0 && (
          <div style={{
            position: 'fixed', bottom: 0, left: 0, right: 0,
            background: '#FFF', borderTop: '1px solid #E4E7EC',
            padding: 14, boxShadow: '0 -2px 8px rgba(0,0,0,0.06)',
            zIndex: 100,
          }}>
            <div style={{ maxWidth: 800, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ flex: 1, fontSize: 13 }}>
                <strong style={{ fontSize: 18, color: '#1B2A4A' }}>{batchTotal} un.</strong>
                <span style={{ color: '#6B7280', marginLeft: 6 }}>pra registrar</span>
              </div>
              <button className="btn-gold" onClick={onSubmitBatch} disabled={submitting}
                      style={{ padding: '12px 20px', fontSize: 14, fontWeight: 700, minWidth: 140 }}>
                {submitting ? '⏳ Enviando...' : '📥 Registrar entrada'}
              </button>
            </div>
          </div>
        )}
      </div>
    );
  }

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