// js/components/widgets/regioes/OportunidadesPanel.jsx
// [Wave 20 v224.2 NUCLEAR] Oportunidades: concentração + gaps + reativar + premium + vendedoras
// Extraído de RegioesAnalytics.jsx:
//   - Concentração alerta (L595-607) [B2]
//   - Gaps cobertura (L753-783) [B1 + H3]
//   - Cidades reativar (L786-801) [B3]
//   - Cidades premium (L803-819) [H1]
//   - Vendedoras por UF (L953-971) [F1/F2 admin only]
(function() {
  'use strict';

  const C = {
    navy:'#1B2A4A', gold:'#B89840', goldSoft:'#FEF9E7',
    blue:'#2563EB',
    red:'#DC2626', redSoft:'#FEE2E2',
    orange:'#EA580C', orangeSoft:'#FFEDD5',
    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 OportunidadesPanel({concentracao, ufsSemCobertura, cidadesGrandesSemCliente, cidadesParaReativar, cidadesPremium, vendedorasPorUf, isAdmin}){
    // [v224.55 FIX-PREV-24 2026-05-28] vars+check em render time
    const calcs = window.ZNX && window.ZNX.regioes && window.ZNX.regioes.calcs;
    const widgets = window.ZNX && window.ZNX.widgets;
    const _missing = [];
    if (!calcs) _missing.push('regioes.calcs');
    if (!widgets || !widgets.SectionHeader) _missing.push('SectionHeader');
    if (_missing.length) {
      const _msg = '[OportunidadesPanel] deps faltando: ' + _missing.join(', ');
      console.error(_msg);
      if (window.Sentry && typeof window.Sentry.captureMessage === 'function') {
        window.Sentry.captureMessage(_msg, 'error');
      }
    }
    const UF_NAMES = (calcs && calcs.UF_NAMES) || {};
    const SectionHeader = widgets && widgets.SectionHeader;
    const fmt = window.fmt || function(v){return 'R$ '+Number(v||0).toFixed(2);};
    return (
      <>
        {/* B2: ALERTA CONCENTRAÇÃO (L596-607) */}
        {concentracao&&concentracao.pct>=30&&(
          <div style={{background:concentracao.pct>=50?C.redSoft:C.orangeSoft,border:'1px solid '+(concentracao.pct>=50?C.red:C.orange)+'55',borderRadius:10,padding:'14px 18px',marginBottom:14,display:'flex',alignItems:'center',gap:14}}>
            <span style={{fontSize:24}}>{concentracao.pct>=50?'🚨':'⚠️'}</span>
            <div style={{flex:1}}>
              <div style={{fontSize:14,fontWeight:800,color:concentracao.pct>=50?C.red:C.orange}}>Concentração de risco geográfica</div>
              <div style={{fontSize:12,color:C.text,marginTop:3}}>
                <strong>{concentracao.nome} ({concentracao.uf})</strong> representa <strong>{concentracao.pct.toFixed(0)}%</strong> da receita do mês ({fmt(concentracao.receita)}).
                {concentracao.pct>=50?' Diversificação geográfica é estratégica pra reduzir risco.':' Considere expandir presença em outros estados.'}
              </div>
            </div>
          </div>
        )}

        {/* B1 + H3: Gaps de cobertura (L753-783) */}
        {((ufsSemCobertura&&ufsSemCobertura.length>0)||(cidadesGrandesSemCliente&&cidadesGrandesSemCliente.length>0))&&(
          <>
            <SectionHeader icon="🎯" title="Oportunidades de expansão" subtitle="Onde a ZAYNEX ainda não chegou"/>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:8}}>
              {ufsSemCobertura&&ufsSemCobertura.length>0&&(
                <div style={{background:'#fff',border:'1px solid '+C.grayBorder,borderRadius:12,padding:18}}>
                  <div style={{fontSize:12,color:C.gold,fontWeight:700,textTransform:'uppercase',letterSpacing:0.5,marginBottom:10}}>🗺️ Estados sem cliente ({ufsSemCobertura.length})</div>
                  <div style={{display:'flex',flexWrap:'wrap',gap:6}}>
                    {ufsSemCobertura.map(function(uf){
                      return (
                        <div key={uf} style={{padding:'6px 10px',background:C.goldSoft,border:'1px solid '+C.gold+'33',borderRadius:6,fontSize:11,fontWeight:600,color:C.navy}}>
                          {uf} <span style={{color:C.gray,fontWeight:400}}>{UF_NAMES[uf]}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
              {cidadesGrandesSemCliente&&cidadesGrandesSemCliente.length>0&&(
                <div style={{background:'#fff',border:'1px solid '+C.grayBorder,borderRadius:12,padding:18}}>
                  <div style={{fontSize:12,color:C.purple,fontWeight:700,textTransform:'uppercase',letterSpacing:0.5,marginBottom:10}}>🏙️ Cidades grandes sem cliente</div>
                  <div style={{maxHeight:200,overflow:'auto'}}>
                    {cidadesGrandesSemCliente.map(function(line){
                      const parts = line.split('|');
                      const cidade = parts[0], uf = parts[1];
                      return (
                        <div key={line} style={{display:'flex',justifyContent:'space-between',padding:'4px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                          <span><strong>{cidade}</strong></span><span style={{color:C.gray}}>{uf}</span>
                        </div>
                      );
                    })}
                  </div>
                  <div style={{marginTop:8,paddingTop:8,borderTop:'1px solid '+C.grayBorder,fontSize:10,color:C.gray,fontStyle:'italic'}}>Top 50 cidades BR (IBGE) — não atendidas</div>
                </div>
              )}
            </div>
          </>
        )}

        {/* B3: Cidades pra reativar (L786-801) */}
        {cidadesParaReativar&&cidadesParaReativar.length>0&&(
          <>
            <SectionHeader icon="🔄" title="Cidades pra reativar" subtitle="3+ clientes com 2+ em risco (sem comprar há 30+ dias)"/>
            <div style={{background:'#fff',border:'1px solid '+C.orange+'33',borderRadius:12,padding:18,marginBottom:8}}>
              {cidadesParaReativar.map(function(r){
                return (
                  <div key={r.cidade+r.estado} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                    <div>
                      <strong>{r.cidade}</strong> <span style={{color:C.gray,fontSize:10,marginLeft:4}}>{r.estado}</span>
                      <div style={{fontSize:10,color:C.gray,marginTop:1}}>{r.clientes} clientes total · pico {r.maxDias} dias sem comprar</div>
                    </div>
                    <div style={{fontWeight:700,color:C.orange}}>{r.emRisco} em risco</div>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {/* H1: Cidades premium (L804-819) */}
        {cidadesPremium&&cidadesPremium.length>0&&(
          <>
            <SectionHeader icon="💎" title="Cidades premium" subtitle="Poucas vendas mas ticket acima de 1.5× a média"/>
            <div style={{background:'#fff',border:'1px solid '+C.gold+'33',borderRadius:12,padding:18,marginBottom:8}}>
              {cidadesPremium.map(function(r){
                return (
                  <div key={r.cidade+r.estado} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'8px 0',borderBottom:'1px solid #F3F4F6',fontSize:12}}>
                    <div>
                      <strong>{r.cidade}</strong> <span style={{color:C.gray,fontSize:10,marginLeft:4}}>{r.estado}</span>
                      <div style={{fontSize:10,color:C.gray,marginTop:1}}>{r.vendas} venda{r.vendas>1?'s':''} · {fmt(r.receita)} total</div>
                    </div>
                    <div style={{fontWeight:700,color:C.gold,fontSize:14}}>{fmt(r.ticket)}</div>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {/* F1+F2 (admin only): Vendedoras x região (L953-971) */}
        {isAdmin&&vendedorasPorUf&&Object.keys(vendedorasPorUf).length>0&&(
          <>
            <SectionHeader icon="👩" title="Vendedoras por estado" subtitle="Top 3 vendedoras por receita em cada estado (top 8 estados)" adminOnly/>
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(220px,1fr))',gap:14,marginBottom:8}}>
              {Object.entries(vendedorasPorUf).map(function(entry){
                const uf = entry[0], vends = entry[1];
                return (
                  <div key={uf} style={{background:'#fff',border:'1px solid '+C.purple+'33',borderRadius:10,padding:14}}>
                    <div style={{fontSize:13,fontWeight:800,color:C.navy,marginBottom:8}}>{uf} <span style={{fontSize:10,color:C.gray,fontWeight:400}}>{UF_NAMES[uf]}</span></div>
                    {vends.map(function(v,i){
                      return (
                        <div key={v.nome} style={{display:'flex',justifyContent:'space-between',fontSize:11,padding:'3px 0',borderBottom:i<vends.length-1?'1px solid #F3F4F6':'none'}}>
                          <span style={{fontWeight:600,color:C.text}}>{i+1}. {v.nome}</span>
                          <span style={{color:C.gold,fontWeight:600}}>{fmt(v.receita)}</span>
                        </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.OportunidadesPanel = OportunidadesPanel;
})();
