// js/components/widgets/regioes/RankingsPanel.jsx
// [Wave 20 v224.2 NUCLEAR] Rankings estados + cidades + crescimento + sazonalidade
// Extraído de RegioesAnalytics.jsx:
//   - Ranking estados (L672-698)
//   - Top cidades (L700-719)
//   - Crescimento/queda (L721-750)
//   - Sazonalidade (L821-846)
(function() {
  'use strict';

  const C = {
    navy:'#1B2A4A', gold:'#B89840',
    blue:'#2563EB',
    green:'#15803D',
    red:'#DC2626',
    orange:'#EA580C',
    purple:'#7C3AED',
    gray:'#6B7280', grayBorder:'#E4E7EC',
    text:'#1C1C28'
  };

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

  function RankingsPanel({ufRanking, statsByUfPrev, margemPorUf, topCidades, cidadesAtendidas, estadosCrescimento, sazonalidadeTop5, mes}){
    // [v224.55 FIX-PREV-25 2026-05-28] vars+check em render time
    // regra_estender_bloco_refs_fail_loud — 1 bloco agregado
    const calcs = window.ZNX && window.ZNX.regioes && window.ZNX.regioes.calcs;
    const regiosW = window.ZNX && window.ZNX.widgets && window.ZNX.widgets.regioes;
    const widgets = window.ZNX && window.ZNX.widgets;
    const _missing = [];
    if (!calcs) _missing.push('regioes.calcs');
    if (!regiosW || !regiosW.MiniBar) _missing.push('regioes.MiniBar');
    if (!widgets || !widgets.SectionHeader) _missing.push('SectionHeader');
    if (_missing.length) {
      const _msg = '[RankingsPanel] deps faltando: ' + _missing.join(', ');
      console.error(_msg);
      if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
        window.Sentry.captureMessage(_msg, 'error');
      }
    }
    const fmtPct = (calcs && calcs.fmtPct) || function(v){return v.toFixed(1)+'%';};
    const fmtMes = (calcs && calcs.fmtMes) || function(m){return m;};
    const UF_NAMES = (calcs && calcs.UF_NAMES) || {};
    // pctColor local — converte cor hex retornada por calcs.pctColor pra C local
    const pctColor = (calcs && calcs.pctColor) || function(v){return v>=10?C.green:v>=0?C.blue:v>=-10?C.orange:C.red;};
    const MiniBar = regiosW && regiosW.MiniBar;
    const SectionHeader = widgets && widgets.SectionHeader;
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    if(!ufRanking||ufRanking.length===0) return null;
    return (
      <>
        {/* RANKING DE ESTADOS (L673-698) */}
        <SectionHeader icon="🏆" title="Ranking de Estados" subtitle={'Top '+Math.min(15,ufRanking.length)+' por receita em '+fmtMes(mes)}/>
        <div style={{background:'#fff',border:'1px solid '+C.grayBorder,borderRadius:12,padding:18,marginBottom:8}}>
          {ufRanking.slice(0,15).map(function(r,i){
            const max = ufRanking[0].receita||1;
            const prev = (statsByUfPrev[r.uf] && statsByUfPrev[r.uf].receita) || 0;
            const variacao = prev>0 ? ((r.receita-prev)/prev)*100 : null;
            const margem = margemPorUf && margemPorUf[r.uf];
            return(
              <div key={r.uf} style={{display:'grid',gridTemplateColumns:'auto 80px 1fr 100px 60px 80px',gap:10,alignItems:'center',padding:'8px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                <div style={{width:24,fontWeight:700,color:i<3?C.gold:C.gray}}>#{i+1}</div>
                <div style={{fontWeight:700,color:C.navy}}>{r.uf} <span style={{fontWeight:400,color:C.gray,fontSize:10}}>{UF_NAMES[r.uf]}</span></div>
                <MiniBar pct={(r.receita/max)*100} color={i===0?C.gold:C.blue}/>
                <div style={{textAlign:'right',fontWeight:700,color:C.text}}>{fmt(r.receita)}</div>
                <div style={{textAlign:'right',color:C.gray,fontSize:11}}>{r.vendas}v · {r.clientes}c</div>
                <div style={{textAlign:'right',fontSize:11,fontWeight:600}}>
                  {variacao!==null?<span style={{color:pctColor(variacao)}}>{fmtPct(variacao)}</span>:<span style={{color:C.gray,fontStyle:'italic'}}>novo</span>}
                  {margem&&margem.margem>0&&<div style={{fontSize:9,color:C.green}}>{margem.margem.toFixed(0)}% margem</div>}
                </div>
              </div>
            );
          })}
        </div>

        {/* TOP CIDADES (L700-719) */}
        {topCidades&&topCidades.length>0&&(
          <>
            <SectionHeader icon="🏙️" title="Top Cidades por Receita" subtitle={cidadesAtendidas+' cidades com vendas no mês'}/>
            <div style={{background:'#fff',border:'1px solid '+C.grayBorder,borderRadius:12,padding:18,marginBottom:8}}>
              {topCidades.map(function(r,i){
                const max = topCidades[0].receita||1;
                return(
                  <div key={r.cidade+r.estado} style={{display:'grid',gridTemplateColumns:'auto 1fr 100px 80px 80px',gap:10,alignItems:'center',padding:'8px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                    <div style={{width:24,fontWeight:700,color:i<3?C.gold:C.gray}}>#{i+1}</div>
                    <div><strong>{r.cidade}</strong> <span style={{color:C.gray,fontSize:10}}>{r.estado}</span></div>
                    <MiniBar pct={(r.receita/max)*100} color={C.purple}/>
                    <div style={{textAlign:'right',fontWeight:700,color:C.text}}>{fmt(r.receita)}</div>
                    <div style={{textAlign:'right',color:C.gray,fontSize:11}}>{fmt(r.ticket)} ticket</div>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {/* CRESCIMENTO/QUEDA (L721-750) */}
        {estadosCrescimento && (estadosCrescimento.ascensao.length>0||estadosCrescimento.queda.length>0)&&(
          <>
            <SectionHeader icon="📈" title="Estados em movimento" subtitle="Crescimento e queda vs mês anterior"/>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:8}}>
              <div style={{background:'#fff',border:'1px solid '+C.green+'33',borderRadius:12,padding:18}}>
                <div style={{fontSize:12,color:C.green,fontWeight:700,textTransform:'uppercase',letterSpacing:0.5,marginBottom:10}}>🚀 Em ascensão</div>
                {estadosCrescimento.ascensao.length===0?<div style={{fontSize:11,color:C.gray,fontStyle:'italic'}}>Nenhum estado com crescimento {'>='} 50%</div>:
                  estadosCrescimento.ascensao.map(function(s){
                    return (
                      <div key={s.uf} style={{display:'flex',justifyContent:'space-between',padding:'6px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                        <span><strong>{s.uf}</strong> · {s.nome}</span>
                        <span style={{color:C.green,fontWeight:700}}>{fmtPct(s.variacao)} · {fmt(s.atual)}</span>
                      </div>
                    );
                  })
                }
              </div>
              <div style={{background:'#fff',border:'1px solid '+C.red+'33',borderRadius:12,padding:18}}>
                <div style={{fontSize:12,color:C.red,fontWeight:700,textTransform:'uppercase',letterSpacing:0.5,marginBottom:10}}>📉 Em queda</div>
                {estadosCrescimento.queda.length===0?<div style={{fontSize:11,color:C.gray,fontStyle:'italic'}}>Nenhum estado com queda {'>'} 20%</div>:
                  estadosCrescimento.queda.map(function(s){
                    return (
                      <div key={s.uf} style={{display:'flex',justifyContent:'space-between',padding:'6px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                        <span><strong>{s.uf}</strong> · {s.nome}</span>
                        <span style={{color:C.red,fontWeight:700}}>{fmtPct(s.variacao)} · {fmt(s.atual)}</span>
                      </div>
                    );
                  })
                }
              </div>
            </div>
          </>
        )}

        {/* SAZONALIDADE (L821-846) */}
        {sazonalidadeTop5 && sazonalidadeTop5.result.length>0 && sazonalidadeTop5.result[0].valores.some(function(v){return v>0;}) && (
          <>
            <SectionHeader icon="📅" title="Sazonalidade · Top 5 estados" subtitle="Receita mensal nos últimos 6 meses"/>
            <div style={{background:'#fff',border:'1px solid '+C.grayBorder,borderRadius:12,padding:18,marginBottom:8}}>
              <div style={{display:'grid',gridTemplateColumns:'80px repeat(6,1fr)',gap:8,fontSize:11,fontWeight:600,color:C.gray,marginBottom:6,paddingBottom:6,borderBottom:'1px solid '+C.grayBorder}}>
                <div></div>
                {sazonalidadeTop5.meses.map(function(m){return <div key={m.mes} style={{textAlign:'center'}}>{m.label}</div>;})}
              </div>
              {sazonalidadeTop5.result.map(function(row){
                const uf = row.uf, valores = row.valores;
                const maxValor = Math.max.apply(null, valores.concat([1]));
                return(
                  <div key={uf} style={{display:'grid',gridTemplateColumns:'80px repeat(6,1fr)',gap:8,fontSize:11,padding:'6px 0',alignItems:'center'}}>
                    <div style={{fontWeight:700,color:C.navy}}>{uf}</div>
                    {valores.map(function(v,i){
                      return (
                        <div key={i} style={{position:'relative',height:24,background:'#F3F4F6',borderRadius:3,overflow:'hidden'}}>
                          <div style={{position:'absolute',inset:0,width:((v/maxValor)*100)+'%',background:i===valores.length-1?C.gold:C.blue}}/>
                          <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',fontSize:9,fontWeight:600,color:v>0?'#fff':C.gray}}>{v>=1000?(v/1000).toFixed(0)+'k':v||''}</div>
                        </div>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          </>
        )}
      </>
    );
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.widgets = window.ZNX.widgets || {};
  window.ZNX.widgets.regioes = window.ZNX.widgets.regioes || {};
  window.ZNX.widgets.regioes.RankingsPanel = RankingsPanel;
})();
