/* global React, ReactDOM */
const { useState: U, useEffect: E, useRef: R, useMemo: M } = React;
const { Icon, DashboardView, TalentosView, ProjetosView, RedeView, OportunidadesView,
  MeuPerfilView, EmpresaView, TalentDetail, Avatar } = window;

const PERSONAS = [
  {id:'comite',     name:'Comitê / Gestor regional', sub:'Visão executiva da rede', color:'#0B5FBE', icon:'briefcase'},
  {id:'talento',    name:'Maria — Talento',          sub:'Estudante / profissional', color:'#06B6D4', icon:'user'},
  {id:'empresa',    name:'Iguatu Têxtil — Empresa',  sub:'Buscando talentos',        color:'#10B981', icon:'building'},
  {id:'instituicao',name:'IFCE — Instituição',       sub:'Educação / Sebrae',        color:'#F59E0B', icon:'book'},
  {id:'mentor',     name:'Cristiane — Mentora',      sub:'Mentoria & orientação',    color:'#7C3AED', icon:'star'},
  {id:'startup',    name:'AgroSensor — Startup',     sub:'Projeto em validação',     color:'#DB2777', icon:'rocket'},
];

const NAV_BY_PERSONA = {
  comite:     [{k:'mapa',l:'Mapa',i:'map'},{k:'dashboard',l:'Visão geral',i:'grid'},{k:'talentos',l:'Talentos',i:'users',c:24},{k:'projetos',l:'Projetos',i:'rocket',c:14},{k:'oportunidades',l:'Oportunidades',i:'trophy',c:8},{k:'mentores',l:'Mentores',i:'star'}],
  talento:    [{k:'mapa',l:'Mapa',i:'map'},{k:'meu',l:'Meu perfil',i:'user'},{k:'oportunidades',l:'Oportunidades',i:'trophy',c:8},{k:'projetos',l:'Projetos',i:'rocket'}],
  empresa:    [{k:'mapa',l:'Mapa',i:'map'},{k:'empresa',l:'Buscar talentos',i:'users'},{k:'projetos',l:'Projetos',i:'rocket'}],
  instituicao:[{k:'mapa',l:'Mapa',i:'map'},{k:'dashboard',l:'Visão geral',i:'grid'},{k:'talentos',l:'Meus alunos',i:'users',c:24},{k:'oportunidades',l:'Editais',i:'trophy'}],
  mentor:     [{k:'mapa',l:'Mapa',i:'map'},{k:'meu',l:'Meu perfil',i:'user'},{k:'talentos',l:'Mentorados',i:'users',c:14},{k:'projetos',l:'Projetos apoiados',i:'rocket'},{k:'oportunidades',l:'Oportunidades',i:'trophy'}],
  startup:    [{k:'mapa',l:'Mapa',i:'map'},{k:'meu',l:'Meu projeto',i:'rocket'},{k:'oportunidades',l:'Editais & eventos',i:'trophy'},{k:'talentos',l:'Procurar time',i:'users'}],
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryColor":"#0B5FBE",
  "density":"normal",
  "dashboardLayout":"grid"
}/*EDITMODE-END*/;

