// js/components/widgets/historico/RankingMetaPanel.jsx
// [Wave 22 v224.3 NUCLEAR] Ranking vendedoras + MinhaPosicao + MetaInfo + Comissão
// Extraído de HistoricoVendedor.jsx:
//   - Ranking vendedoras + privacy disclaimer (L589-649)
//   - Meta + Comissão cards (L655-718)
(function(){
  'use strict';
  const COLORS = {
    navy:'#1B2A4A', gold:'#B89840', goldSoft:'#FEF9E7',
    blue:'#2563EB',
    green:'#15803D', greenSoft:'#DCFCE7',
    orange:'#EA580C',
    gray:'#6B7280', grayBorder:'#E4E7EC',
    text:'#1C1C28'
  };

  // [Wave 22 v224.3 + v224.55 2026-05-28] vars+check MOVED to component body (preventivo)
  // regra_validacao_helpers_runtime_quando_ordem_scripts_uncertain

  function RankingMetaPanel({rankingVendedoras, minhaPosicao, metaInfo, vendedoraAlvo, isAdmin, mes}){
    // [v224.55 FIX-PREV-18 2026-05-28] vars+check em render time
    const calcs = window.ZNX && window.ZNX.historico && window.ZNX.historico.calcs;
    const widgets = window.ZNX && window.ZNX.widgets;
    const _missing = [];
    if(!calcs) _missing.push('historico.calcs');
    if(!widgets || !widgets.SectionHeader) _missing.push('SectionHeader');
    if(_missing.length){
      const _msg = '[RankingMetaPanel] deps faltando: ' + _missing.join(', ');
      console.error(_msg);
      if(window.Sentry && typeof window.Sentry.captureMessage === 'function'){
        window.Sentry.captureMessage(_msg, 'error');
      }
    }
    const fmtMes = (calcs && calcs.fmtMes) || function(m){return m;};
    const SectionHeader = widgets && widgets.SectionHeader;
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    return (
      <>
        {/* RANKING DE VENDEDORAS (L589-649) */}
        {rankingVendedoras && rankingVendedoras.length>1 && (
          <>
            <SectionHeader icon="🏆" title="Ranking de Vendedoras" subtitle={rankingVendedoras.length+' vendedoras ativas em '+fmtMes(mes)}/>
            <div style={{background:'#fff',border:'1px solid '+COLORS.grayBorder,borderRadius:12,padding:18,marginBottom:8}}>
              {minhaPosicao && (
                <div style={{background:'linear-gradient(135deg,'+COLORS.goldSoft+',#FFFBEB)',border:'1px solid '+COLORS.gold+'55',borderRadius:10,padding:'14px 18px',marginBottom:14,display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
                  <div style={{fontSize:36,fontWeight:900,color:COLORS.gold,lineHeight:1}}>#{minhaPosicao.posicao}</div>
                  <div style={{flex:1,minWidth:180}}>
                    <div style={{fontSize:14,fontWeight:800,color:COLORS.navy}}>{vendedoraAlvo} é a #{minhaPosicao.posicao} de {minhaPosicao.total}</div>
                    <div style={{fontSize:12,color:COLORS.gray,marginTop:3}}>
                      Top {100-minhaPosicao.percentil+1}% das vendedoras
                      {isAdmin && minhaPosicao.proxima && <span> · Faltam <strong style={{color:COLORS.orange}}>{fmt(minhaPosicao.gap)}</strong> pra alcançar {minhaPosicao.proxima.nome}</span>}
                      {!isAdmin && minhaPosicao.proxima && <span> · Próxima posição: <strong>{minhaPosicao.proxima.nome}</strong></span>}
                    </div>
                  </div>
                </div>
              )}
              {/* Tabela ranking — colunas adaptadas por role */}
              <div style={{maxHeight: rankingVendedoras.length>6?280:'auto', overflow:'auto'}}>
                {rankingVendedoras.map(function(r,i){
                  const isMe = r.nome===vendedoraAlvo;
                  const max = rankingVendedoras[0].valor || 1;
                  return (
                    <div key={r.nome} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 6px',borderBottom:'1px solid #F3F4F6',background:isMe?COLORS.goldSoft:'transparent',borderRadius:isMe?6:0}}>
                      <div style={{width:24,fontSize:12,fontWeight:700,color:i<3?COLORS.gold:COLORS.gray}}>#{i+1}</div>
                      <div style={{flex:1,fontSize:13,fontWeight:isMe?700:500,color:COLORS.text}}>{r.nome}{isMe&&<span style={{marginLeft:6,fontSize:10,color:COLORS.gold,fontWeight:700}}>(você)</span>}</div>
                      {isAdmin && (
                        <>
                          <div style={{width:160,height:8,background:'#F3F4F6',borderRadius:4,overflow:'hidden'}}>
                            <div style={{width:((r.valor/max)*100)+'%',height:'100%',background:isMe?COLORS.gold:COLORS.blue,borderRadius:4}}/>
                          </div>
                          <div style={{width:90,textAlign:'right',fontSize:12,fontWeight:700,color:COLORS.text}}>{fmt(r.valor)}</div>
                          <div style={{width:50,textAlign:'right',fontSize:11,color:COLORS.gray}}>{r.notas} nota{r.notas>1?'s':''}</div>
                        </>
                      )}
                      {!isAdmin && isMe && (
                        <>
                          <div style={{width:90,textAlign:'right',fontSize:12,fontWeight:700,color:COLORS.gold}}>{fmt(r.valor)}</div>
                          <div style={{width:50,textAlign:'right',fontSize:11,color:COLORS.gray}}>{r.notas} nota{r.notas>1?'s':''}</div>
                        </>
                      )}
                      {!isAdmin && !isMe && (
                        <div style={{width:140,textAlign:'right',fontSize:11,color:COLORS.gray,fontStyle:'italic'}}>—</div>
                      )}
                    </div>
                  );
                })}
              </div>
              {!isAdmin && (
                <div style={{marginTop:10,paddingTop:10,borderTop:'1px solid '+COLORS.grayBorder,fontSize:11,color:COLORS.gray,fontStyle:'italic',textAlign:'center'}}>
                  💡 Cada vendedora vê só o próprio valor. Foque em superar você mesma!
                </div>
              )}
            </div>
          </>
        )}

        {/* META + COMISSÃO (L655-718) */}
        {metaInfo && (
          <>
            <SectionHeader
              icon={metaInfo.isEmpresa?'🏢':'🎯'}
              title={metaInfo.isEmpresa?'Meta da Empresa':'Meta + Comissão'}
              subtitle={metaInfo.isEmpresa?'Visão consolidada do time — meta total da ZAYNEX':'Quanto falta pra bater + quanto você ganha'}
            />
            <div style={{display:'grid',gridTemplateColumns:'1.4fr 1fr',gap:14,marginBottom:8}}>
              {/* Meta + Progresso */}
              <div style={{background:'#fff',border:'1px solid '+COLORS.grayBorder,borderRadius:12,padding:18}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:6}}>
                  <div style={{fontSize:11,color:COLORS.gray,fontWeight:600,textTransform:'uppercase',letterSpacing:0.5}}>{metaInfo.isEmpresa?'Meta empresa':'Meta do mês'}</div>
                  <div style={{fontSize:22,fontWeight:900,color:metaInfo.baterMeta?COLORS.green:COLORS.navy}}>{metaInfo.pct.toFixed(1)}%</div>
                </div>
                <div style={{fontSize:13,color:COLORS.text,marginBottom:10}}>
                  <strong>{fmt(metaInfo.realizado)}</strong> de <strong>{fmt(metaInfo.meta)}</strong>
                  {metaInfo.falta>0 && <span style={{color:COLORS.orange,marginLeft:6}}> · faltam {fmt(metaInfo.falta)}</span>}
                </div>
                <div style={{height:14,background:'#F3F4F6',borderRadius:7,overflow:'hidden',marginBottom:14,position:'relative'}}>
                  <div style={{width:metaInfo.pct+'%',height:'100%',background:metaInfo.baterMeta?'linear-gradient(90deg,'+COLORS.green+',#22C55E)':'linear-gradient(90deg,'+COLORS.blue+','+COLORS.gold+')',borderRadius:7,transition:'width .3s'}}/>
                  {metaInfo.pct>=95 && <div style={{position:'absolute',top:0,bottom:0,left:'95%',width:1,background:COLORS.green}}/>}
                </div>
                <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,fontSize:12}}>
                  <div>
                    <div style={{color:COLORS.gray,fontSize:10,fontWeight:600,textTransform:'uppercase'}}>Projeção fim do mês</div>
                    <div style={{fontWeight:800,color:metaInfo.projecao>=metaInfo.meta?COLORS.green:COLORS.orange,marginTop:2}}>{fmt(metaInfo.projecao)}</div>
                  </div>
                  <div>
                    <div style={{color:COLORS.gray,fontSize:10,fontWeight:600,textTransform:'uppercase'}}>Ritmo necessário</div>
                    <div style={{fontWeight:800,color:COLORS.text,marginTop:2}}>
                      {metaInfo.diasRestantes>0?fmt(metaInfo.necessarioPorDia)+'/dia':'Mês fechado'}
                      {metaInfo.diasRestantes>0 && <span style={{fontSize:10,color:COLORS.gray,fontWeight:500}}> · {metaInfo.diasRestantes}d restantes</span>}
                    </div>
                  </div>
                </div>
              </div>
              {/* Comissão (vendedora) ou Estimativa (empresa) */}
              <div style={{background:metaInfo.baterMeta?'linear-gradient(135deg,'+COLORS.greenSoft+',#F0FDF4)':'linear-gradient(135deg,'+COLORS.goldSoft+',#FFFBEB)',border:'1px solid '+(metaInfo.baterMeta?COLORS.green:COLORS.gold)+'55',borderRadius:12,padding:18}}>
                <div style={{fontSize:11,color:metaInfo.baterMeta?COLORS.green:COLORS.gold,fontWeight:700,textTransform:'uppercase',letterSpacing:0.5,marginBottom:6}}>
                  {metaInfo.isEmpresa
                    ? (metaInfo.baterMeta?'✓ Empresa bateu — Comissões':'Comissões estimadas time')
                    : (metaInfo.baterMeta?'✓ Meta batida — Comissão de':'Comissão atual (sem bater meta)')
                  }
                </div>
                <div style={{fontSize:28,fontWeight:900,color:metaInfo.baterMeta?COLORS.green:COLORS.navy,lineHeight:1}}>{fmt(metaInfo.comissaoAtual)}</div>
                <div style={{fontSize:11,color:COLORS.gray,marginTop:4}}>
                  {metaInfo.isEmpresa
                    ? 'Estimativa: 0.5%–1% sobre realizado consolidado'
                    : (metaInfo.baterMeta?'1% sobre vendas líquidas':'0.5% sobre vendas (1% se bater meta)')
                  }
                </div>
                {!metaInfo.baterMeta && (
                  <div style={{marginTop:12,padding:'10px 12px',background:'rgba(255,255,255,0.7)',borderRadius:8,border:'1px dashed '+COLORS.gold}}>
                    <div style={{fontSize:10,color:COLORS.gray,fontWeight:600,textTransform:'uppercase'}}>{metaInfo.isEmpresa?'Se empresa bater →':'Se bater meta →'}</div>
                    <div style={{fontSize:18,fontWeight:800,color:COLORS.green,marginTop:2}}>{fmt(metaInfo.comissaoSeBater)}</div>
                    <div style={{fontSize:10,color:COLORS.green,marginTop:1,fontWeight:600}}>+{fmt(metaInfo.comissaoSeBater-metaInfo.comissaoAtual)} a mais</div>
                  </div>
                )}
              </div>
            </div>
          </>
        )}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.historico = window.ZNX.widgets.historico || {};
  window.ZNX.widgets.historico.RankingMetaPanel = RankingMetaPanel;
})();
