// ============================================================
// Página: Alunos
// ============================================================
function PageAlunos({ alunos, setAlunos, openAlunoId, setOpenAlunoId }) {
  const [filtro, setFiltro] = useState("Todos");
  const [search, setSearch] = useState("");
  const [showNew, setShowNew] = useState(false);

  useEffect(()=>{
    const h = ()=>setShowNew(true);
    window.addEventListener("iuvenis:newAluno", h);
    return ()=>window.removeEventListener("iuvenis:newAluno", h);
  },[]);

  const statuses = ["Todos","Ativo","Aguardando","Pausado"];
  const counts = {
    Todos: alunos.length,
    Ativo: alunos.filter(a=>a.status==="Ativo").length,
    Aguardando: alunos.filter(a=>a.status==="Aguardando").length,
    Pausado: alunos.filter(a=>a.status==="Pausado").length,
  };

  const filtered = alunos.filter(a => {
    if (filtro !== "Todos" && a.status !== filtro) return false;
    if (search && !(a.nome+a.email+a.pais+a.programa).toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  }).map(a => ({ ...a, score: healthScore(a) }));

  const aluno = openAlunoId ? alunos.find(a=>a.id===openAlunoId) : null;
  const mrr = alunos.filter(a=>a.status==="Ativo").reduce((s,a)=>s+a.mensalidade,0);
  const emRiscoCount = alunos.filter(a => healthScore(a) < 55).length;

  // Distribuição por país (mantido pra cmd-K context)
  const byCountry = {};
  alunos.forEach(a=>{ byCountry[a.pais] = (byCountry[a.pais]||0)+1; });

  return (
    <div className="flex-col gap-4">
      <div className="grid g-4">
        <StatCard label="Alunos totais" value={alunos.length} delta={6.7}/>
        <StatCard label="Ativos"        value={counts.Ativo} delta={4.0} accent="var(--success)"/>
        <StatCard label="MRR estimado"  value={fmtBRL(mrr)} delta={8.4} accent="var(--brand-accent)"/>
        <StatCard label="Em risco"      value={emRiscoCount} delta={-12.0} accent="var(--danger)"/>
      </div>

      <div className="grid g-2-1">
        <div className="card" style={{ padding:0 }}>
          <div style={{ padding:"16px 20px", borderBottom:"1px solid var(--border)", display:"flex", alignItems:"center", justifyContent:"space-between", gap:12, flexWrap:"wrap" }}>
            <div className="pill-group">
              {statuses.map(s => (
                <button key={s} className={"pill " + (filtro===s?"active":"")} onClick={()=>setFiltro(s)}>
                  {s} <span style={{ marginLeft:4, opacity:0.6 }}>{counts[s]}</span>
                </button>
              ))}
            </div>
            <div className="row gap-2">
              <div className="row gap-2" style={{ background:"var(--surface-2)", border:"1px solid var(--border)", padding:"6px 10px", borderRadius:8, fontSize:13 }}>
                <I.search size={14} className="text-3"/>
                <input style={{ background:"transparent", border:"none", outline:"none", width:160 }} placeholder="Buscar…" value={search} onChange={e=>setSearch(e.target.value)}/>
              </div>
              <button className="btn btn-primary" onClick={()=>setShowNew(true)}><I.plus size={14}/> Novo aluno</button>
            </div>
          </div>
          <table className="dt">
            <thead><tr>
              <th>Aluno</th><th>País / Programa</th><th>Etapa</th><th>Plano</th><th style={{ width:120 }}>Progresso</th><th style={{ width:100 }}>Health</th><th className="num" style={{ textAlign:"right" }}>Mensal.</th>
            </tr></thead>
            <tbody>
              {filtered.map(a => (
                <tr key={a.id} className="clickable" onClick={()=>setOpenAlunoId(a.id)}>
                  <td>
                    <div className="row gap-2">
                      <Avatar name={a.nome}/>
                      <div>
                        <div style={{ fontWeight:500 }}>{a.nome}</div>
                        <div className="text-3" style={{ fontSize:11.5 }}>{a.email}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div style={{ fontWeight:500 }}>{a.pais}</div>
                    <div className="text-3" style={{ fontSize:11.5 }}>{a.programa}</div>
                  </td>
                  <td><span className="tag">{a.etapa}</span></td>
                  <td>
                    <span className={"tag " + (a.plano==="Premium"?"brand":"")}>{a.plano}</span>
                  </td>
                  <td>
                    <div className="row gap-2">
                      <div className="bar" style={{ flex:1 }}><i style={{ width:a.progresso+"%", background: a.progresso>80?"var(--success)": a.progresso<30?"var(--warn)":"var(--brand)" }}/></div>
                      <span className="num text-3" style={{ fontSize:11, minWidth:28 }}>{a.progresso}%</span>
                    </div>
                  </td>
                  <td>
                    <div className="row gap-2">
                      <span style={{ width:8, height:8, borderRadius:50, background: a.score>=75?"var(--success)": a.score>=55?"var(--brand-accent)": a.score>=40?"var(--warn)":"var(--danger)" }}></span>
                      <span className="num" style={{ fontSize:12.5, fontWeight:600, color: a.score<55?"var(--danger)":"var(--text)" }}>{a.score}</span>
                    </div>
                  </td>
                  <td className="num" style={{ textAlign:"right" }}>{fmtBRL(a.mensalidade)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="flex-col gap-4">
          <div className="card">
            <div className="card-h"><div className="card-title">Alunos no mundo</div><div className="card-sub">{alunos.length} ativos em {Object.keys(alunos.reduce((m,a)=>(m[a.pais]=1,m),{})).length} países</div></div>
            <WorldMapMini/>
          </div>

          <div className="card">
            <div className="card-h"><div className="card-title">Aprovação de visto</div><div className="card-sub">Taxa de sucesso por país</div></div>
            <div className="flex-col gap-3">
              {DX.vistos.map(v=>(
                <div key={v.pais}>
                  <div className="row gap-2" style={{ justifyContent:"space-between", fontSize:13 }}>
                    <span style={{ fontWeight:500 }}>{v.pais}</span>
                    <div className="row gap-2">
                      <span className="num" style={{ fontWeight:600, color: v.taxa>=95?"var(--success)":"var(--text)" }}>{v.taxa}%</span>
                      <span className="text-3 num" style={{ fontSize:11 }}>· {v.total}</span>
                    </div>
                  </div>
                  <div className="bar mt-2"><i style={{ width:v.taxa+"%", background: v.taxa>=95?"var(--success)":"var(--brand)" }}/></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {aluno && <ModalAluno aluno={aluno} onClose={()=>setOpenAlunoId(null)}/>}
      {showNew && <ModalNovoAluno onClose={()=>setShowNew(false)} onSave={(a)=>{ setAlunos(prev=>[a,...prev]); setShowNew(false); }}/>}
    </div>
  );
}

function ModalAluno({ aluno, onClose }) {
  return (
    <Modal title={aluno.nome} sub={aluno.email + " · " + aluno.programa + " · " + aluno.pais}
      onClose={onClose} wide
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Fechar</button>
        <button className="btn">Enviar mensagem</button>
        <button className="btn btn-primary">Abrir prontuário <I.ext size={12}/></button>
      </>}>
      <div className="grid g-3 mb-4">
        <div><div className="stat-label">Status</div><span className={"tag " + (aluno.status==="Ativo"?"success": aluno.status==="Pausado"?"warn":"")}>{aluno.status}</span></div>
        <div><div className="stat-label">Plano</div><span className={"tag " + (aluno.plano==="Premium"?"brand":"")}>{aluno.plano}</span></div>
        <div><div className="stat-label">Mensalidade</div><div className="num" style={{ fontWeight:500 }}>{fmtBRL(aluno.mensalidade)}</div></div>
      </div>

      <div className="mb-4">
        <div className="stat-label">Progresso da jornada</div>
        <div className="row gap-3 mt-2">
          <div className="bar" style={{ flex:1, height:10 }}><i style={{ width:aluno.progresso+"%" }}/></div>
          <span className="num" style={{ fontWeight:600 }}>{aluno.progresso}%</span>
        </div>
        <div className="row gap-2 mt-2" style={{ fontSize:12, color:"var(--text-3)", justifyContent:"space-between" }}>
          {["Onboarding","Documentação","Visto","Pré-embarque","Embarcado"].map(s=>(
            <div key={s} className="row gap-2"><span style={{ width:6, height:6, borderRadius:50, background: s===aluno.etapa?"var(--brand)":"var(--border-strong)" }}></span>{s}</div>
          ))}
        </div>
      </div>

      <div className="grid g-2">
        <div>
          <div className="stat-label">Última atividade</div>
          <ul style={{ paddingLeft:18, fontSize:13, lineHeight:1.7, margin:"6px 0 0", color:"var(--text-2)" }}>
            <li>Concluiu módulo <strong>Documentação</strong> · há 2 dias</li>
            <li>Mensagem no WhatsApp · há 4 dias</li>
            <li>Aula assistida: "Carta de motivação" · há 5 dias</li>
            <li>Pagamento mensalidade confirmado · 15/05</li>
          </ul>
        </div>
        <div>
          <div className="stat-label">Próximos passos</div>
          <ul style={{ paddingLeft:18, fontSize:13, lineHeight:1.7, margin:"6px 0 0", color:"var(--text-2)" }}>
            <li>Agendar entrevista de visto</li>
            <li>Enviar comprovante de matrícula da escola</li>
            <li>Validar seguro saúde internacional</li>
            <li>Call de mentoria · 02/06 às 19h</li>
          </ul>
        </div>
      </div>
    </Modal>
  );
}

function ModalNovoAluno({ onClose, onSave }) {
  const [form, setForm] = useState({ nome:"", email:"", pais:"Canadá", programa:"Working Holiday", plano:"Premium" });
  const submit = () => {
    if (!form.nome || !form.email) return;
    onSave({
      id: "A" + (Math.floor(Math.random()*99)+17),
      ...form,
      status:"Aguardando", etapa:"Onboarding",
      entrada: new Date().toISOString().slice(0,10),
      progresso: 0, mensalidade: form.plano==="Premium"?1490:990,
    });
  };
  return (
    <Modal title="Adicionar novo aluno" sub="Cadastrar aluno e iniciar onboarding" onClose={onClose}
      footer={<>
        <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
        <button className="btn btn-primary" onClick={submit}>Salvar aluno</button>
      </>}>
      <div className="grid g-2 gap-3">
        <div className="form-row"><label className="form-label">Nome completo</label><input className="input" value={form.nome} onChange={e=>setForm({...form, nome:e.target.value})}/></div>
        <div className="form-row"><label className="form-label">E-mail</label><input className="input" value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></div>
        <div className="form-row"><label className="form-label">País destino</label>
          <select className="select" value={form.pais} onChange={e=>setForm({...form, pais:e.target.value})}>
            {["Canadá","Irlanda","Austrália","Reino Unido","EUA","Portugal","Espanha","Malta","França","Alemanha","Nova Zelândia"].map(p=><option key={p}>{p}</option>)}
          </select>
        </div>
        <div className="form-row"><label className="form-label">Programa</label>
          <select className="select" value={form.programa} onChange={e=>setForm({...form, programa:e.target.value})}>
            {["Working Holiday","Inglês 3m","Inglês 6m","Inglês 9m","Student Visa","Mestrado","Au Pair","Intercâmbio HS"].map(p=><option key={p}>{p}</option>)}
          </select>
        </div>
        <div className="form-row" style={{ gridColumn:"1 / -1" }}>
          <label className="form-label">Plano</label>
          <div className="pill-group">
            {["Premium","Mentoria"].map(p=>(
              <button key={p} className={"pill " + (form.plano===p?"active":"")} onClick={()=>setForm({...form, plano:p})}>{p} · {p==="Premium"?"R$ 1.490":"R$ 990"}</button>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { PageAlunos });

// ============================================================
// World Map (mini) — stylized continents + student dots
// ============================================================
function WorldMapMini() {
  // Simplified abstract continent shapes — not geographically precise
  const continents = "M60 80 Q90 70 130 75 L180 90 Q200 110 195 145 L160 200 Q120 215 90 195 Q55 175 50 130 Q48 100 60 80 Z " + // Americas (left blob)
                     "M310 80 Q360 70 410 80 L450 100 Q460 130 445 160 L400 175 Q360 165 330 155 Q305 135 305 110 Q305 90 310 80 Z " + // Europe/Africa
                     "M470 95 Q540 80 600 90 L650 110 Q665 145 645 175 L580 195 Q510 185 470 165 Q455 135 470 95 Z " + // Asia
                     "M600 270 Q660 260 700 280 L720 305 Q715 335 685 345 L630 340 Q605 320 600 295 Q598 280 600 270 Z";    // Oceania

  return (
    <svg viewBox="0 0 800 380" width="100%" style={{ display:"block" }}>
      <path d={continents} fill="var(--surface-3)" opacity="0.85"/>
      {DX.mapaAlunos.map((p,i)=>{
        // Scale coords to fit viewBox
        const x = p.cx; const y = p.cy;
        const r = 6 + Math.sqrt(p.n) * 4;
        return (
          <g key={i}>
            <circle cx={x} cy={y} r={r+4} fill="var(--brand-accent)" opacity="0.18">
              <animate attributeName="r" values={`${r+4};${r+10};${r+4}`} dur="2.4s" repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0.18;0.05;0.18" dur="2.4s" repeatCount="indefinite"/>
            </circle>
            <circle cx={x} cy={y} r={r} fill="var(--brand)" stroke="white" strokeWidth="2"/>
            <text x={x} y={y+3.5} textAnchor="middle" fontSize="10.5" fill="white" fontWeight="700" fontFamily="var(--font-mono)">{p.n}</text>
            <text x={x} y={y+r+13} textAnchor="middle" fontSize="9" fill="var(--text-3)" fontFamily="var(--font-mono)">{p.pais}</text>
          </g>
        );
      })}
    </svg>
  );
}