function App() {
  const [persona, setPersona] = U('comite');
  const [view, setView] = U('mapa');
  const [personaOpen, setPersonaOpen] = U(false);
  const [talentoSel, setTalentoSel] = U(null);
  const [search, setSearch] = U('');
  const [searchOpen, setSearchOpen] = U(false);

  const tweaks = (window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, ()=>{}]);
  const t = tweaks[0]; const setT = tweaks[1];

  E(() => {
    document.documentElement.style.setProperty('--primary', t.primaryColor);
    document.documentElement.style.setProperty('--blue-700', t.primaryColor);
    document.documentElement.dataset.density = t.density;
    document.documentElement.dataset.dashboard = t.dashboardLayout;
  }, [t.primaryColor, t.density, t.dashboardLayout]);

  E(() => {
    const nav = NAV_BY_PERSONA[persona];
    if (!nav.find(n => n.k === view)) setView(nav[0].k);
  }, [persona]);

  // Close persona panel on click outside
  E(() => {
    if (!personaOpen) return;
    const onClick = (e) => {
      if (!e.target.closest('.persona-panel') && !e.target.closest('.persona')) setPersonaOpen(false);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [personaOpen]);

  const onSelectTalento = (id) => setTalentoSel(id);
  const onSelectProjeto = () => setView('projetos');

  const persObj = PERSONAS.find(p => p.id === persona);

  const renderView = () => {
    switch(view) {
      case 'mapa': return <MapaPage onSelectTalento={onSelectTalento}/>;
      case 'dashboard': return <DashboardView onSelectTalento={onSelectTalento} onSelectProjeto={onSelectProjeto}/>;
      case 'talentos': return <TalentosView onSelectTalento={onSelectTalento}/>;
      case 'projetos': return <ProjetosView onSelectProjeto={onSelectProjeto}/>;
      case 'oportunidades': return <OportunidadesView/>;
      case 'mentores': return <MentoresView/>;
      case 'meu': return <MeuPerfilView talentoId={persona==='mentor'?'t13':'t1'} onOpenProjeto={onSelectProjeto}/>;
      case 'empresa': return <EmpresaView onSelectTalento={onSelectTalento}/>;
      default: return <MapaPage onSelectTalento={onSelectTalento}/>;
    }
  };

  const nav = NAV_BY_PERSONA[persona];

  return <div className="shell">
    <header className="topnav">
      <div className="tn-brand">
        <div className="tn-mark" aria-label="MRTI">
          <svg viewBox="0 0 120 120" width="28" height="28" style={{display:'block'}}>
            <circle cx="60" cy="60" r="46" fill="none" stroke="#fff" strokeWidth="2" opacity=".45"/>
            <g fill="#fff">
              <circle cx="60" cy="60" r="6"/>
              <circle cx="38" cy="42" r="4.5"/>
              <circle cx="82" cy="38" r="4.5"/>
              <circle cx="32" cy="72" r="4.5"/>
              <circle cx="86" cy="78" r="4.5"/>
              <circle cx="56" cy="86" r="4.5"/>
            </g>
            <g stroke="#fff" strokeWidth="1.4" opacity=".55">
              <line x1="60" y1="60" x2="38" y2="42"/>
              <line x1="60" y1="60" x2="82" y2="38"/>
              <line x1="60" y1="60" x2="32" y2="72"/>
              <line x1="60" y1="60" x2="86" y2="78"/>
              <line x1="60" y1="60" x2="56" y2="86"/>
            </g>
          </svg>
        </div>
        <div className="tn-sub-only">Inova Centro-Sul</div>
      </div>
      <div className="tn-divider"/>
      <nav className="tn-menu">
        {nav.map(n => (
          <div key={n.k} className={`tn-item ${view===n.k?'active':''}`} onClick={() => setView(n.k)}>
            <Icon name={n.i} size={15}/>
            {n.l}
            {n.c && <span className="badge">{n.c}</span>}
          </div>
        ))}
      </nav>
      <div className="tn-actions">
        <div className={`tn-search ${searchOpen?'is-open':''}`}>
          <button className="tn-search-btn" onClick={()=>{ setSearchOpen(o=>!o); setTimeout(()=>{ const el=document.getElementById('tn-search-input'); if(el) el.focus(); }, 50); }} title="Buscar">
            <Icon name="search" size={16}/>
          </button>
          <input id="tn-search-input" placeholder="Buscar talento, projeto, município…"
            value={search} onChange={e=>setSearch(e.target.value)}
            onBlur={()=>{ if(!search) setSearchOpen(false); }}/>
        </div>

        <div style={{position:'relative'}}>
          <div className="persona" onClick={(e) => { e.stopPropagation(); setPersonaOpen(o=>!o); }}>
            <span className="persona-dot"/>
            <span className="persona-name">{persObj.name.split('—')[0].trim()}</span>
            <span className="persona-arrow">▾</span>
          </div>
          {personaOpen && (
            <div className="persona-panel" style={{top:50}}>
              <div className="pp-head">Visualizar plataforma como…</div>
              {PERSONAS.map(p => (
                <div key={p.id} className={`pp-item ${persona===p.id?'active':''}`}
                  onClick={() => { setPersona(p.id); setPersonaOpen(false); }}>
                  <div className="pp-ic" style={{background:p.color+'22', color:p.color}}>
                    <Icon name={p.icon} size={15}/>
                  </div>
                  <div style={{flex:1, minWidth:0}}>
                    <div className="pp-name">{p.name}</div>
                    <div className="pp-sub">{p.sub}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </header>

    <main className="main">
      <div className="content">
        <div className="page" style={view==='mapa'?{padding:0, maxWidth:'none'}:{}}>{renderView()}</div>
      </div>
    </main>

    {talentoSel && <TalentDetail talentId={talentoSel}
      onClose={() => setTalentoSel(null)}
      onOpenProjeto={() => { setTalentoSel(null); setView('projetos'); }}/>}

    {window.TweaksPanel && (
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Cor da marca">
          <window.TweakColor t={t} setT={setT} k="primaryColor"
            options={[
              ['#0B5FBE','#0E3F84','#1976E0'],
              ['#0E7490','#06B6D4','#0891B2'],
              ['#7C3AED','#5B21B6','#A78BFA'],
              ['#059669','#10B981','#047857'],
            ]}/>
        </window.TweakSection>
        <window.TweakSection title="Densidade da informação">
          <window.TweakRadio t={t} setT={setT} k="density"
            options={[{value:'compact',label:'Compacto'},{value:'normal',label:'Normal'},{value:'comfy',label:'Amplo'}]}/>
        </window.TweakSection>
        <window.TweakSection title="Layout do dashboard">
          <window.TweakRadio t={t} setT={setT} k="dashboardLayout"
            options={[{value:'grid',label:'Grade'},{value:'column',label:'Coluna'}]}/>
        </window.TweakSection>
        <window.TweakSection title="Persona ativa">
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6}}>
            {PERSONAS.map(p => (
              <button key={p.id} onClick={() => setPersona(p.id)}
                style={{padding:'8px 10px', borderRadius:8,
                  border: persona===p.id ? '2px solid '+p.color : '1px solid #E2E8F0',
                  background: persona===p.id ? p.color+'18' : '#fff',
                  fontSize:11.5, fontWeight:600, cursor:'pointer', textAlign:'left',
                  color: persona===p.id ? p.color : '#334155'}}>
                {p.name.split('—')[0].trim()}
              </button>
            ))}
          </div>
        </window.TweakSection>
      </window.TweaksPanel>
    )}
  </div>;
}

// ============ Mapa standalone page — fullbleed map + click-to-open city popover ============
function MapaPage({onSelectTalento}) {
  const [heatmap, setHeatmap] = U('talentos');
  const [focused, setFocused] = U(null);
  const [tab, setTab] = U('talentos');
  const [filter, setFilter] = U('todos');
  const stageRef = R(null);
  const [allOpen, setAllOpen] = U(false);
  const [zoomOut, setZoomOut] = U(0); // 0..1 accumulator for "afastar" gesture
  const zoomTimer = R(null);

  const focMun = focused ? window.MUNICIPALITIES.find(c => c.id === focused) : null;

  // Detectar gesto de "afastar" o mapa: roda do mouse para cima (deltaY > 0) ou pinch out.
  // Acumula um valor 0..1; ao passar 1, abre a tela com todos os talentos.
  E(() => {
    const el = stageRef.current;
    if (!el) return;
    const onWheel = (e) => {
      if (allOpen || focMun) return;
      // deltaY positivo = afastando (scroll para baixo / pinch para fora em trackpad é geralmente negativo;
      // priorizamos o scroll-wheel para cima = zoom-out clássico)
      if (e.deltaY > 0) {
        e.preventDefault();
        setZoomOut(z => {
          const next = Math.min(1, z + Math.min(0.06, e.deltaY / 600));
          if (next >= 1) {
            setAllOpen(true);
            return 0;
          }
          return next;
        });
        clearTimeout(zoomTimer.current);
        zoomTimer.current = setTimeout(() => setZoomOut(0), 700);
      }
    };
    el.addEventListener('wheel', onWheel, {passive:false});
    return () => el.removeEventListener('wheel', onWheel);
  }, [allOpen, focMun]);

  const talentosCity = M(() => focMun ? window.TALENTOS.filter(t => t.cidade === focMun.nome) : [], [focMun]);
  const projetosCity = M(() => focMun ? window.PROJETOS_INOV.filter(p => p.cidade === focMun.nome) : [], [focMun]);
  const oportunidadesCity = M(() => focMun ? (window.OPORTUNIDADES||[]).filter(o => !o.cidade || o.cidade === focMun.nome || o.cidade === 'Centro-Sul') : [], [focMun]);
  const mentoresCity = M(() => focMun ? (window.MENTORES||[]).filter(m => m.cidade === focMun.nome) : [], [focMun]);

  // Filters
  const PROJ_FILTERS = ['todos','ideação','validação','MVP','operação'];

  // Talentos: sempre ordenados por pontuação na trilha (decrescente)
  const filteredTalents = M(() => {
    return [...talentosCity].sort((a,b) => (b.pontos||0) - (a.pontos||0));
  }, [talentosCity]);

  const filteredProjs = M(() => {
    if (filter === 'todos') return projetosCity;
    return projetosCity.filter(p => (p.fase||'').toLowerCase().includes(filter.toLowerCase()));
  }, [projetosCity, filter]);

  E(() => { setFilter('todos'); }, [tab, focMun]);

  // Compute popover position next to clicked city
  const [popPos, setPopPos] = U({left: 20, top: 80});
  E(() => {
    if (!focMun || !stageRef.current) return;
    const stage = stageRef.current.getBoundingClientRect();
    const svg = stageRef.current.querySelector('svg.map-svg');
    if (!svg) return;
    // Find the path for this municipality
    const pathEl = svg.querySelector(`path[data-mun="${focMun.id}"]`);
    let cx, cy;
    if (pathEl) {
      const bb = pathEl.getBoundingClientRect();
      cx = bb.left + bb.width/2 - stage.left;
      cy = bb.top + bb.height/2 - stage.top;
    } else {
      cx = stage.width/2; cy = stage.height/2;
    }
    // Place to the right by default; flip if not enough space
    const popW = 420, popH = 480;
    let left = cx + 30;
    if (left + popW > stage.width - 12) left = cx - popW - 30;
    if (left < 12) left = 12;
    let top = cy - popH/2;
    if (top < 12) top = 12;
    if (top + popH > stage.height - 12) top = stage.height - popH - 12;
    setPopPos({ left, top });
  }, [focMun]);

  return <div style={{height:'calc(100vh - 68px)', display:'flex', flexDirection:'column'}}>
    <div className="map-canvas" ref={stageRef} style={{flex:1, minHeight:0, position:'relative', background:'linear-gradient(180deg,#F4F8FE,#EAF1FB)', overflow:'hidden'}}>
      <div style={{position:'absolute', inset:0, transform:`scale(${1 - zoomOut*0.18})`, opacity: 1 - zoomOut*0.45, transformOrigin:'center', transition: zoomOut===0 ? 'transform .35s ease, opacity .35s ease' : 'none'}}>
        <window.MapCS heatmap={heatmap} focused={focused} onSelect={setFocused}/>
      </div>

      {/* Hint de "afastar para ver todos" */}
      {zoomOut > 0.05 && !allOpen && (
        <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', pointerEvents:'none', zIndex:5}}>
          <div style={{background:'rgba(11,18,32,.88)', color:'#fff', padding:'14px 22px', borderRadius:14, fontFamily:'Outfit', fontWeight:600, fontSize:15, letterSpacing:'-0.01em', boxShadow:'0 14px 40px rgba(11,18,32,.3)', display:'flex', alignItems:'center', gap:12}}>
            <div style={{width:36, height:36, borderRadius:'50%', border:'2px solid rgba(255,255,255,.2)', position:'relative'}}>
              <div style={{position:'absolute', inset:2, borderRadius:'50%', background:'conic-gradient(#5BA3F5 ' + (zoomOut*360) + 'deg, transparent 0)'}}/>
              <div style={{position:'absolute', inset:6, borderRadius:'50%', background:'#0B1220', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14}}>↗</div>
            </div>
            <div>
              <div style={{fontSize:11, opacity:.65, fontFamily:'Inter', textTransform:'uppercase', letterSpacing:'.08em', fontWeight:600}}>Continue afastando</div>
              <div>Ver todos os talentos da região</div>
            </div>
          </div>
        </div>
      )}

      {/* top-left toolbar — heatmap modes */}
      <div className="map-toolbar">
        {[{k:'talentos',l:'Talentos'},{k:'projetos',l:'Projetos'},
          {k:'eventos',l:'Eventos'},{k:'mr',l:'Microrregiões'}].map(t => (
          <div key={t.k} className={`map-tool ${heatmap===t.k?'active':''}`} onClick={()=>setHeatmap(t.k)}>{t.l}</div>
        ))}
      </div>

      {/* top-right info panel when nothing focused */}
      {!focMun && (
        <div className="map-welcome" style={{position:'absolute', top:14, right:14, background:'rgba(255,255,255,.94)',
          backdropFilter:'blur(8px)', border:'1px solid #E2E8F0', borderRadius:12,
          padding:'14px 16px', boxShadow:'0 4px 14px rgba(11,18,32,.08)', maxWidth:280}}>
          <div style={{fontSize:10.5, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase',
            color:'#64748B', marginBottom:6}}>Mapa Regional de Talentos</div>
          <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:16, letterSpacing:'-0.01em', marginBottom:8}}>
            16 municípios · 5 microrregiões
          </div>
          <div style={{fontSize:12.5, color:'#475569', lineHeight:1.5}}>
            Clique em um município para explorar talentos, projetos, mentores e oportunidades. Use a barra superior para alternar entre modos de calor.
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:12, paddingTop:12, borderTop:'1px solid #F1F5F9'}}>
            <div>
              <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:20, letterSpacing:'-0.02em'}}>{window.TALENTOS.length}</div>
              <div style={{fontSize:10.5, color:'#64748B', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>Talentos</div>
            </div>
            <div>
              <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:20, letterSpacing:'-0.02em'}}>{window.PROJETOS_INOV.length}</div>
              <div style={{fontSize:10.5, color:'#64748B', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>Projetos</div>
            </div>
            <div>
              <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:20, letterSpacing:'-0.02em'}}>{(window.MENTORES||[]).length}</div>
              <div style={{fontSize:10.5, color:'#64748B', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>Mentores</div>
            </div>
            <div>
              <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:20, letterSpacing:'-0.02em'}}>{(window.OPORTUNIDADES||[]).length}</div>
              <div style={{fontSize:10.5, color:'#64748B', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>Oportunidades</div>
            </div>
          </div>
        </div>
      )}

      {/* legend */}
      <div className="map-legend">
        <div className="map-legend-h">{({talentos:'Densidade de talentos',projetos:'Densidade de projetos',
          eventos:'Eventos realizados',mr:'Microrregiões'})[heatmap]}</div>
        {heatmap === 'mr' ? Object.entries(window.MR_NAMES).map(([k,n]) => (
          <div key={k} className="map-legend-row">
            <span className="map-legend-dot" style={{background:window.MR_COLORS[k]}}/>
            <span style={{color:'#475569'}}>{n}</span>
          </div>
        )) : <>
          <div style={{display:'flex', alignItems:'center', gap:6, marginTop:4}}>
            <div style={{height:8, width:120, borderRadius:4,
              background:`linear-gradient(90deg, ${window.shade('#0B5FBE',.7)}, #0B5FBE)`}}/>
          </div>
          <div style={{display:'flex', justifyContent:'space-between', fontSize:10, color:'#94A3B8', marginTop:3, width:120}}>
            <span>Menor</span><span>Maior</span>
          </div>
        </>}
      </div>

      {/* CITY POPOVER — segue o filtro superior do mapa */}
      {focMun && <CityPopover
        mun={focMun} pos={popPos}
        heatmap={heatmap}
        filter={filter} setFilter={setFilter}
        talentos={filteredTalents}
        projetos={filteredProjs}
        oportunidades={oportunidadesCity}
        mentores={mentoresCity}
        projFilters={PROJ_FILTERS}
        onSelectTalento={onSelectTalento}
        onClose={() => setFocused(null)}/>}

      {/* Botão flutuante: ver todos os talentos */}
      {!focMun && !allOpen && (
        <button className="map-allbtn" onClick={()=>setAllOpen(true)}
          style={{position:'absolute', bottom:18, right:18, zIndex:6, background:'#0B1220', color:'#fff',
            border:'none', padding:'11px 16px', borderRadius:11, fontFamily:'Outfit', fontWeight:600, fontSize:13.5,
            letterSpacing:'-0.01em', cursor:'pointer', display:'flex', alignItems:'center', gap:10,
            boxShadow:'0 8px 22px rgba(11,18,32,.28)'}}>
          <Icon name="users" size={15}/>
          <span className="map-allbtn-l">Ver todos os {window.TALENTOS.length} talentos</span>
          <span className="map-allbtn-s">{window.TALENTOS.length} talentos</span>
          <span className="map-allbtn-h" style={{opacity:.55, fontSize:11, fontWeight:500, marginLeft:4, paddingLeft:10, borderLeft:'1px solid rgba(255,255,255,.18)'}}>ou afaste o mapa ↗</span>
        </button>
      )}

      {allOpen && <AllTalentosOverlay onClose={()=>setAllOpen(false)} onSelectTalento={onSelectTalento}/>}
    </div>
  </div>;
}

