// js/components/widgets/produtos-insights/BrandsStockSection.jsx
// [Wave 29 v224.10 NUCLEAR] Sections combinadas: stock + brands + suggestions + detailed
// Extraído de ProdutosInsightsTab.jsx L314-524 (literal · 4 sections em 1 widget)
(function(){
  'use strict';

  function BrandsStockSection(props){
    const STitle = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.STitle;
    const KCard = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.KCard;
    const HBar = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.HBar;
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    const {section, brandData, stockHealth, prodMomentum, rendimentoDetalhado, promoSuggestions, capitalPorMarca} = props;

    if(!STitle || !KCard || !HBar) return null;

    // ─── STOCK ─── [v224.110 filtros + sortable + Última venda + total + banner janela adaptativa]
    if(section === 'stock'){
      const {stockWindowDays, setStockWindowDays, stockMinUnits, setStockMinUnits, deadSortBy, setDeadSortBy} = props;
      const win = stockWindowDays || 90;
      const minU = stockMinUnits || 0;
      const sortBy = deadSortBy || 'value';

      const deadSorted = [].concat(stockHealth.dead || []).sort(function(a,b){
        if(sortBy === 'value') return (b.stock*(b.avgCost||0)) - (a.stock*(a.avgCost||0));
        if(sortBy === 'stock') return (b.stock||0) - (a.stock||0);
        if(sortBy === 'lastSale'){
          const ad = a.daysSinceLastSale==null ? 99999 : a.daysSinceLastSale;
          const bd = b.daysSinceLastSale==null ? 99999 : b.daysSinceLastSale;
          return bd - ad;
        }
        if(sortBy === 'name') return String(a.name||'').localeCompare(String(b.name||''));
        return 0;
      });

      const deadTotalCost = (stockHealth.dead||[]).reduce(function(a,p){return a + p.stock*(p.avgCost||0);}, 0);
      const deadTotalSale = (stockHealth.dead||[]).reduce(function(a,p){return a + p.stock*(p.salePrice||0);}, 0);
      const dangerTotalCost = (stockHealth.danger||[]).reduce(function(a,p){return a + p.stock*(p.avgCost||0);}, 0);

      const effectiveWin = stockHealth.effectiveWindow || win;
      const winLabel = effectiveWin < win
        ? 'Sem giro em ' + effectiveWin + ' dias (histórico disponível · ' + win + ' solicitados)'
        : 'Sem giro em ' + win + ' dias';

      return (
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,marginBottom:16}}>
          <div className="card">
            <STitle t="🧟 Dead Stock" s={(stockHealth.dead||[]).length+' produtos · '+fmt(deadTotalCost)+' parado (custo) · '+fmt(deadTotalSale)+' (venda)'}/>
            <div style={{display:'flex',gap:8,flexWrap:'wrap',marginBottom:10,fontSize:11,alignItems:'center'}}>
              <label style={{display:'flex',alignItems:'center',gap:4,color:'#6B7280'}}>
                Sem giro em:
                <select value={win} onChange={function(e){setStockWindowDays && setStockWindowDays(Number(e.target.value));}}
                  style={{padding:'3px 6px',fontSize:11,border:'1px solid #D1D5DB',borderRadius:4}}>
                  <option value={15}>15 dias</option>
                  <option value={30}>30 dias</option>
                  <option value={60}>60 dias</option>
                  <option value={90}>90 dias</option>
                  <option value={180}>180 dias</option>
                </select>
              </label>
              <label style={{display:'flex',alignItems:'center',gap:4,color:'#6B7280'}}>
                Estoque ≥:
                <input type="number" min={0} value={minU}
                  onChange={function(e){setStockMinUnits && setStockMinUnits(Math.max(0, Number(e.target.value)||0));}}
                  style={{width:60,padding:'3px 6px',fontSize:11,border:'1px solid #D1D5DB',borderRadius:4}}/>
                <span style={{color:'#9CA3AF'}}>un.</span>
              </label>
              <label style={{display:'flex',alignItems:'center',gap:4,color:'#6B7280'}}>
                Ordenar:
                <select value={sortBy} onChange={function(e){setDeadSortBy && setDeadSortBy(e.target.value);}}
                  style={{padding:'3px 6px',fontSize:11,border:'1px solid #D1D5DB',borderRadius:4}}>
                  <option value="value">Valor parado</option>
                  <option value="stock">Estoque</option>
                  <option value="lastSale">Última venda (+ antiga)</option>
                  <option value="name">Nome A-Z</option>
                </select>
              </label>
              <span style={{marginLeft:'auto',color:'#9CA3AF',fontSize:10}}>{winLabel}</span>
            </div>
            {effectiveWin < win && (
              <div style={{background:'#FEF3C7',border:'1px solid #F59E0B',borderRadius:4,padding:'4px 8px',marginBottom:8,fontSize:10,color:'#92400E'}}>
                ⚠️ Histórico de vendas tem só {stockHealth.actualDaysAvailable} dias (desde {stockHealth.oldestSaleDate||'—'}). Janela efetiva: {effectiveWin}d.
              </div>
            )}
            {(stockHealth.dead||[]).length === 0 ?
              <div style={{color:'#16A34A',fontSize:13,textAlign:'center',padding:20}}>✓ Nenhum produto parado!</div>
            :
              <div style={{maxHeight:480,overflowY:'auto'}}>
                <table style={{fontSize:12}}>
                  <thead><tr>
                    <th>Produto</th><th>Marca</th><th>Estoque</th>
                    <th>Custo Médio</th><th>Preço Venda</th><th>Última venda</th><th>Valor parado</th>
                  </tr></thead>
                  <tbody>{deadSorted.map(function(p){
                    const lastTxt = p.lastSaleDate ? p.lastSaleDate + ' (' + p.daysSinceLastSale + 'd)' : 'Nunca';
                    const lastColor = p.lastSaleDate ? (p.daysSinceLastSale > 60 ? '#DC2626' : '#92400E') : '#6B7280';
                    return (
                      <tr key={p.id}>
                        <td style={{fontWeight:500}}>{p.name}</td>
                        <td className="dim">{p.brand||'—'}</td>
                        <td style={{color:'#DC2626',fontWeight:700}}>{p.stock} un.</td>
                        <td className="dim">{fmt(p.avgCost||0)}</td>
                        <td className="dim">{fmt(p.salePrice||0)}</td>
                        <td style={{fontSize:11,color:lastColor}}>{lastTxt}</td>
                        <td className="dim">{fmt(p.stock*(p.avgCost||0))}</td>
                      </tr>
                    );
                  })}</tbody>
                </table>
              </div>
            }
          </div>
          <div className="card">
            <STitle t="⚠️ Risco de Ruptura" s={(stockHealth.danger||[]).length+' produtos com <20 dias · '+fmt(dangerTotalCost)+' em risco'}/>
            {(stockHealth.danger||[]).length === 0 ?
              <div style={{color:'#16A34A',fontSize:13,textAlign:'center',padding:20}}>✓ Nenhum produto em risco.</div>
            :
              <div style={{maxHeight:480,overflowY:'auto'}}>
                <table style={{fontSize:12}}>
                  <thead><tr>
                    <th>Produto</th><th>Estoque</th><th>Custo Médio</th><th>Preço Venda</th>
                    <th>Última venda</th><th>Giro/dia</th><th>Restantes</th>
                  </tr></thead>
                  <tbody>{(stockHealth.danger||[]).map(function(p){
                    const lastTxt = p.lastSaleDate ? p.lastSaleDate + ' (' + p.daysSinceLastSale + 'd)' : 'Nunca';
                    return (
                      <tr key={p.id}>
                        <td style={{fontWeight:500}}>{p.name}</td>
                        <td>{p.stock} un.</td>
                        <td className="dim">{fmt(p.avgCost||0)}</td>
                        <td className="dim">{fmt(p.salePrice||0)}</td>
                        <td style={{fontSize:11,color:'#6B7280'}}>{lastTxt}</td>
                        <td className="dim">{p.dailyRate.toFixed(2)}/dia</td>
                        <td style={{fontWeight:700,color:p.daysLeft<7?'#DC2626':p.daysLeft<15?'#EA580C':'#2563EB'}}>{p.daysLeft}d</td>
                      </tr>
                    );
                  })}</tbody>
                </table>
              </div>
            }
          </div>
        </div>
      );
    }

    // ─── BRANDS ─── (L357-378)
    if(section === 'brands'){
      return (
        <>
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:14,marginBottom:18}}>
            <KCard label="Marcas Ativas" value={brandData.length} color='#9c27b0'/>
            <KCard label="Capital Total" value={fmt(capitalPorMarca.reduce(function(s,b){return s+b.costVal;},0))} color='#A89070' sub="estoque a custo"/>
            <KCard label="Top marca" value={(brandData[0]&&brandData[0].brand)||'—'} sub={brandData[0]?fmt(brandData[0].revenue):''} color='#2563EB'/>
            <KCard label="Top capital" value={(capitalPorMarca[0]&&capitalPorMarca[0].brand)||'—'} sub={capitalPorMarca[0]?fmt(capitalPorMarca[0].costVal):''} color='#EA580C'/>
          </div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
            <div className="card">
              <STitle t="⭐ Top Marcas — Receita" s="Faturamento histórico"/>
              {brandData.slice(0,15).map(function(b, i){
                return <HBar key={b.brand} label={(i+1)+'. '+b.brand} value={b.revenue} max={(brandData[0]&&brandData[0].revenue)||1} fmtFn={fmt} color={i===0?'#9c27b0':i<3?'#2563EB':'#3a3020'} sub={b.qty+'un · '+b.margin.toFixed(0)+'%mg · '+b.clients+'cli'} width={170} minWidth={90}/>;
              })}
            </div>
            <div className="card">
              <STitle t="💰 Capital em Estoque por Marca" s="Onde está o dinheiro parado"/>
              {capitalPorMarca.slice(0,15).map(function(b, i){
                return <HBar key={b.brand} label={(i+1)+'. '+b.brand} value={b.costVal} max={(capitalPorMarca[0]&&capitalPorMarca[0].costVal)||1} fmtFn={fmt} color={i===0?'#A89070':i<3?'#EA580C':'#9CA3AF'} sub={b.skus+'sku · '+b.units+'un'} width={170} minWidth={90}/>;
              })}
            </div>
          </div>
        </>
      );
    }

    // ─── SUGGESTIONS ─── (L381-437)
    if(section === 'suggestions'){
      const momentumUp = prodMomentum.filter(function(p){return p.momentum>0;});
      const momentumDown = prodMomentum.filter(function(p){return p.momentum<0;});
      return (
        <>
          <div style={{display:'flex',gap:8,marginBottom:14,flexWrap:'wrap',fontSize:11}}>
            {[{icon:'🔴',label:'Liquidação',color:'#DC2626'},{icon:'🟡',label:'Desconto',color:'#EA580C'},{icon:'🔵',label:'Bundle',color:'#2563EB'},{icon:'🟢',label:'Destaque',color:'#16A34A'}].map(function(t){
              return <span key={t.label} style={{background:'#F9FAFB',border:'1px solid '+t.color+'33',borderRadius:10,padding:'4px 10px',color:t.color,fontWeight:600}}>{t.icon} {t.label}</span>;
            })}
            <span style={{marginLeft:'auto',color:'#6B7280'}}>{promoSuggestions.length} sugestões</span>
          </div>
          <div className="card" style={{padding:0}}>
            <table>
              <thead><tr><th></th><th>Produto</th><th>Marca</th><th>Estoque</th><th>Margem</th><th>Motivo</th><th>Desconto</th></tr></thead>
              <tbody>
                {promoSuggestions.slice(0,80).map(function(s){
                  return (
                    <tr key={s.id}>
                      <td style={{fontSize:18}}>{s.icon}</td>
                      <td style={{fontWeight:500,fontSize:12}}>{s.name}</td>
                      <td className="dim">{s.brand}</td>
                      <td style={{fontWeight:700}}>{s.stock} un.</td>
                      <td style={{color:s.margin>40?'#16A34A':s.margin>20?'#2563EB':'#DC2626',fontWeight:600}}>{s.margin.toFixed(0)}%</td>
                      <td className="dim" style={{fontSize:11}}>{s.reason}</td>
                      <td style={{fontWeight:700,color:'#92700A'}}>{s.discount}</td>
                    </tr>
                  );
                })}
                {promoSuggestions.length === 0 && <tr><td colSpan={7} style={{textAlign:'center',color:'#16A34A',padding:20}}>✓ Nada urgente — tudo girando bem.</td></tr>}
              </tbody>
            </table>
          </div>
          {prodMomentum.length > 0 && (
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,marginTop:16}}>
              <div className="card">
                <STitle t="🚀 Ganhando tração" s="30d vs 30d anteriores"/>
                {momentumUp.slice(0,10).map(function(p){
                  return (
                    <div key={p.id} style={{display:'flex',alignItems:'center',gap:10,marginBottom:6,padding:'6px 10px',background:'#F0FDF4',borderRadius:6,border:'1px solid #16A34A22'}}>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:12,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.name}</div>
                        <div style={{fontSize:10,color:'#6B7280'}}>{p.brand} · estoque {p.stock}</div>
                      </div>
                      <div style={{textAlign:'right'}}><div style={{fontSize:12,fontWeight:800,color:'#16A34A'}}>+{p.momentum.toFixed(0)}%</div><div style={{fontSize:10,color:'#6B7280'}}>{p.prev}→{p.recent}</div></div>
                    </div>
                  );
                })}
                {momentumUp.length === 0 && <div style={{textAlign:'center',padding:14,color:'#6B7280',fontSize:12}}>Sem dados</div>}
              </div>
              <div className="card">
                <STitle t="📉 Perdendo força"/>
                {momentumDown.slice(0,10).map(function(p){
                  return (
                    <div key={p.id} style={{display:'flex',alignItems:'center',gap:10,marginBottom:6,padding:'6px 10px',background:'#FEF2F2',borderRadius:6,border:'1px solid #DC262622'}}>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:12,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{p.name}</div>
                        <div style={{fontSize:10,color:'#6B7280'}}>{p.brand} · estoque {p.stock}</div>
                      </div>
                      <div style={{textAlign:'right'}}><div style={{fontSize:12,fontWeight:800,color:'#DC2626'}}>{p.momentum.toFixed(0)}%</div><div style={{fontSize:10,color:'#6B7280'}}>{p.prev}→{p.recent}</div></div>
                    </div>
                  );
                })}
                {momentumDown.length === 0 && <div style={{textAlign:'center',padding:14,color:'#16A34A',fontSize:12}}>✓ Nada caindo</div>}
              </div>
            </div>
          )}
        </>
      );
    }

    // ─── DETAILED ─── (L440-524)
    if(section === 'detailed'){
      const totalRev = rendimentoDetalhado.reduce(function(s,p){return s+p.revenue;}, 0);
      const totalProfit = rendimentoDetalhado.reduce(function(s,p){return s+p.profit;}, 0);
      return (
        <>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:12}}>
            <div>
              <STitle t="📋 Rendimento Detalhado por Produto" s={'Filtros aplicados — '+rendimentoDetalhado.length+' produtos com venda'}/>
            </div>
            <div style={{fontSize:11,color:'#9CA3AF'}}>
              Receita total: <strong style={{color:'#16A34A'}}>{fmt(totalRev)}</strong> ·
              Lucro: <strong style={{color:'#92700A'}}>{fmt(totalProfit)}</strong>
            </div>
          </div>
          <div className="card" style={{padding:0}}>
            <table style={{fontSize:12}}>
              <thead><tr>
                <th>#</th><th>Produto</th><th>Marca</th>
                <th style={{textAlign:'right'}}>Qtd</th>
                <th style={{textAlign:'right'}}>Receita</th>
                <th style={{textAlign:'right'}}>Share</th>
                <th style={{textAlign:'right'}}>Lucro</th>
                <th style={{textAlign:'right'}}>Margem</th>
              </tr></thead>
              <tbody>
                {rendimentoDetalhado.slice(0,150).map(function(p, i){
                  const marginColor = p.margin>=25?'#16A34A':p.margin>=15?'#2563EB':p.margin>=8?'#EA580C':'#DC2626';
                  return (
                    <tr key={p.id}>
                      <td style={{fontWeight:700,color:'#9CA3AF'}}>#{i+1}</td>
                      <td style={{fontWeight:500}}>{p.name}{p.is_decant?' 🧪':''}</td>
                      <td className="dim">{p.brand||'—'}</td>
                      <td style={{textAlign:'right',fontWeight:700}}>{p.qty} un.</td>
                      <td style={{textAlign:'right',color:'#2563EB',fontWeight:700}}>{fmt(p.revenue)}</td>
                      <td style={{textAlign:'right',color:'#9CA3AF'}}>{p.share.toFixed(1)}%</td>
                      <td style={{textAlign:'right',color:p.profit>=0?'#16A34A':'#DC2626',fontWeight:600}}>{fmt(p.profit)}</td>
                      <td style={{textAlign:'right'}}>
                        <span style={{display:'inline-block',padding:'2px 8px',borderRadius:10,fontSize:11,fontWeight:700,background:marginColor+'20',color:marginColor,border:'1px solid '+marginColor+'44'}}>
                          {p.margin.toFixed(1)}%
                        </span>
                      </td>
                    </tr>
                  );
                })}
                {rendimentoDetalhado.length === 0 && <tr><td colSpan={8} style={{textAlign:'center',color:'#6B7280',padding:20}}>Nenhum produto vendido nos filtros aplicados.</td></tr>}
                {rendimentoDetalhado.length > 150 && <tr><td colSpan={8} style={{textAlign:'center',color:'#9CA3AF',padding:10,fontSize:11}}>+{rendimentoDetalhado.length-150} produtos abaixo do top 150 — refine os filtros pra ver mais.</td></tr>}
              </tbody>
            </table>
          </div>

          {/* Rendimento por Marca (mini) */}
          <div className="card" style={{padding:0,marginTop:14}}>
            <div style={{padding:'14px 16px 0'}}>
              <STitle t="⭐ Rendimento por Marca" s="Agregado dos filtros aplicados"/>
            </div>
            <table style={{fontSize:12}}>
              <thead><tr>
                <th>#</th><th>Marca</th>
                <th style={{textAlign:'right'}}>Qtd</th>
                <th style={{textAlign:'right'}}>Clientes</th>
                <th style={{textAlign:'right'}}>Receita</th>
                <th style={{textAlign:'right'}}>Lucro</th>
                <th style={{textAlign:'right'}}>Margem</th>
              </tr></thead>
              <tbody>
                {brandData.slice(0,50).map(function(b, i){
                  const mc = b.margin>=25?'#16A34A':b.margin>=15?'#2563EB':b.margin>=8?'#EA580C':'#DC2626';
                  return (
                    <tr key={b.brand}>
                      <td style={{fontWeight:700,color:'#9CA3AF'}}>#{i+1}</td>
                      <td style={{fontWeight:600,color:'#1B2A4A'}}>{b.brand}</td>
                      <td style={{textAlign:'right',fontWeight:700}}>{b.qty}</td>
                      <td style={{textAlign:'right',color:'#9CA3AF'}}>{b.clients}</td>
                      <td style={{textAlign:'right',color:'#2563EB',fontWeight:700}}>{fmt(b.revenue)}</td>
                      <td style={{textAlign:'right',color:b.profit>=0?'#16A34A':'#DC2626'}}>{fmt(b.profit)}</td>
                      <td style={{textAlign:'right'}}>
                        <span style={{display:'inline-block',padding:'2px 8px',borderRadius:10,fontSize:11,fontWeight:700,background:mc+'20',color:mc}}>{b.margin.toFixed(1)}%</span>
                      </td>
                    </tr>
                  );
                })}
                {brandData.length === 0 && <tr><td colSpan={7} style={{textAlign:'center',color:'#6B7280',padding:20}}>Nenhuma marca vendida nos filtros.</td></tr>}
              </tbody>
            </table>
          </div>
        </>
      );
    }

    return null;
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.produtosInsights = window.ZNX.widgets.produtosInsights || {};
  window.ZNX.widgets.produtosInsights.BrandsStockSection = BrandsStockSection;
  window.ProdutosInsightsBrandsStock_v224_10_wave29 = true;
})();
