// js/components/widgets/entradas/AcabandoPanel.jsx
// [Wave 4 KIMI Strategy C 2026-05-15] Extraído de Entradas.jsx L951-1071 — refactor zero-lógica.
// Padrão: IIFE + window.ZNX.widgets.entradas.X namespace + props injection.
//
// Tab v215 cobertura ≤14d Alfonso/Senador. Toggle warehouse + stats badges (crítico/atenção/pedidos)
// + export CSV + tabela produtos acabando com botão "📦 Pedi" (reorder request).
// Gate canSeeWarehouseComparisons aplicado no caller (gate-fora pattern consagrado).
//
// Props (validados FASE 1.5 = 10 props):
//   acabandoWh: string (warehouse ID) — toggle Alfonso/Senador atual
//   setAcabandoWh: setter — alterna warehouse
//   acabandoData: array — produtos filtrados ≤14d cobertura
//   acabandoStats: object {critico, atencao, pedidos} — badges
//   loadingReorders: bool — loading state
//   pediInflightRef: useRef Set — IDs em flight (regra_loading_state_obrigatorio)
//   handlePedi: async fn(item) — handler "Pedi" do pai (faz reorder request via RPC)
//   warehouseName: fn(id) → string — resolve warehouse name
//   W_ALFONSO: string (UUID constant) — warehouse Alfonso ID
//   W_SENADOR: string (UUID constant) — warehouse Senador ID
//
// Deps runtime globals: fmtDate, today, toast, Sentry (window.*).
(function() {
  'use strict';

  function AcabandoPanel({acabandoWh, setAcabandoWh, acabandoData, acabandoStats, loadingReorders, pediInflightRef, handlePedi, warehouseName, W_ALFONSO, W_SENADOR}){
    return (
      <div>
        {/* Toggle warehouse + stats + export */}
        <div className="card" style={{padding:14,marginBottom:14,display:'flex',gap:14,flexWrap:'wrap',alignItems:'center'}}>
          <div style={{display:'inline-flex',background:'#F3F4F6',borderRadius:8,padding:3}}>
            <button onClick={()=>setAcabandoWh(W_ALFONSO)} style={{padding:'8px 18px',border:'none',borderRadius:6,fontSize:13,fontWeight:700,cursor:'pointer',background:acabandoWh===W_ALFONSO?'#92400E':'transparent',color:acabandoWh===W_ALFONSO?'#fff':'#6B7280'}}>🏛️ Alfonso</button>
            <button onClick={()=>setAcabandoWh(W_SENADOR)} style={{padding:'8px 18px',border:'none',borderRadius:6,fontSize:13,fontWeight:700,cursor:'pointer',background:acabandoWh===W_SENADOR?'#1E40AF':'transparent',color:acabandoWh===W_SENADOR?'#fff':'#6B7280'}}>🏢 Senador</button>
          </div>
          <div style={{width:1,height:30,background:'#E5E7EB'}}/>
          <div style={{display:'flex',gap:14,flex:1}}>
            <div style={{background:'#FEE2E2',padding:'8px 14px',borderRadius:8,minWidth:110}}>
              <div style={{fontSize:10,color:'#991B1B',textTransform:'uppercase',fontWeight:700,letterSpacing:.5}}>🔴 Crítico (≤3d)</div>
              <div style={{fontSize:22,fontWeight:800,color:'#991B1B'}}>{acabandoStats.critico}</div>
            </div>
            <div style={{background:'#FEF3C7',padding:'8px 14px',borderRadius:8,minWidth:110}}>
              <div style={{fontSize:10,color:'#92400E',textTransform:'uppercase',fontWeight:700,letterSpacing:.5}}>🟡 Atenção (4-14d)</div>
              <div style={{fontSize:22,fontWeight:800,color:'#92400E'}}>{acabandoStats.atencao}</div>
            </div>
            <div style={{background:'#DCFCE7',padding:'8px 14px',borderRadius:8,minWidth:110}}>
              <div style={{fontSize:10,color:'#166534',textTransform:'uppercase',fontWeight:700,letterSpacing:.5}}>✓ Já pedidos</div>
              <div style={{fontSize:22,fontWeight:800,color:'#166534'}}>{acabandoStats.pedidos}</div>
            </div>
          </div>
          <button
            disabled={acabandoData.length===0}
            onClick={()=>{
              try{
                const wn = warehouseName(acabandoWh);
                const header=['Status','Produto','Marca','Categoria','Estoque '+wn,'Velocidade/dia','Vendas 30d','Dias cobertura','Qtd sugerida','Já pedido por','Já pedido em'];
                const lines=[header.join(';')];
                acabandoData.forEach(p=>{
                  lines.push([
                    p.status==='critico'?'CRITICO':'ATENCAO',
                    p.name,p.brand,p.category,p.stock,p.velocity,p.velocity30d,p.daysFmt,p.qtySuggested,
                    p.pedido?.by||'',p.pedido?fmtDate(p.pedido.at):''
                  ].map(v=>String(v).replace(/;/g,',')).join(';'));
                });
                const blob=new Blob(['﻿'+lines.join('\n')],{type:'text/csv;charset=utf-8'});
                const url=URL.createObjectURL(blob);
                const a=document.createElement('a');
                a.href=url;
                a.download='zaynex_acabando_'+wn.toLowerCase()+'_'+today()+'.csv';
                a.click();
                setTimeout(()=>URL.revokeObjectURL(url),500);
                if(typeof toast==='function')toast('✅ CSV exportado','success');
              }catch(e){
                console.error('[ZNX v215] csv',e);
                if(typeof Sentry!=='undefined')try{Sentry.captureException(e,{tags:{feature:'acabando_csv'}});}catch(_){}
                if(typeof toast==='function')toast('❌ Falha export CSV','error');
              }
            }}
            style={{padding:'8px 16px',background:acabandoData.length===0?'#9CA3AF':'#10B981',color:'#fff',border:'none',borderRadius:6,fontSize:12,fontWeight:700,cursor:acabandoData.length===0?'not-allowed':'pointer'}}>📥 Export CSV</button>
        </div>

        {/* Info box */}
        <div style={{background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:8,padding:'10px 14px',marginBottom:14,fontSize:12,color:'#1E40AF'}}>
          💡 <strong>Como funciona:</strong> Lista produtos do depósito <strong>{warehouseName(acabandoWh)}</strong> com cobertura de <strong>até 14 dias</strong>. Velocidade calculada com vendas dos últimos 30 dias. Clique em <strong>📦 Pedi</strong> pra marcar reposição e evitar pedidos duplicados (outros estoquistas veem em tempo real). Exclui produtos descontinuados, sem venda em 30d e já pedidos nas últimas 72h.
        </div>

        {/* Tabela */}
        <div className="card" style={{padding:0}}>
          <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <span>📦 {acabandoData.length} produto(s) acabando em {warehouseName(acabandoWh)}</span>
            {loadingReorders && <span style={{fontSize:11,color:'#9CA3AF',fontWeight:400}}>Carregando pedidos...</span>}
          </div>
          {acabandoData.length===0 ? (
            <div style={{padding:40,textAlign:'center',color:'#9CA3AF'}}>
              <div style={{fontSize:32,marginBottom:8}}>✓</div>
              <div style={{fontWeight:700,color:'#16A34A',fontSize:15,marginBottom:4}}>Nenhum produto crítico em {warehouseName(acabandoWh)}</div>
              <div style={{fontSize:12}}>Estoque saudável — todos com mais de 14 dias de cobertura</div>
            </div>
          ) : (
            <div style={{overflowX:'auto',maxHeight:600}}>
              <table>
                <thead><tr style={{position:'sticky',top:0,background:'#fff',zIndex:1}}>
                  <th>Status</th>
                  <th>Produto</th>
                  <th>Marca</th>
                  <th style={{textAlign:'right'}}>Estoque</th>
                  <th style={{textAlign:'right'}}>Velocidade<br/><span style={{fontSize:10,fontWeight:400,color:'#9CA3AF'}}>un/dia (30d)</span></th>
                  <th style={{textAlign:'right'}}>Cobertura</th>
                  <th style={{textAlign:'right'}}>Sugerido</th>
                  <th>Ação</th>
                </tr></thead>
                <tbody>
                  {acabandoData.map(p=>{
                    const isInFlight = pediInflightRef.current.has(p.id);
                    const statusBg = p.status==='critico'?'#FEE2E2':'#FEF3C7';
                    const statusFg = p.status==='critico'?'#991B1B':'#92400E';
                    const statusLbl = p.status==='critico'?'🔴 Crítico':'🟡 Atenção';
                    return (
                      <tr key={p.id} style={{background:p.pedido?'#F0FDF4':'#fff'}}>
                        <td><span style={{padding:'3px 8px',borderRadius:4,fontSize:10,fontWeight:700,background:statusBg,color:statusFg}}>{statusLbl}</span></td>
                        <td style={{fontSize:12,fontWeight:600,maxWidth:280}}>{p.name}</td>
                        <td><span style={{fontSize:11,color:'#2563EB',background:'#FEF3C7',padding:'2px 6px',borderRadius:4}}>{p.brand}</span></td>
                        <td style={{textAlign:'right',fontWeight:700,fontSize:14,color:p.stock<=3?'#DC2626':'#1F2937'}}>{p.stock} un.</td>
                        <td style={{textAlign:'right',fontSize:12,color:'#6B7280'}}>{p.velocity}<div style={{fontSize:10,color:'#9CA3AF'}}>{p.velocity30d}/mês</div></td>
                        <td style={{textAlign:'right',fontWeight:700,color:statusFg,fontSize:14}}>{p.daysFmt}</td>
                        <td style={{textAlign:'right',fontWeight:600,color:'#B89840'}}>{p.qtySuggested} un.</td>
                        <td>
                          {p.pedido ? (
                            <span style={{padding:'4px 10px',background:'#DCFCE7',color:'#166534',borderRadius:5,fontSize:11,fontWeight:700,display:'inline-block'}}>✓ Pedido {fmtDate(p.pedido.at)} · {p.pedido.by}</span>
                          ) : (
                            <button
                              onClick={()=>handlePedi(p)}
                              disabled={isInFlight}
                              style={{padding:'5px 14px',background:isInFlight?'#9CA3AF':'#B89840',color:'#fff',border:'none',borderRadius:5,fontSize:12,fontWeight:700,cursor:isInFlight?'wait':'pointer',opacity:isInFlight?0.6:1}}>
                              {isInFlight?'⏳ Registrando...':'📦 Pedi'}
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    );
  }

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