// ============ City popover — segue o heatmap superior ============
function CityPopover({mun, pos, heatmap, filter, setFilter,
  talentos, projetos, oportunidades, mentores,
  projFilters, onSelectTalento, onClose}) {
  const counts = {
    talentos: window.TALENTOS.filter(t=>t.cidade===mun.nome).length,
    projetos: window.PROJETOS_INOV.filter(p=>p.cidade===mun.nome).length,
    mentores: (window.MENTORES||[]).filter(m=>m.cidade===mun.nome).length,
    oportunidades: oportunidades.length,
  };
  const mrColor = window.MR_COLORS[mun.mr];

  // Map heatmap mode -> what to show
  const MODE_LABEL = {talentos:'Talentos', projetos:'Projetos', eventos:'Oportunidades & eventos', mr:'Resumo do município'};
  const mode = heatmap; // 'talentos' | 'projetos' | 'eventos' | 'mr'
  const filters = mode==='projetos' ? projFilters : null;

  return <div className="city-pop" style={{left:pos.left, top:pos.top}} onClick={e=>e.stopPropagation()}>
    <div className="city-pop-h">
      <button className="city-pop-close" onClick={onClose} aria-label="Fechar">✕</button>
      <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:6, flexWrap:'wrap'}}>
        <span className="badge badge-mr"
          style={{background:mrColor+'22', color:window.shade(mrColor,-.25)}}>{mun.mr}</span>
        <span style={{fontSize:11, color:'#64748B'}}>{window.MR_NAMES[mun.mr]}</span>
        {mun.isPolo && <span className="badge" style={{background:'#FEF3C7', color:'#92400E', fontSize:10.5}}>POLO REGIONAL</span>}
      </div>
      <h3>{mun.nome}</h3>
      <div className="meta">{(mun.pop/1000).toFixed(1)}k habitantes · IDH {mun.idh.toFixed(2)} · {mun.empresas} empresas · {mun.setor}</div>
    </div>

    {/* Header da seção atual — reflete o filtro superior do mapa */}
    <div className="city-pop-section">
      <div className="city-pop-section-l">
        <Icon name={mode==='talentos'?'users':mode==='projetos'?'rocket':mode==='eventos'?'trophy':'map'} size={14}/>
        <span>{MODE_LABEL[mode]}</span>
      </div>
      <div className="city-pop-section-c">
        {mode==='talentos' && counts.talentos}
        {mode==='projetos' && counts.projetos}
        {mode==='eventos' && counts.oportunidades}
        {mode==='mr' && '—'}
      </div>
    </div>

    {filters && (
      <div className="city-pop-filters">
        {filters.map(f => (
          <div key={f} className={`city-pop-filter ${filter===f?'active':''}`}
            onClick={()=>setFilter(f)} style={{textTransform:'capitalize'}}>
            {f}
          </div>
        ))}
      </div>
    )}

    <div className="city-pop-list">
      {mode==='talentos' && (talentos.length === 0
        ? <div className="city-pop-empty">Nenhum talento cadastrado.</div>
        : talentos.map((t, idx) => (
          <div key={t.id} className="city-pop-item" onClick={() => onSelectTalento(t.id)}>
            <div style={{fontFamily:'JetBrains Mono', fontWeight:700, fontSize:11, color:'#94A3B8', width:18, textAlign:'right'}}>{idx+1}</div>
            <Avatar name={t.nome} initials={t.avatar} size="sm"/>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontWeight:600, fontSize:13, color:'#0B1220'}}>{t.nome}</div>
              <div style={{fontSize:11.5, color:'#64748B', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{t.curso}</div>
            </div>
            <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:1, minWidth:46}}>
              <div style={{fontFamily:'JetBrains Mono', fontWeight:700, fontSize:13, color:'#0B5FBE'}}>{t.pontos}</div>
              <div style={{fontSize:9.5, color:'#94A3B8', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>pontos</div>
            </div>
          </div>
        )))}

      {mode==='projetos' && (projetos.length === 0
        ? <div className="city-pop-empty">Nenhum projeto neste município{filter!=='todos'?' com este filtro':''}.</div>
        : projetos.map(p => (
          <div key={p.id} className="city-pop-item" style={{flexDirection:'column', alignItems:'flex-start', gap:4}}>
            <div style={{display:'flex', alignItems:'center', gap:8, width:'100%'}}>
              <div style={{width:32, height:32, borderRadius:8, background:'#EBF2FB', color:'#0B5FBE',
                display:'grid', placeItems:'center', flexShrink:0, fontSize:13}}>
                <Icon name="rocket" size={15}/>
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontWeight:600, fontSize:13, color:'#0B1220'}}>{p.nome}</div>
                <div style={{fontSize:11.5, color:'#64748B'}}>{p.fase} · {p.area}</div>
              </div>
              {p.matchScore && <div style={{fontFamily:'JetBrains Mono', fontWeight:700, fontSize:12,
                color:'#0B5FBE', background:'#EBF2FB', padding:'2px 7px', borderRadius:6}}>{p.matchScore}%</div>}
            </div>
            {p.descricao && <div style={{fontSize:11.5, color:'#64748B', paddingLeft:42, lineHeight:1.45}}>{p.descricao}</div>}
          </div>
        )))}

      {mode==='eventos' && (oportunidades.length === 0
        ? <div className="city-pop-empty">Nenhuma oportunidade ativa para este município.</div>
        : oportunidades.map(o => (
          <div key={o.id} className="city-pop-item" style={{flexDirection:'column', alignItems:'flex-start', gap:4}}>
            <div style={{display:'flex', alignItems:'center', gap:8, width:'100%'}}>
              <span className="op-tipo" data-t={o.tipo} style={{margin:0, fontSize:9.5, padding:'2px 7px'}}>{o.tipo}</span>
              <div style={{flex:1, fontWeight:600, fontSize:13, color:'#0B1220'}}>{o.titulo}</div>
              {o.prazo && <div style={{fontSize:11, color:'#64748B'}}>{o.prazo}</div>}
            </div>
            <div style={{fontSize:11.5, color:'#64748B', lineHeight:1.45}}>{o.org}</div>
          </div>
        )))}

      {mode==='mr' && (
        <div style={{padding:'14px 16px'}}>
          <div className="city-pop-stats" style={{borderTop:0, borderBottom:0, padding:0, marginBottom:14}}>
            <div className="city-pop-stat"><div className="v">{counts.talentos}</div><div className="l">Talentos</div></div>
            <div className="city-pop-stat"><div className="v">{counts.projetos}</div><div className="l">Projetos</div></div>
            <div className="city-pop-stat"><div className="v">{counts.mentores}</div><div className="l">Mentores</div></div>
            <div className="city-pop-stat"><div className="v">{counts.oportunidades}</div><div className="l">Edital/eventos</div></div>
          </div>
          <div style={{fontSize:12.5, color:'#475569', lineHeight:1.5}}>
            <strong>{mun.nome}</strong> integra a <strong>{window.MR_NAMES[mun.mr]}</strong>.
            Setor predominante: {mun.setor}. Para explorar talentos, projetos ou oportunidades,
            troque o filtro superior do mapa.
          </div>
        </div>
      )}
    </div>
  </div>;
}

