// js/components/widgets/marcas/ficha-tabs/EstoqueComprasGeoAlertasSection.jsx
// [Wave 30 v224.11 NUCLEAR EXTRACT 2026-05-24] 4 tabs consolidadas (FichaMarca L428-581)
// Padrão Wave 29 BrandsStockSection (consolidação 4 sections em 1 widget = mais shrink no main)
// Tabs: estoque + compras + geovend + alertas
// Props: tab, estoque, comprasMarca, geoStats, vendedorasDaMarca, brand, m, alertas, brandProducts, suppliers
// Deps lazy: window.fmt, window.nid, window.ZNX.marcasHelpers.fmtDateSafe
(function(){
  'use strict';
  function EstoqueComprasGeoAlertasSection(props){
    var fmt = window.fmt;
    var nid = window.nid;
    var MH = window.ZNX && window.ZNX.marcasHelpers;
    var fmtDateSafe = MH && MH.fmtDateSafe;
    var tab = props.tab;
    var estoque = props.estoque;
    var comprasMarca = props.comprasMarca;
    var geoStats = props.geoStats;
    var vendedorasDaMarca = props.vendedorasDaMarca;
    var brand = props.brand;
    var m = props.m;
    var alertas = props.alertas;
    var brandProducts = props.brandProducts;
    var suppliers = props.suppliers;

    if(tab==='estoque'){
      return (
        <div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:14}}>
            <div className="stat-card"><div className="stat-label">Unidades em estoque</div><div className="stat-value">{estoque.unidades}</div></div>
            <div className="stat-card"><div className="stat-label">R$ congelado</div><div className="stat-value gold">{fmt(estoque.valor)}</div></div>
            <div className="stat-card"><div className="stat-label">Giro estimado</div><div className="stat-value">{estoque.giroEstimado?Math.round(estoque.giroEstimado)+'d':'—'}</div></div>
            <div className="stat-card"><div className="stat-label">SKUs alerta</div><div className="stat-value" style={{color:'#B89840'}}>{estoque.baixo.length+estoque.parado.length}</div></div>
          </div>

          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
            <div className="card" style={{padding:0}}>
              <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#B89840'}}>⚠️ Baixo estoque (≤5 un)</div>
              {estoque.baixo.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Nenhum</div>:(
                <table>
                  <thead><tr><th>SKU</th><th style={{textAlign:'right'}}>Estoque</th></tr></thead>
                  <tbody>
                    {estoque.baixo.map(function(p){
                      return (<tr key={p.id}><td style={{fontWeight:600}}>{p.name}</td><td style={{textAlign:'right'}}>{p.stock||0}</td></tr>);
                    })}
                  </tbody>
                </table>
              )}
            </div>
            <div className="card" style={{padding:0}}>
              <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#B91C1C'}}>🚨 Estoque parado (60+ dias)</div>
              {estoque.parado.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Nenhum</div>:(
                <table>
                  <thead><tr><th>SKU</th><th style={{textAlign:'right'}}>Estoque</th><th style={{textAlign:'right'}}>R$ congelado</th></tr></thead>
                  <tbody>
                    {estoque.parado.slice(0,15).map(function(p){
                      return (
                        <tr key={p.id}>
                          <td style={{fontWeight:600}}>{p.name}</td>
                          <td style={{textAlign:'right'}}>{p.stock||0}</td>
                          <td style={{textAlign:'right',color:'#B91C1C'}}>{fmt((p.stock||0)*(p.avgCost||0))}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      );
    }

    if(tab==='compras'){
      return (
        <div>
          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>🛒 Histórico de compras envolvendo a marca</div>
            {comprasMarca.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Nenhuma compra registrada com SKUs desta marca</div>:(
              <table>
                <thead><tr><th>Data</th><th>Fornecedor</th><th style={{textAlign:'right'}}>Itens da marca</th><th style={{textAlign:'right'}}>Valor compra</th></tr></thead>
                <tbody>
                  {comprasMarca.slice(0,30).map(function(pu){
                    var sup = suppliers && suppliers.find(function(s){return nid(s.id,pu.supplierId);});
                    var itensDaMarca = (pu.items||[]).filter(function(it){return brandProducts.some(function(p){return nid(p.id,it.productId);});});
                    var valorMarca = itensDaMarca.reduce(function(acc,i){return acc+((i.qty||0)*(i.cost||i.price||0));},0);
                    return (
                      <tr key={pu.id}>
                        <td className="dim">{fmtDateSafe(pu.date)}</td>
                        <td style={{fontWeight:600}}>{(sup&&sup.name)||pu.supplier||'—'}</td>
                        <td style={{textAlign:'right'}}>{itensDaMarca.length}</td>
                        <td style={{textAlign:'right'}} className="gold">{fmt(valorMarca)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      );
    }

    if(tab==='geovend'){
      return (
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>📍 Top estados</div>
            {geoStats.ufs.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Sem dados</div>:(
              <table>
                <thead><tr><th>UF</th><th style={{textAlign:'right'}}>Receita</th><th style={{textAlign:'right'}}>%</th></tr></thead>
                <tbody>
                  {geoStats.ufs.slice(0,10).map(function(g){
                    return (<tr key={g.uf}><td style={{fontWeight:700,color:'#1B2A4A'}}>{g.uf}</td><td style={{textAlign:'right'}} className="gold">{fmt(g.receita)}</td><td style={{textAlign:'right'}} className="dim">{m.receita>0?(g.receita/m.receita*100).toFixed(1)+'%':'—'}</td></tr>);
                  })}
                </tbody>
              </table>
            )}
          </div>
          <div className="card" style={{padding:0}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>🏙️ Top cidades</div>
            {geoStats.cidades.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Sem dados</div>:(
              <table>
                <thead><tr><th>Cidade</th><th style={{textAlign:'right'}}>Receita</th></tr></thead>
                <tbody>
                  {geoStats.cidades.slice(0,10).map(function(c){
                    return (<tr key={c.name}><td style={{fontWeight:600}}>{c.name}</td><td style={{textAlign:'right'}} className="gold">{fmt(c.receita)}</td></tr>);
                  })}
                </tbody>
              </table>
            )}
          </div>
          <div className="card" style={{padding:0,gridColumn:'1 / -1'}}>
            <div style={{padding:'14px 16px',borderBottom:'1px solid #E4E7EC',fontWeight:700,color:'#2563EB'}}>🏆 Top vendedoras desta marca</div>
            {vendedorasDaMarca.length===0?<div style={{padding:20,color:'#9CA3AF',textAlign:'center'}}>Sem dados</div>:(
              <table>
                <thead><tr><th>#</th><th>Vendedora</th><th style={{textAlign:'right'}}>Vendas</th><th style={{textAlign:'right'}}>Receita</th><th style={{textAlign:'right'}}>% participação</th></tr></thead>
                <tbody>
                  {vendedorasDaMarca.slice(0,15).map(function(v,i){
                    return (
                      <tr key={v.nome}>
                        <td className="dim">{i+1}</td>
                        <td style={{fontWeight:600}}>{v.nome}</td>
                        <td style={{textAlign:'right'}}>{v.vendas}</td>
                        <td style={{textAlign:'right'}} className="gold">{fmt(v.receita)}</td>
                        <td style={{textAlign:'right'}}>{v.pct.toFixed(1)}%</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      );
    }

    if(tab==='alertas'){
      return (
        <div>
          {alertas.length===0?(
            <div className="card" style={{textAlign:'center',padding:40}}>
              <div style={{fontSize:48,marginBottom:10}}>✅</div>
              <div style={{fontSize:18,fontWeight:700,color:'#15803D'}}>Marca em dia</div>
              <div style={{fontSize:13,color:'#6B7280',marginTop:6}}>Nenhum alerta crítico no momento</div>
            </div>
          ):(
            <div style={{display:'flex',flexDirection:'column',gap:10}}>
              {alertas.map(function(a,i){
                var cor = a.tipo==='critico'?'#B91C1C':a.tipo==='aviso'?'#B89840':'#2563EB';
                var bg = a.tipo==='critico'?'#FEE2E2':a.tipo==='aviso'?'#FEF3C7':'#DBEAFE';
                var ico = a.tipo==='critico'?'🚨':a.tipo==='aviso'?'⚠️':'ℹ️';
                return (
                  <div key={i} className="card" style={{borderLeft:'4px solid '+cor,background:bg,display:'flex',alignItems:'center',gap:14}}>
                    <span style={{fontSize:24}}>{ico}</span>
                    <div style={{flex:1}}>
                      <div style={{fontSize:11,color:cor,fontWeight:700,letterSpacing:1,textTransform:'uppercase',marginBottom:2}}>{a.tipo}</div>
                      <div style={{color:'#1B2A4A',fontWeight:600}}>{a.msg}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      );
    }

    return null;
  }
  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.fichaMarca = window.ZNX.widgets.fichaMarca || {};
  window.ZNX.widgets.fichaMarca.EstoqueComprasGeoAlertasSection = EstoqueComprasGeoAlertasSection;
})();
