/* global React */
const { useState: useS, useMemo: useM } = React;
const { Icon, Avatar, Selo, ClassifPill, Sparkline, Radar, Trail, BarRow, shade } = window;

// ============ Network Graph ============
function NetworkGraph({focusedId, onSelect}) {
  const W = 980, H = 600;
  const data = useM(() => buildGraph(focusedId), [focusedId]);

  return (
    <div className="network-shell">
      <svg viewBox={`0 0 ${W} ${H}`} className="network-svg" preserveAspectRatio="xMidYMid meet">
        <defs>
          <radialGradient id="netGlow"><stop offset="0%" stopColor="#0B5FBE" stopOpacity=".22"/>
            <stop offset="100%" stopColor="#0B5FBE" stopOpacity="0"/></radialGradient>
        </defs>
        {/* edges */}
        {data.edges.map((e, i) => (
          <line key={i} x1={e.x1} y1={e.y1} x2={e.x2} y2={e.y2}
            stroke={e.color} strokeWidth={e.weight}
            strokeOpacity=".55" strokeLinecap="round"/>
        ))}
        {/* nodes */}
        {data.nodes.map(n => (
          <g key={n.id} className="net-node" transform={`translate(${n.x}, ${n.y})`}
            onClick={() => onSelect && onSelect(n.id)}>
            {n.glow && <circle r={n.r+18} fill="url(#netGlow)"/>}
            <circle r={n.r} fill={n.color} stroke="#fff" strokeWidth="2.5"/>
            {n.r > 14 && <text dy="0.5" fontSize={n.r > 22 ? 10 : 8.5}>{n.label}</text>}
          </g>
        ))}
        {/* node labels (outside) */}
        {data.nodes.filter(n=>n.outLabel).map(n => (
          <text key={'l-'+n.id} x={n.x} y={n.y + n.r + 14} textAnchor="middle"
            fontSize="10.5" fontFamily="DM Sans" fontWeight="600" fill="#334155">{n.outLabel}</text>
        ))}
      </svg>
      <div className="net-legend">
        <h4>Tipos de nó</h4>
        <div className="row"><span className="dot" style={{background:'#0B5FBE'}}/>Talento</div>
        <div className="row"><span className="dot" style={{background:'#7C3AED'}}/>Projeto / Startup</div>
        <div className="row"><span className="dot" style={{background:'#F59E0B'}}/>Mentor</div>
        <div className="row"><span className="dot" style={{background:'#10B981'}}/>Empresa / Demanda</div>
      </div>
      <div className="net-info">
        <div style={{fontSize:11, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', color:'#64748B'}}>Rede ativa</div>
        <div style={{fontFamily:'Outfit', fontSize:18, fontWeight:600, marginTop:4, lineHeight:1.2}}>
          {data.nodes.length} nós · {data.edges.length} conexões
        </div>
        <div style={{fontSize:12, color:'#475569', marginTop:6, lineHeight:1.5}}>
          Clique em um nó para ver suas conexões. Linhas mais grossas = mais interações.
        </div>
      </div>
    </div>
  );
}

function buildGraph(focusedId) {
  const W = 980, H = 600, cx = W/2, cy = H/2;
  // Project hubs in inner orbit
  const projetos = window.PROJETOS_INOV.slice(0, 10);
  const mentores = window.MENTORES.slice(0, 6);
  const empresas = window.EMPRESAS.slice(0, 6);
  const talentos = window.TALENTOS;

  const nodes = [];

  // Place projects in inner orbit
  projetos.forEach((p, i) => {
    const a = (i / projetos.length) * Math.PI * 2 - Math.PI/2;
    const r = 130;
    nodes.push({
      id: p.id, type:'projeto', x: cx + r*Math.cos(a), y: cy + r*Math.sin(a),
      r: 22, color:'#7C3AED', label: p.nome.split(' ')[0].slice(0,4).toUpperCase(),
      outLabel: p.nome.length < 18 ? p.nome : p.nome.split(' ')[0]
    });
  });

  // Place mentors in mid orbit
  mentores.forEach((m, i) => {
    const a = (i / mentores.length) * Math.PI * 2;
    const r = 230;
    nodes.push({
      id: m.id, type:'mentor', x: cx + r*Math.cos(a), y: cy + r*Math.sin(a),
      r: 18, color:'#F59E0B', label: m.avatar
    });
  });

  // Place companies in outer orbit (right side)
  empresas.forEach((e, i) => {
    const a = -Math.PI/2 + Math.PI/3 + (i/empresas.length) * Math.PI * 1.4;
    const r = 285;
    nodes.push({
      id: e.id, type:'empresa', x: cx + r*Math.cos(a), y: cy + r*Math.sin(a),
      r: 16, color:'#10B981', label: e.nome.slice(0,3).toUpperCase()
    });
  });

  // Place talents in outer orbit
  talentos.slice(0, 18).forEach((t, i) => {
    const a = -Math.PI/2 + (i / 18) * Math.PI * 2;
    const r = 270 + (i % 3) * 14;
    nodes.push({
      id: t.id, type:'talento', x: cx + r*Math.cos(a), y: cy + r*Math.sin(a),
      r: 14, color:'#0B5FBE', label: t.avatar
    });
  });

  // Build edges from CONEXOES
  const nodeMap = {};
  nodes.forEach(n => nodeMap[n.id] = n);
  const edges = [];

  window.CONEXOES.forEach(c => {
    const a = nodeMap[c.a], b = nodeMap[c.b];
    if (!a || !b) return;
    edges.push({
      x1:a.x, y1:a.y, x2:b.x, y2:b.y,
      color: c.tipo==='mentora' ? '#F59E0B' : c.tipo==='demanda' ? '#10B981' : '#0B5FBE',
      weight: 1.5
    });
  });

  // Highlight focused
  if (focusedId && nodeMap[focusedId]) {
    nodeMap[focusedId].glow = true;
    nodeMap[focusedId].r += 4;
  }

  return {nodes, edges};
}
window.NetworkGraph = NetworkGraph;

// ============ Talent card ============
function TalentCard({t, onClick}) {
  const setor = window.SETORES_INOV.find(s => s.id === t.interesses[0]);
  return (
    <div className="talent-card" onClick={onClick}>
      <div className="talent-head">
        <Avatar name={t.nome} initials={t.avatar} size="md"/>
        <div style={{flex:1, minWidth:0}}>
          <div className="talent-name">{t.nome}</div>
          <div className="talent-meta">{t.cidade} · {t.curso}</div>
          <div style={{marginTop:4}}><span className="badge badge-mr"
            style={{background:window.MR_COLORS[t.mr]+'22',
              color:shade(window.MR_COLORS[t.mr],-.25)}}>{t.mr}</span></div>
        </div>
      </div>
      <div className="talent-resumo">{t.resumo}</div>
      <div className="talent-selos">
        {t.selos.slice(0,4).map(id => <Selo key={id} id={id}/>)}
        {t.selos.length > 4 && <span className="selo">+{t.selos.length-4}</span>}
      </div>
      <div className="talent-foot">
        <ClassifPill id={t.classificacao}/>
        <span className="pontos"><strong>{t.pontos}</strong> pts</span>
      </div>
    </div>
  );
}
window.TalentCard = TalentCard;

// ============ Talent detail panel ============
function TalentDetail({talentId, onClose, onOpenProjeto}) {
  const t = window.findTalento(talentId);
  if (!t) return null;
  const projeto = t.projetoAtivo ? window.findProjeto(t.projetoAtivo) : null;
  const setor = window.SETORES_INOV.find(s => s.id === t.interesses[0]);
  const color = setor ? setor.cor : '#0B5FBE';

  return <>
    <div className="detail-overlay" onClick={onClose}/>
    <div className="detail-panel">
      <button className="detail-close" onClick={onClose}>✕</button>
      <div className="detail-hero">
        <div style={{display:'flex', gap:18, alignItems:'flex-start'}}>
          <Avatar name={t.nome} initials={t.avatar} size="xl"/>
          <div style={{flex:1, paddingTop:6}}>
            <div style={{display:'flex', gap:6, marginBottom:6}}>
              <span className="badge badge-mr" style={{background:window.MR_COLORS[t.mr]+'22',
                color:shade(window.MR_COLORS[t.mr],-.25)}}>{t.mr} · {t.cidade}</span>
              <ClassifPill id={t.classificacao}/>
            </div>
            <h2 style={{fontSize:26, fontFamily:'Outfit'}}>{t.nome}</h2>
            <div style={{color:'#64748B', marginTop:4, fontSize:13.5}}>
              {t.curso} · {t.instituicao} · {t.idade} anos
            </div>
            <div style={{marginTop:14, display:'flex', gap:8}}>
              <button className="btn btn-primary"><Icon name="msg" size={14}/> Entrar em contato</button>
              <button className="btn btn-ghost"><Icon name="plus" size={14}/> Conectar a projeto</button>
            </div>
          </div>
        </div>
      </div>
      <div className="detail-body">
        <div className="detail-section">
          <h4>Trilha de evolução · {t.pontos} pontos</h4>
          <Trail points={t.pontos}/>
        </div>
        <div className="detail-section">
          <h4>5 dimensões do talento</h4>
          <Radar dim={t.dim} size={240} color={color}/>
        </div>
        <div className="detail-section">
          <h4>Selos conquistados ({t.selos.length})</h4>
          <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
            {t.selos.map(id => <Selo key={id} id={id}/>)}
          </div>
        </div>
        <div className="detail-section">
          <h4>Resumo</h4>
          <p style={{fontSize:13.5, color:'#334155', lineHeight:1.6}}>{t.resumo}</p>
        </div>
        <div className="detail-section">
          <h4>Habilidades</h4>
          <div style={{display:'flex', flexWrap:'wrap', gap:5}}>
            {t.habilidades.map(h => <span key={h} className="skill-tag">{h}</span>)}
          </div>
        </div>
        {(() => {
          const cv = window.getCV ? window.getCV(t) : null;
          if (!cv) return null;
          return <>
            <div className="detail-section">
              <h4>Formação acadêmica</h4>
              <div className="cv-list">
                {cv.formacao.map((f, i) => (
                  <div key={i} className="cv-item">
                    <div className="cv-icon" style={{background:'#EBF2FB', color:'#0B5FBE'}}>
                      <Icon name="book" size={14}/>
                    </div>
                    <div style={{flex:1, minWidth:0}}>
                      <div className="cv-title">{f.curso}</div>
                      <div className="cv-org">{f.instituicao} · {f.cidade}</div>
                      {f.detalhe && <div className="cv-desc">{f.detalhe}</div>}
                    </div>
                    <div className="cv-side">
                      <div>{f.inicio} – {f.fim || 'atual'}</div>
                      <span className={`cv-status ${f.status==='Concluído'?'done':'cur'}`}>{f.status}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="detail-section">
              <h4>Experiência profissional ({cv.experiencia.length})</h4>
              {cv.experiencia.length === 0
                ? <div style={{fontSize:13, color:'#94A3B8', fontStyle:'italic'}}>Sem experiência profissional registrada — talento em formação inicial.</div>
                : <div className="cv-list">
                  {cv.experiencia.map((e, i) => (
                    <div key={i} className="cv-item">
                      <div className="cv-icon" style={{background:e.atual?'#D1FAE5':'#F1F5F9', color:e.atual?'#065F46':'#475569'}}>
                        <Icon name="briefcase" size={14}/>
                      </div>
                      <div style={{flex:1, minWidth:0}}>
                        <div className="cv-title">{e.cargo}</div>
                        <div className="cv-org">{e.empresa} · {e.cidade}</div>
                        <div className="cv-desc">{e.descricao}</div>
                      </div>
                      <div className="cv-side">
                        <div>{e.inicio} – {e.atual ? 'atual' : e.fim}</div>
                        <span className="cv-tipo">{e.tipo}</span>
                      </div>
                    </div>
                  ))}
                </div>}
            </div>
            <div className="detail-section">
              <h4>Cursos & certificações</h4>
              <div style={{display:'flex', flexDirection:'column', gap:6}}>
                {cv.cursos.map((c, i) => (
                  <div key={i} style={{display:'flex', alignItems:'center', gap:10, padding:'7px 10px',
                    background:'#F8FAFC', borderRadius:8, fontSize:12.5}}>
                    <Icon name="trophy" size={13}/>
                    <span style={{flex:1, fontWeight:500, color:'#334155'}}>{c.nome}</span>
                    <span style={{color:'#64748B', fontFamily:'JetBrains Mono', fontSize:11.5}}>{c.horas}h</span>
                    <span style={{color:'#94A3B8', fontFamily:'JetBrains Mono', fontSize:11.5}}>{c.ano}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="detail-section">
              <h4>Idiomas</h4>
              <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                {cv.idiomas.map((id, i) => (
                  <span key={i} className="skill-tag">
                    <strong style={{marginRight:4}}>{id.nome}</strong>{id.nivel}
                  </span>
                ))}
              </div>
            </div>
          </>;
        })()}
        <div className="detail-section">
          <h4>Histórico de inovação</h4>
          <div className="tl">
            {t.historico.map((h, i) => (
              <div key={i} className="tl-item">
                <div className="tl-dot"/>
                <div>
                  <div className="tl-tipo">{h.tipo}</div>
                  <div className="tl-titulo">{h.titulo}</div>
                  <div className="tl-resultado">{h.resultado}</div>
                </div>
                <div className="tl-side">{h.ano} · +{h.pontos}</div>
              </div>
            ))}
          </div>
        </div>
        {projeto && (
          <div className="detail-section">
            <h4>Projeto ativo</h4>
            <div className="card" style={{cursor:'pointer'}} onClick={() => onOpenProjeto(projeto.id)}>
              <div style={{display:'flex', alignItems:'center', gap:10}}>
                <div style={{width:38, height:38, borderRadius:8, background:color+'22',
                  display:'grid', placeItems:'center', color:shade(color,-.25), fontWeight:700, fontFamily:'Outfit'}}>
                  {projeto.nome.slice(0,2).toUpperCase()}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontWeight:600}}>{projeto.nome}</div>
                  <div style={{fontSize:12, color:'#64748B'}}>{projeto.fase} · {projeto.cidade}</div>
                </div>
                <Icon name="arrowRight" size={16}/>
              </div>
            </div>
          </div>
        )}
        {t.necessidades.length > 0 && (
          <div className="detail-section">
            <h4>O que está buscando</h4>
            <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
              {t.necessidades.map(n => (
                <span key={n} style={{padding:'5px 10px', background:'#FEF3C7', color:'#92400E',
                  borderRadius:8, fontSize:12, fontWeight:500}}>
                  <span style={{marginRight:5}}>◆</span>{n}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  </>;
}
window.TalentDetail = TalentDetail;

// ============ Project card ============
function ProjectCard({p, onClick}) {
  const setor = window.SETORES_INOV.find(s => s.id === p.setor);
  return (
    <div className="card" style={{cursor:'pointer'}} onClick={onClick}>
      <div style={{display:'flex', alignItems:'flex-start', gap:12, marginBottom:10}}>
        <div style={{width:44, height:44, borderRadius:10, background:setor.cor+'22',
          display:'grid', placeItems:'center', color:shade(setor.cor,-.25), fontWeight:700,
          fontFamily:'Outfit', fontSize:14, flexShrink:0}}>
          {p.nome.slice(0,2).toUpperCase()}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontWeight:600, fontSize:14.5, fontFamily:'Outfit'}}>{p.nome}</div>
          <div style={{fontSize:12, color:'#64748B', marginTop:2}}>
            {setor.nome} · {p.cidade}
          </div>
        </div>
      </div>
      <div style={{fontSize:12.5, color:'#334155', lineHeight:1.5,
        display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden'}}>
        {p.problema}
      </div>
      <div style={{display:'flex', alignItems:'center', gap:8, marginTop:12, paddingTop:10,
        borderTop:'1px solid #F1F5F9'}}>
        <span className="badge" style={{background:setor.cor+'18', color:shade(setor.cor,-.25)}}>
          {p.fase}
        </span>
        <div style={{display:'flex', marginLeft:'auto', gap:-6}}>
          {p.equipe.slice(0,3).map((tid, i) => {
            const t = window.findTalento(tid);
            if (!t) return null;
            return <div key={tid} style={{marginLeft: i ? -8 : 0, border:'2px solid #fff', borderRadius:'50%'}}>
              <Avatar name={t.nome} initials={t.avatar} size="sm"/>
            </div>;
          })}
        </div>
      </div>
    </div>
  );
}
window.ProjectCard = ProjectCard;

// ============ Opportunity card ============
function OpCard({o, onClick}) {
  const pct = o.vagas > 0 ? Math.min(100, (o.inscritos/o.vagas)*100) : 0;
  return (
    <div className="op-card" onClick={onClick}>
      <span className="op-tipo" data-t={o.tipo}>{o.tipo}</span>
      <h4>{o.nome}</h4>
      <div className="op-meta">
        <span><Icon name="calendar" size={12}/> {o.data}</span>
        <span><Icon name="map" size={12}/> {o.cidade}</span>
      </div>
      <div className="op-desc">{o.descricao}</div>
      <div style={{marginTop:12, display:'flex', alignItems:'center', gap:8}}>
        <Icon name="trophy" size={13} stroke={2}/>
        <span style={{fontSize:12.5, color:'#334155', fontWeight:500}}>{o.premio}</span>
      </div>
      {o.vagas > 0 && <>
        <div className="op-bar"><i style={{width:pct+'%'}}/></div>
        <div className="op-stats">
          <span><strong>{o.inscritos}</strong> inscritos · <strong>{o.vagas}</strong> vagas</span>
          <span><strong>{o.dias_restantes}</strong> dias</span>
        </div>
      </>}
    </div>
  );
}
window.OpCard = OpCard;

// ============ Match feed card ============
function MatchCard({m, onSelect}) {
  const tipoLabel = {
    'projeto-talento':'Projeto ↔ Talento',
    'projeto-mentor':'Projeto ↔ Mentor',
    'empresa-talento':'Empresa ↔ Talento',
    'oportunidade-talento':'Oportunidade ↔ Talento',
    'oportunidade-projeto':'Oportunidade ↔ Projeto',
  };
  const resolveA = (id) => {
    if (id.startsWith('p')) return window.findProjeto(id);
    if (id.startsWith('t')) return window.findTalento(id);
    if (id.startsWith('m')) return window.findMentor(id);
    if (id.startsWith('e')) return window.findEmpresa(id);
    if (id.startsWith('o')) return window.findOpor(id);
  };
  const a = resolveA(m.a), b = resolveA(m.b);
  if (!a || !b) return null;
  const aLabel = a.nome, bLabel = b.nome;
  const aMeta = a.cidade + (a.fase ? ' · ' + a.fase : (a.curso ? ' · ' + a.curso : ''));
  const bMeta = b.cidade + (b.fase ? ' · ' + b.fase : (b.curso ? ' · ' + b.curso : ''));

  return (
    <div className="match-card" onClick={() => onSelect && onSelect(m)}>
      <div className="accent"/>
      <div>
        <span className="mc-tag"><Icon name="spark" size={11}/>{tipoLabel[m.tipo]}</span>
        <div className="mc-pair">
          <div>
            <div className="mc-name">{aLabel}</div>
            <div className="mc-meta">{aMeta}</div>
          </div>
          <div className="mc-pair-arrow"><Icon name="arrowRight" size={11}/></div>
          <div>
            <div className="mc-name">{bLabel}</div>
            <div className="mc-meta">{bMeta}</div>
          </div>
        </div>
        <div className="mc-reason">{m.razao}</div>
      </div>
      <div className="mc-actions">
        <div style={{textAlign:'right'}}>
          <div className="mc-score">{m.score}<span style={{fontSize:13, color:'#94A3B8', fontWeight:500}}>%</span></div>
          <div className="mc-score-lbl">match</div>
        </div>
        <button className="btn btn-primary btn-sm">Aprovar match</button>
      </div>
    </div>
  );
}
window.MatchCard = MatchCard;
