// js/components/widgets/insights/GeralPanel.jsx
// [Wave 5 KIMI 2026-05-15] Extraído de Insights.jsx tab='geral' — refactor zero-lógica.
// Padrão: IIFE + window.ZNX.widgets.insights.X namespace + props injection.
//
// Props (validadas FASE 1.5 = 14 props incluindo BarChart12 helper interno):
//   curM, lastM: object — current month + last month stats (revenue, profit, newClients)
//   growth: number — revenue growth %
//   profGrowth: number — profit growth %
//   qFunnel: object {t, pending, negoc, approved, converted, refused, rate, avgVal}
//   monthlyData: array — 12 meses (revenue, profit)
//   paretoData: object {top10, top20, top10Rev, top20Rev, top10Pct, top20Pct, total, totalRev}
//   stockHealth: object {costVal, saleVal, potentialProfit, dead[], deadCostVal, danger[]}
//   sales: array — vendas (usado em canal de venda)
//   topCategorias: array — [{cat, revenue, qty}]
//   rfmMatrix: object {champion, leais, novos, emRisco, perdidos, hibernando}
//   crossSell: array — [{a, b, brandA, brandB, count}]
//   BarChart12: function — helper interno Insights.jsx L289 (passado como prop literal byte-by-byte)
//
// Deps runtime globals: fmt, saleFinalTotal (window.fmt, window.saleFinalTotal).
// Widget deps (Wave 1 PR1): KCard, STitle, HBar (via window.ZNX.widgets).
(function() {
  'use strict';
  // [Wave 5 KIMI + v224.55 2026-05-28] vars+check MOVED to component body (preventivo)
  // regra_validacao_helpers_runtime_quando_ordem_scripts_uncertain

  function GeralPanel({curM, lastM, growth, profGrowth, qFunnel, monthlyData, paretoData, stockHealth, sales, topCategorias, rfmMatrix, crossSell, BarChart12}){
    // [v224.55 FIX-PREV-20 2026-05-28] vars+check em render time
    const KCard = window.ZNX?.widgets?.KCard;
    const STitle = window.ZNX?.widgets?.STitle;
    const HBar = window.ZNX?.widgets?.HBar;
    if (!KCard || !STitle || !HBar) {
      console.error('[GeralPanel] widgets faltando: KCard/STitle/HBar');
      window.Sentry?.captureMessage?.('[GeralPanel] base widgets missing', 'error');
    }
    return (
      <div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:14,marginBottom:20}}>
          <KCard label="Faturamento — Mês" value={fmt(curM.revenue)} trendVal={growth} color='#2563EB'/>
          {/* [Bug #642 fase 2 20260518] Lucro Líquido usa curM.lucroLiquido (era curM.profit BRUTO).
              Consistente cross-page com Bug #619 Relatorio (mesma factory: profit - gastosMes). */}
          <KCard label="Lucro Líquido" value={fmt(curM.lucroLiquido!=null?curM.lucroLiquido:curM.profit)} trendVal={profGrowth} color={(curM.lucroLiquido!=null?curM.lucroLiquido:curM.profit)>=0?'#16A34A':'#DC2626'}/>
          {/* [Bug #642 fase 2] Margem Líquida (era Margem Média BRUTA) — usa lucroLiquido se disponível */}
          <KCard label="Margem Líquida" value={curM.revenue>0?((curM.lucroLiquido!=null?curM.lucroLiquido:curM.profit)/curM.revenue*100).toFixed(1)+'%':'—'} sub="do mês atual" color='#EA580C'/>
          <KCard label="Novos Clientes" value={curM.newClients} sub="este mês" color='#2196f3' trendVal={lastM.newClients>0?(curM.newClients-lastM.newClients)/lastM.newClients*100:undefined}/>
          <KCard label="Conversão de ORC" value={qFunnel.rate.toFixed(1)+'%'} sub={`${qFunnel.converted} convertidos`} color='#9c27b0'/>
        </div>

        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,marginBottom:16}}>
          <div className="card">
            <STitle t="📈 Faturamento — Últimos 12 Meses"/>
            <BarChart12 data={monthlyData} valueKey="revenue" colorFn={(_,i,last)=>last?'#2563EB':`#2563EB${Math.max(30,i*8).toString(16).padStart(2,'0')}`} labelColor="#2563EB"/>
            <div style={{display:'flex',justifyContent:'space-between',fontSize:11,borderTop:'1px solid #F3F4F6',paddingTop:8}}>
              <span style={{color:'#9CA3AF'}}>Média: {fmt(monthlyData.reduce((a,m)=>a+m.revenue,0)/12)}/mês</span>
              <span style={{color:growth>=0?'#16A34A':'#DC2626',fontWeight:700}}>{growth>=0?'↑':'↓'} {Math.abs(growth).toFixed(1)}% vs mês ant.</span>
            </div>
          </div>
          <div className="card">
            {/* [Bug #642 fase 2 20260518] BarChart12 12-meses agora usa lucroLiquido (era profit BRUTO).
                Consistente com KCard "Lucro Líquido" acima + cross-page Bug #619 Relatorio.
                Fallback `lucroLiquido!=null?lucroLiquido:profit` via valueKey dinâmico. */}
            <STitle t="💰 Lucro Líquido — Últimos 12 Meses"/>
            <BarChart12 data={monthlyData} valueKey={monthlyData[11]&&monthlyData[11].lucroLiquido!=null?'lucroLiquido':'profit'} colorFn={(m,_,last)=>{const v=(m.lucroLiquido!=null?m.lucroLiquido:m.profit);return last?(v>=0?'#16A34A':'#DC2626'):(v>=0?'#16A34A55':'#DC262655')}} labelColor="#16A34A"/>
            <div style={{display:'flex',justifyContent:'space-between',fontSize:11,borderTop:'1px solid #F3F4F6',paddingTop:8}}>
              <span style={{color:'#9CA3AF'}}>Média: {fmt(monthlyData.reduce((a,m)=>a+(m.lucroLiquido!=null?m.lucroLiquido:m.profit),0)/12)}/mês</span>
              <span style={{color:profGrowth>=0?'#16A34A':'#DC2626',fontWeight:700}}>{profGrowth>=0?'↑':'↓'} {Math.abs(profGrowth).toFixed(1)}% vs mês ant.</span>
            </div>
          </div>
        </div>

        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:16}}>
          {/* Quote Funnel */}
          <div className="card">
            <STitle t="🔄 Funil de Orçamentos" s="Da criação à conversão"/>
            {[{label:'Criados',val:qFunnel.t,color:'#2196f3'},{label:'Pendentes',val:qFunnel.pending,color:'#9CA3AF'},{label:'Em Negociação',val:qFunnel.negoc,color:'#EA580C'},{label:'Aprovados',val:qFunnel.approved,color:'#2563EB'},{label:'Convertidos ✓',val:qFunnel.converted,color:'#16A34A'},{label:'Recusados ✕',val:qFunnel.refused,color:'#DC2626'}].map(({label,val,color})=>(
              <div key={label} style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:9}}>
                <span style={{fontSize:12,color:'#9CA3AF'}}>{label}</span>
                <span style={{fontSize:15,fontWeight:700,color}}>{val}</span>
              </div>
            ))}
            <div style={{borderTop:'1px solid #F3F4F6',paddingTop:10,marginTop:2,display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
              <div style={{background:'#F8FAFB',borderRadius:6,padding:'8px 10px',textAlign:'center'}}>
                <div style={{fontSize:10,color:'#6B7280'}}>Taxa conversão</div>
                <div style={{fontSize:16,fontWeight:800,color:'#16A34A'}}>{qFunnel.rate.toFixed(1)}%</div>
              </div>
              <div style={{background:'#F8FAFB',borderRadius:6,padding:'8px 10px',textAlign:'center'}}>
                <div style={{fontSize:10,color:'#6B7280'}}>Ticket médio ORC</div>
                <div style={{fontSize:13,fontWeight:700,color:'#2563EB'}}>{fmt(qFunnel.avgVal)}</div>
              </div>
            </div>
          </div>

          {/* Pareto */}
          <div className="card">
            <STitle t="📐 Concentração — Lei de Pareto" s="Quem gera a receita?"/>
            <div style={{textAlign:'center',padding:'6px 0 16px'}}>
              <div style={{fontSize:46,fontWeight:900,color:'#2563EB',lineHeight:1}}>{paretoData.top20Pct.toFixed(0)}%</div>
              <div style={{fontSize:12,color:'#9CA3AF',marginTop:6}}>da receita gerada pelos top {paretoData.top20} clientes</div>
              <div style={{fontSize:11,color:'#6B7280',marginTop:2}}>({Math.round(paretoData.top20/Math.max(1,paretoData.total)*100)}% da base)</div>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              {[{label:`Top 10% (${paretoData.top10} clientes)`,pct:paretoData.top10Pct,val:paretoData.top10Rev,color:'#2563EB'},{label:`Top 20% (${paretoData.top20} clientes)`,pct:paretoData.top20Pct,val:paretoData.top20Rev,color:'#EA580C'},{label:'Total da base',pct:100,val:paretoData.totalRev,color:'#6B7280'}].map(({label,pct,val,color})=>(
                <div key={label}>
                  <div style={{display:'flex',justifyContent:'space-between',fontSize:11,marginBottom:3}}>
                    <span style={{color:'#9CA3AF'}}>{label}</span>
                    <span style={{color,fontWeight:700}}>{pct.toFixed(1)}%  ·  {fmt(val)}</span>
                  </div>
                  <div style={{background:'#F9FAFB',borderRadius:3,height:5,overflow:'hidden'}}>
                    <div style={{height:'100%',width:`${pct}%`,background:color,borderRadius:3}}/>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Stock snapshot */}
          <div className="card">
            <STitle t="📦 Saúde do Estoque" s="Visão rápida"/>
            {[
              {label:'Valor em estoque (custo)',val:fmt(stockHealth.costVal),color:'#9CA3AF'},
              {label:'Valor em estoque (venda)',val:fmt(stockHealth.saleVal),color:'#2563EB'},
              {label:'Lucro potencial',val:fmt(stockHealth.potentialProfit),color:'#16A34A'},
              {label:'Dead stock (90d sem giro)',val:stockHealth.dead.length+' produtos',color:'#DC2626'},
              {label:'Capital parado',val:fmt(stockHealth.deadCostVal),color:'#DC2626'},
              {label:'Risco de ruptura',val:stockHealth.danger.length+' produtos',color:'#EA580C'},
            ].map(({label,val,color})=>(
              <div key={label} style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:9,paddingBottom:9,borderBottom:'1px solid #F3F4F6'}}>
                <span style={{fontSize:11,color:'#9CA3AF'}}>{label}</span>
                <span style={{fontSize:12,fontWeight:700,color}}>{val}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Canal de Venda */}
        {(()=>{
          const canalMap={};
          sales.forEach(s=>{const c=s.canal||'Não informado';canalMap[c]=(canalMap[c]||{count:0,revenue:0});canalMap[c].count++;canalMap[c].revenue+=saleFinalTotal(s);});
          const canalList=Object.entries(canalMap).map(([c,v])=>({canal:c,...v})).sort((a,b)=>b.revenue-a.revenue);
          const maxRev=canalList[0]?.revenue||1;
          if(canalList.length===0)return null;
          const canalColors={'WhatsApp':'#25d366','Instagram':'#e1306c','Indicação':'#2563EB','Loja Física':'#2196f3','Site':'#EA580C','Outro':'#9c27b0','Não informado':'#444'};
          return(
            <div className="card" style={{marginTop:16}}>
              <STitle t="📡 Canal de Venda" s="Distribuição por origem"/>
              <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(160px,1fr))',gap:12}}>
                {canalList.map(({canal,count,revenue})=>(
                  <div key={canal} style={{background:'#F8FAFB',borderRadius:8,padding:'12px 14px'}}>
                    <div style={{fontSize:12,fontWeight:700,color:canalColors[canal]||'#A89070',marginBottom:6}}>{canal}</div>
                    <div style={{background:'#F9FAFB',borderRadius:3,height:4,marginBottom:8,overflow:'hidden'}}>
                      <div style={{height:'100%',width:`${revenue/maxRev*100}%`,background:canalColors[canal]||'#A89070',borderRadius:3}}/>
                    </div>
                    <div style={{display:'flex',justifyContent:'space-between',fontSize:11}}>
                      <span style={{color:'#6B7280'}}>{count} venda{count!==1?'s':''}</span>
                      <span style={{color:'#374151',fontWeight:600}}>{fmt(revenue)}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })()}

        {/* [NOVO v112] A3 — Top Categorias do mês + RFM teaser */}
        {topCategorias.length>0&&(
          <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:16,marginTop:16}}>
            <div className="card">
              <STitle t="📂 Top Categorias" s="Receita acumulada · histórico completo"/>
              {topCategorias.slice(0,8).map((c,i)=>{
                const max = topCategorias[0].revenue||1;
                return(
                  <HBar key={c.cat} label={`${i+1}. ${c.cat}`} value={c.revenue} max={max} fmtFn={fmt} color={i===0?'#7C3AED':i<3?'#2563EB':'#9CA3AF'} sub={`${c.qty} un.`}/>
                );
              })}
            </div>
            <div className="card">
              <STitle t="👥 RFM — Segmentação de Clientes" s="Recência × Frequência × Monetary"/>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                <div style={{padding:'10px 12px',background:'linear-gradient(135deg,#FEF9E7,#FFFBEB)',border:'1px solid #C8A95155',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#92700A',fontWeight:700,textTransform:'uppercase'}}>👑 Champions</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#92700A',marginTop:2}}>{rfmMatrix.champion}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Comprou recente, frequente, alto valor</div>
                </div>
                <div style={{padding:'10px 12px',background:'#F0FDF4',border:'1px solid #16A34A33',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#15803D',fontWeight:700,textTransform:'uppercase'}}>💚 Leais</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#15803D',marginTop:2}}>{rfmMatrix.leais}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Recentes e frequentes</div>
                </div>
                <div style={{padding:'10px 12px',background:'#EFF6FF',border:'1px solid #2563EB33',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#1D4ED8',fontWeight:700,textTransform:'uppercase'}}>✨ Novos</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#1D4ED8',marginTop:2}}>{rfmMatrix.novos}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Compraram recente, ainda 1ª vez</div>
                </div>
                <div style={{padding:'10px 12px',background:'#FFEDD5',border:'1px solid #EA580C33',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#EA580C',fontWeight:700,textTransform:'uppercase'}}>⚠️ Em risco</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#EA580C',marginTop:2}}>{rfmMatrix.emRisco}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Frequentes mas sumiram</div>
                </div>
                <div style={{padding:'10px 12px',background:'#FEE2E2',border:'1px solid #DC262633',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#B91C1C',fontWeight:700,textTransform:'uppercase'}}>💀 Perdidos</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#B91C1C',marginTop:2}}>{rfmMatrix.perdidos}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Sem compra recente, baixo valor</div>
                </div>
                <div style={{padding:'10px 12px',background:'#F3F4F6',border:'1px solid #D1D5DB',borderRadius:8}}>
                  <div style={{fontSize:9,color:'#6B7280',fontWeight:700,textTransform:'uppercase'}}>😴 Hibernando</div>
                  <div style={{fontSize:22,fontWeight:900,color:'#6B7280',marginTop:2}}>{rfmMatrix.hibernando}</div>
                  <div style={{fontSize:10,color:'#6B7280'}}>Outros segmentos</div>
                </div>
              </div>
              <div style={{marginTop:10,fontSize:10,color:'#9CA3AF',textAlign:'center'}}>Vai pra aba <strong>Clientes</strong> pra ver detalhes completos</div>
            </div>
          </div>
        )}

        {/* [v120 INS2] Cross-sell de PRODUTOS movido pra aba Geral (era na aba Clientes erradamente) */}
        {crossSell.length>0&&(
          <div className="card" style={{marginTop:16}}>
            <STitle t="🔗 Cross-sell — Produtos comprados juntos" s="Top 10 pares que aparecem em vendas multi-item — base pra criar combos/bundles"/>
            <table style={{width:'100%',fontSize:12}}>
              <thead><tr style={{background:'#F8FAFB'}}>
                <th style={{textAlign:'left',padding:'8px 6px'}}>Produto A</th>
                <th style={{textAlign:'left',padding:'8px 6px'}}>Produto B</th>
                <th style={{textAlign:'right',padding:'8px 6px',width:80}}>Vendas juntas</th>
              </tr></thead>
              <tbody>
                {crossSell.map((p,i)=>(
                  <tr key={i} style={{borderBottom:'1px solid #F3F4F6'}}>
                    <td style={{padding:'8px 6px'}}>
                      <div style={{fontSize:11,fontWeight:600}}>{p.a}</div>
                      {p.brandA&&<div style={{fontSize:9,color:'#9CA3AF'}}>{p.brandA}</div>}
                    </td>
                    <td style={{padding:'8px 6px'}}>
                      <div style={{fontSize:11,fontWeight:600}}>{p.b}</div>
                      {p.brandB&&<div style={{fontSize:9,color:'#9CA3AF'}}>{p.brandB}</div>}
                    </td>
                    <td style={{padding:'8px 6px',textAlign:'right'}}>
                      <span style={{padding:'3px 10px',background:'#FEF9E7',color:'#92700A',borderRadius:4,fontWeight:700}}>{p.count}×</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{marginTop:10,fontSize:11,color:'#9CA3AF',fontStyle:'italic'}}>💡 Use estes pares pra criar combos/bundles de venda — tendem a vender juntos naturalmente.</div>
          </div>
        )}
      </div>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.insights = window.ZNX.widgets.insights || {};
  window.ZNX.widgets.insights.GeralPanel = GeralPanel;
})();