const CLASS_COLOR = {
  'Iniciante':'#94A3B8','Intermediário':'#0E7490','Avançado':'#0B5FBE','Expert':'#7C3AED'
};

// ============ MENTORES ============
function MentoresView() {
  return <div>
    <div className="page-head">
      <div>
        <h2 className="page-title">Mentores</h2>
        <div className="page-sub">{window.MENTORES.length} mentores ativos · {window.CONEXOES.filter(c=>c.tipo==='mentora').length} mentorias em andamento</div>
      </div>
    </div>
    <div className="op-grid">
      {window.MENTORES.map(m => (
        <div key={m.id} className="card" style={{cursor:'pointer'}}>
          <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
            <Avatar name={m.nome} initials={m.avatar} size="lg" color="#F59E0B"/>
            <div style={{flex:1}}>
              <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:15}}>{m.nome}</div>
              <div style={{fontSize:12, color:'#64748B', marginTop:2}}>{m.org} · {m.cidade}</div>
              <div style={{display:'flex', gap:6, marginTop:8, flexWrap:'wrap'}}>
                {m.foco.map(f => <span key={f} className="skill-tag">{f}</span>)}
              </div>
            </div>
          </div>
          <p style={{fontSize:12.5, color:'#475569', marginTop:12, lineHeight:1.5}}>{m.bio}</p>
          <div style={{display:'flex', alignItems:'center', gap:14, marginTop:12, paddingTop:10,
            borderTop:'1px solid #F1F5F9', fontSize:12, color:'#64748B'}}>
            <span><strong style={{color:'#0B1220', fontFamily:'JetBrains Mono'}}>{m.mentorados}</strong> mentorados</span>
            <span><strong style={{color:'#10B981', fontFamily:'JetBrains Mono'}}>{m.slots}</strong> vagas abertas</span>
          </div>
        </div>
      ))}
    </div>
  </div>;
}
window.MentoresView = MentoresView;

