// js/components/widgets/entradas/WarehouseTransferPanel.jsx
// [Backlog #590 2026-05-16] Extraído de Entradas.jsx L740-956 — refactor zero-RPC zero-lógica.
// Padrão: IIFE + window.ZNX.widgets.entradas.X namespace + props injection.
//
// Strategy B (variant pattern): 1 widget reusável substitui as DUAS metades duplicadas
// (falt_alf + falt_sen) que eram 85% idênticas — diferem só em tema (amber/blue), source
// (faltaAlfonso/faltaSenador), sel state (selectedFaltAlf/selectedFaltSen) e direção transfer.
//
// variant='alfonso' = mostra "Falta no Alfonso (mover do Senador)" + tema amber/dourado
// variant='senador' = mostra "Falta no Senador (revisar)" + tema blue
//
// Props (validados FASE 1.5 = 13 props):
//   list: array — produtos faltando (faltaAlfonso ou faltaSenador)
//   totals: object {skus, un, valor} — totals do panel
//   sel: Map — seleção atual (selectedFaltAlf ou selectedFaltSen)
//   variant: 'alfonso' | 'senador' — controla tema/labels/direction
//   canSeeCost: bool — gate coluna VALOR
//   clearSelection: fn(tabKey) — limpa seleção
//   selectAll: fn(tabKey, list) — seleciona todos
//   toggleSelect: fn(tabKey, id, qty) — toggle individual
//   setItemQty: fn(tabKey, id, qty, maxQty) — edita qty editável
//   bulkTransfer: fn(direction) — RPC transfer_request (NÃO MEXER)
//   totalSelectedUn: fn(sel) → number — soma unidades selecionadas
//   bulkXferInflightRef: useRef — loading state (regra_loading_state_obrigatorio)
//   bulkXferProgress: object {done, total} | null — progress display
//
// Deps runtime globals: fmt (window.fmt), Icon (componente global).
(function() {
  'use strict';

  function WarehouseTransferPanel({list, totals, sel, variant, canSeeCost, clearSelection, selectAll, toggleSelect, setItemQty, bulkTransfer, totalSelectedUn, bulkXferInflightRef, bulkXferProgress}){
    // Theme derivation per variant
    const isAlfonso = variant==='alfonso';
    const tabKey = isAlfonso ? 'falt_alf' : 'falt_sen';
    const direction = isAlfonso ? 'senador_to_alfonso' : 'alfonso_to_senador';
    const directionLabel = isAlfonso ? 'Senador → Alfonso' : 'Alfonso → Senador';
    const themeBg = isAlfonso ? 'linear-gradient(135deg,#FEF3C7 0%,#FDE68A 100%)' : 'linear-gradient(135deg,#DBEAFE 0%,#BFDBFE 100%)';
    const themeBorder = isAlfonso ? '#D97706' : '#2563EB';
    const themeTitleColor = isAlfonso ? '#92400E' : '#1E40AF';
    const themeDescColor = isAlfonso ? '#78350F' : '#1E3A8A';
    const title = isAlfonso ? '⚠️ Falta no Alfonso (mover do Senador)' : 'ℹ️ Falta no Senador (revisar — pode ser exclusivo do Alfonso)';
    const description = isAlfonso
      ? <>Produtos disponíveis no <b>Senador</b> mas com estoque ZERO no <b>Alfonso</b> (PDV principal de saída). Marque o SKU e <b>edite a quantidade</b> que quer transferir (1 até o total disponível). Clique <b>Transferir</b> pra criar os pedidos.</>
      : <>Produtos disponíveis no <b>Alfonso</b> mas com estoque ZERO no <b>Senador</b>. Marque o SKU e <b>edite a quantidade</b> que quer transferir (1 até o total disponível). Use com cuidado — Alfonso é o PDV principal.</>;
    const skuColor = isAlfonso ? '#D97706' : '#2563EB';
    const valuePotentialBg = isAlfonso ? 'linear-gradient(135deg,#FEF3C7 0%,#FDE68A 100%)' : 'linear-gradient(135deg,#DBEAFE 0%,#BFDBFE 100%)';
    const valuePotentialColor = isAlfonso ? '#92400E' : '#1E40AF';
    const valuePotentialLabel = isAlfonso ? 'Unidades no Senador' : 'Unidades no Alfonso';
    const transferBg = isAlfonso ? '#EFF6FF' : '#FEF3C7';
    const transferLabelColor = isAlfonso ? '#1E40AF' : '#92400E';
    const transferValueColor = isAlfonso ? '#2563EB' : '#D97706';
    const transferUnColor = isAlfonso ? '#1E40AF' : '#92400E';
    const rowHighlightBg = isAlfonso ? '#FEF3C7' : '#DBEAFE';
    const qtyColor = isAlfonso ? '#D97706' : '#2563EB';
    const maxBtnBorder = isAlfonso ? '#D97706' : '#2563EB';
    const maxBtnBg = isAlfonso ? '#FEF3C7' : '#DBEAFE';
    const maxBtnColor = isAlfonso ? '#92400E' : '#1E40AF';
    const emptyMsg = isAlfonso
      ? '✅ Nada faltando em Alfonso. Tudo que está em Senador também está em Alfonso.'
      : '✅ Nada faltando em Senador. Tudo que está em Alfonso também está em Senador.';

    const allSelected = list.length>0 && list.every(x=>sel.has(x.id));
    const totalUn = totalSelectedUn(sel);
    return (
      <div>
        {/* Header explicativo */}
        <div className="card" style={{padding:14,marginBottom:14,background:themeBg,borderLeft:`4px solid ${themeBorder}`}}>
          <div style={{fontWeight:700,color:themeTitleColor,marginBottom:4}}>{title}</div>
          <div style={{fontSize:13,color:themeDescColor,lineHeight:1.5}}>{description}</div>
        </div>
        {/* Stats */}
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:12,marginBottom:14}}>
          <div className="card" style={{padding:14}}><div style={{fontSize:11,color:'#6B7280',fontWeight:600,textTransform:'uppercase'}}>SKUs faltando</div><div style={{fontSize:26,fontWeight:800,color:skuColor,marginTop:4}}>{totals.skus}</div></div>
          <div className="card" style={{padding:14}}><div style={{fontSize:11,color:'#6B7280',fontWeight:600,textTransform:'uppercase'}}>{valuePotentialLabel}</div><div style={{fontSize:26,fontWeight:800,color:'#1B2A4A',marginTop:4}}>{totals.un.toLocaleString('pt-BR')}</div></div>
          {canSeeCost && (
            <div className="card" style={{padding:14,background:valuePotentialBg}}>
              <div style={{fontSize:11,color:valuePotentialColor,fontWeight:600,textTransform:'uppercase'}}>Valor potencial</div>
              <div style={{fontSize:22,fontWeight:800,color:valuePotentialColor,marginTop:4}}>{fmt(totals.valor)}</div>
            </div>
          )}
          <div className="card" style={{padding:14,background:transferBg}}>
            <div style={{fontSize:11,color:transferLabelColor,fontWeight:600,textTransform:'uppercase'}}>A transferir</div>
            <div style={{fontSize:22,fontWeight:800,color:transferValueColor,marginTop:4}}>{sel.size} <span style={{fontSize:13,color:'#6B7280',fontWeight:600}}>SKUs</span></div>
            <div style={{fontSize:13,color:transferUnColor,fontWeight:600,marginTop:2}}>{totalUn.toLocaleString('pt-BR')} un.</div>
          </div>
        </div>
        {/* Barra de ações */}
        <div className="card" style={{padding:10,marginBottom:10,display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}}>
          <button className="btn-outline btn-sm" onClick={()=>allSelected?clearSelection(tabKey):selectAll(tabKey,list)} disabled={list.length===0}>{allSelected?'Limpar tudo':'Selecionar tudo'}</button>
          {sel.size>0 && <button className="btn-outline btn-sm" onClick={()=>clearSelection(tabKey)}>Limpar ({sel.size})</button>}
          <div style={{flex:1}}/>
          <button
            className="btn-gold"
            onClick={()=>bulkTransfer(direction)}
            disabled={sel.size===0 || bulkXferInflightRef.current}
            style={{display:'flex',alignItems:'center',gap:6}}>
            <Icon n="arrow-right" size={14}/>
            {bulkXferInflightRef.current
              ? `Transferindo ${bulkXferProgress?.done||0}/${bulkXferProgress?.total||0}...`
              : `Transferir ${sel.size} SKUs (${totalUn} un.) ${directionLabel}`}
          </button>
        </div>
        {/* Tabela */}
        {list.length===0 ? (
          <div className="card" style={{padding:32,textAlign:'center',color:'#9CA3AF'}}>
            {emptyMsg}
          </div>
        ) : (
          <div className="card" style={{padding:0,overflow:'auto'}}>
            <table style={{width:'100%'}}>
              <thead>
                <tr>
                  <th style={{width:36}}><input type="checkbox" checked={allSelected} onChange={()=>allSelected?clearSelection(tabKey):selectAll(tabKey,list)}/></th>
                  <th>Marca</th>
                  <th>Produto</th>
                  <th style={{textAlign:'center'}}>Volume</th>
                  <th style={{textAlign:'right'}}>Disponível</th>
                  <th style={{textAlign:'right',minWidth:160}}>Qty a transferir</th>
                  {canSeeCost && <th style={{textAlign:'right'}}>Valor R$</th>}
                </tr>
              </thead>
              <tbody>
                {list.map(item=>{
                  const isSel = sel.has(item.id);
                  const q = isSel ? Number(sel.get(item.id))||0 : 0;
                  const invalid = isSel && (q<=0 || q>item.qty);
                  return (
                    <tr key={item.id} style={{background:isSel?rowHighlightBg:'transparent'}}>
                      <td><input type="checkbox" checked={isSel} onChange={()=>toggleSelect(tabKey,item.id,item.qty)}/></td>
                      <td style={{fontWeight:600,fontSize:12,color:'#6B7280'}}>{item.brand}</td>
                      <td style={{fontSize:13}}>{item.name}</td>
                      <td style={{textAlign:'center',fontSize:12,color:'#6B7280'}}>{item.volume||'—'}</td>
                      <td style={{textAlign:'right',fontWeight:700,color:qtyColor}}>{item.qty}</td>
                      <td style={{textAlign:'right'}}>
                        {isSel ? (
                          <div style={{display:'inline-flex',alignItems:'center',gap:4,justifyContent:'flex-end'}}>
                            <button type="button" onClick={()=>setItemQty(tabKey,item.id,Math.max(1,q-1),item.qty)} disabled={q<=1} style={{width:24,height:24,border:'1px solid #E4E7EC',background:'#fff',borderRadius:4,cursor:q<=1?'not-allowed':'pointer',fontSize:14,fontWeight:700,color:'#6B7280'}}>−</button>
                            <input
                              type="number"
                              min={1}
                              max={item.qty}
                              value={q}
                              onChange={e=>setItemQty(tabKey,item.id,e.target.value,item.qty)}
                              onClick={e=>e.stopPropagation()}
                              style={{width:64,padding:'4px 6px',border:'1px solid '+(invalid?'#DC2626':'#E4E7EC'),borderRadius:4,fontSize:13,fontWeight:700,textAlign:'center',color:invalid?'#DC2626':'#1B2A4A',background:invalid?'#FEE2E2':'#fff'}}
                            />
                            <button type="button" onClick={()=>setItemQty(tabKey,item.id,Math.min(item.qty,q+1),item.qty)} disabled={q>=item.qty} style={{width:24,height:24,border:'1px solid #E4E7EC',background:'#fff',borderRadius:4,cursor:q>=item.qty?'not-allowed':'pointer',fontSize:14,fontWeight:700,color:'#6B7280'}}>+</button>
                            <button type="button" onClick={()=>setItemQty(tabKey,item.id,item.qty,item.qty)} title="Máximo" style={{padding:'2px 6px',border:`1px solid ${maxBtnBorder}`,background:maxBtnBg,color:maxBtnColor,borderRadius:4,fontSize:10,fontWeight:700,cursor:'pointer'}}>MAX</button>
                          </div>
                        ) : <span style={{color:'#9CA3AF'}}>—</span>}
                      </td>
                      {canSeeCost && <td style={{textAlign:'right',fontWeight:600,color:'#1B2A4A'}}>{fmt(isSel ? (q*item.price) : item.valor)}</td>}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.entradas = window.ZNX.widgets.entradas || {};
  window.ZNX.widgets.entradas.WarehouseTransferPanel = WarehouseTransferPanel;
})();