// ============ All Talentos Overlay — abre ao "afastar" o mapa ============
function AllTalentosOverlay({onClose, onSelectTalento}) {
  const [q, setQ] = U('');
  const [mr, setMr] = U('todas');
  const [sort, setSort] = U('pontos');

  const list = M(() => {
    let arr = [...window.TALENTOS];
    if (mr !== 'todas') {
      const cidadesMR = window.MUNICIPALITIES.filter(m => m.mr === mr).map(m => m.nome);
      arr = arr.filter(t => cidadesMR.includes(t.cidade));
    }
    if (q.trim()) {
      const s = q.toLowerCase();
      arr = arr.filter(t => t.nome.toLowerCase().includes(s)
        || (t.curso||'').toLowerCase().includes(s)
        || (t.cidade||'').toLowerCase().includes(s)
        || (t.skills||[]).some(k => k.toLowerCase().includes(s)));
    }
    if (sort === 'pontos') arr.sort((a,b) => (b.pontos||0)-(a.pontos||0));
    else if (sort === 'nome') arr.sort((a,b) => a.nome.localeCompare(b.nome));
    else if (sort === 'cidade') arr.sort((a,b) => a.cidade.localeCompare(b.cidade));
    return arr;
  }, [q, mr, sort]);

  E(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  return <div style={{position:'fixed', inset:0, zIndex:50, background:'rgba(11,18,32,.55)', backdropFilter:'blur(8px)',
    animation:'fadeIn .2s ease', display:'flex', flexDirection:'column'}} onClick={onClose}>
    <div onClick={e=>e.stopPropagation()} style={{flex:1, display:'flex', flexDirection:'column',
      margin:'40px auto', maxWidth:1280, width:'calc(100% - 64px)', background:'#fff', borderRadius:18,
      boxShadow:'0 28px 80px rgba(11,18,32,.4)', overflow:'hidden', animation:'popIn .25s cubic-bezier(.2,.8,.3,1.1)'}}>
      <div style={{padding:'20px 28px', borderBottom:'1px solid #F1F5F9', display:'flex', alignItems:'center', gap:18, flexWrap:'wrap'}}>
        <div style={{flex:'1 1 240px'}}>
          <div style={{fontSize:11, color:'#64748B', textTransform:'uppercase', letterSpacing:'.1em', fontWeight:700}}>Visão regional</div>
          <h2 style={{fontFamily:'Outfit', fontWeight:700, fontSize:24, letterSpacing:'-0.02em', margin:'2px 0 0'}}>
            Todos os talentos · <span style={{color:'#0B5FBE'}}>{list.length}</span>
            <span style={{fontWeight:500, fontSize:14, color:'#64748B', marginLeft:8}}>de {window.TALENTOS.length}</span>
          </h2>
        </div>
        <div style={{position:'relative', flex:'1 1 280px', maxWidth:380}}>
          <span style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'#94A3B8'}}><Icon name="search" size={15}/></span>
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Buscar por nome, curso, skill ou cidade…"
            style={{width:'100%', height:42, borderRadius:10, border:'1px solid #E2E8F0', padding:'0 14px 0 38px', fontSize:13, outline:'none', background:'#F8FAFC'}}/>
        </div>
        <button onClick={onClose} style={{width:42, height:42, borderRadius:10, border:'1px solid #E2E8F0', background:'#fff', cursor:'pointer', display:'grid', placeItems:'center', color:'#64748B'}}>✕</button>
      </div>

      <div style={{padding:'14px 28px', borderBottom:'1px solid #F1F5F9', display:'flex', gap:18, flexWrap:'wrap', alignItems:'center'}}>
        <div style={{display:'flex', alignItems:'center', gap:6}}>
          <span style={{fontSize:11.5, color:'#64748B', fontWeight:600, marginRight:4}}>Microrregião:</span>
          {[['todas','Todas'], ...Object.entries(window.MR_NAMES)].map(([k,l]) => (
            <button key={k} onClick={()=>setMr(k)} style={{padding:'6px 11px', borderRadius:7, border:'none', cursor:'pointer',
              background: mr===k ? '#0B5FBE' : '#F1F5F9', color: mr===k ? '#fff' : '#475569',
              fontSize:11.5, fontWeight:600}}>
              {k==='todas' ? l : k}
            </button>
          ))}
        </div>
        <div style={{display:'flex', alignItems:'center', gap:6, marginLeft:'auto'}}>
          <span style={{fontSize:11.5, color:'#64748B', fontWeight:600}}>Ordenar:</span>
          {[['pontos','Pontos'],['nome','Nome'],['cidade','Cidade']].map(([k,l]) => (
            <button key={k} onClick={()=>setSort(k)} style={{padding:'6px 11px', borderRadius:7, border:'none', cursor:'pointer',
              background: sort===k ? '#0B1220' : '#F1F5F9', color: sort===k ? '#fff' : '#475569',
              fontSize:11.5, fontWeight:600}}>{l}</button>
          ))}
        </div>
      </div>

      <div style={{flex:1, overflow:'auto', padding:24, background:'#F8FAFC'}}>
        <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:14}}>
          {list.map(t => (
            <div key={t.id} onClick={()=>{ onSelectTalento(t.id); onClose(); }}
              style={{background:'#fff', borderRadius:12, padding:16, border:'1px solid #E2E8F0', cursor:'pointer',
                transition:'transform .12s, box-shadow .12s', display:'flex', flexDirection:'column', gap:10}}
              onMouseEnter={e=>{e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 10px 24px rgba(11,18,32,.08)';}}
              onMouseLeave={e=>{e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow='';}}>
              <div style={{display:'flex', gap:10, alignItems:'center'}}>
                <Avatar name={t.nome} initials={t.avatar} size="md"/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontFamily:'Outfit', fontWeight:600, fontSize:14, letterSpacing:'-0.01em'}}>{t.nome}</div>
                  <div style={{fontSize:11.5, color:'#64748B', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{t.curso}</div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div style={{fontFamily:'JetBrains Mono', fontWeight:700, fontSize:14, color:'#0B5FBE'}}>{t.pontos}</div>
                  <div style={{fontSize:9.5, color:'#94A3B8', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:600}}>pts</div>
                </div>
              </div>
              <div style={{display:'flex', gap:5, flexWrap:'wrap'}}>
                {(t.skills||[]).slice(0,3).map(s => <span key={s} className="skill-tag" style={{fontSize:10.5, padding:'2px 7px'}}>{s}</span>)}
              </div>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', paddingTop:8, borderTop:'1px solid #F1F5F9', fontSize:11, color:'#64748B'}}>
                <span>{t.cidade}</span>
                <span style={{display:'inline-flex', alignItems:'center', gap:4, color: CLASS_COLOR[t.classificacao] || '#475569', fontWeight:600}}>
                  <span style={{width:6, height:6, borderRadius:'50%', background:'currentColor'}}/>
                  {t.classificacao}
                </span>
              </div>
            </div>
          ))}
          {list.length === 0 && (
            <div style={{gridColumn:'1/-1', padding:60, textAlign:'center', color:'#94A3B8'}}>Nenhum talento encontrado.</div>
          )}
        </div>
      </div>
    </div>
  </div>;
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
