/* Painel Admin — todas as telas */

function AdminDashboard({ onNavigate }) {
  const M = FC_METRICAS;
  return (
    <div className="fc-stack fc-gap-6">
      <div>
        <div className="fc-h1">Painel Admin</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>
          Bom dia, professor. Aqui está o retrato da plataforma nos últimos 30 dias.
        </div>
      </div>

      {/* KPI cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
        <KpiCard label="Alunos ativos" value={M.alunosAtivos} delta={M.alunosAtivosDelta} icon={I.users} />
        <KpiCard label="MRR" value={`R$ ${M.mrr.toLocaleString('pt-BR')}`} delta={M.mrrDelta} deltaPrefix="R$ " icon={I.trendUp} />
        <KpiCard label="Inadimplentes" value={M.inadimplentes} delta={M.inadimplentesDelta} negative icon={I.alert} />
        <KpiCard label="Conclusão média" value={`${M.conclusaoMedia}%`} delta={M.conclusaoMediaDelta} icon={I.target} suffix="%" />
      </div>

      {/* Alerta de dúvidas pendentes */}
      <Card style={{ background: 'var(--fc-azul-profundo)', color: 'white', border: 'none' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{ width: 48, height: 48, borderRadius: 10, background: 'rgba(200,168,75,0.2)', color: 'var(--fc-dourado)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <I.chat size={24} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: 'white' }}>{M.duvidasPendentes} dúvidas pendentes de resposta</div>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>A mais antiga está esperando há 2 dias.</div>
          </div>
          <button className="fc-btn fc-btn-primary fc-btn-sm" onClick={() => onNavigate('admin-duvidas')}>Responder agora</button>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 }}>
        {/* Evolução */}
        <Card>
          <div className="fc-card-hd">
            <div>
              <div className="fc-h3">Evolução de alunos ativos</div>
              <div className="fc-small" style={{ marginTop: 2 }}>Últimos 12 meses</div>
            </div>
            <Badge tone="green"><I.trendUp size={11} /> +73% no ano</Badge>
          </div>
          <LineChart data={M.evolucaoAtivos} />
        </Card>

        <Card>
          <div className="fc-h3" style={{ marginBottom: 16 }}>Distribuição de planos</div>
          <PlanoDist dist={M.planoDist} />
        </Card>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <Card>
          <div className="fc-card-hd">
            <div>
              <div className="fc-h3">Aulas com maior drop-off</div>
              <div className="fc-small" style={{ marginTop: 2 }}>Indica onde a didática pode melhorar</div>
            </div>
          </div>
          <div className="fc-stack fc-gap-2">
            {M.retencaoPiores.map((r, i) => (
              <div key={r.aulaId} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < M.retencaoPiores.length - 1 ? '1px solid var(--fc-gray-100)' : 'none' }}>
                <div style={{ width: 24, textAlign: 'center', fontSize: 12, fontWeight: 700, color: 'var(--fc-gray-500)' }}>{i + 1}</div>
                <div style={{ flex: 1, fontSize: 13 }}>{r.titulo}</div>
                <div style={{ width: 120 }}>
                  <Progress value={r.retencao} size="xs" />
                </div>
                <div style={{ width: 48, textAlign: 'right', fontSize: 13, fontWeight: 600, color: 'var(--fc-error)' }}>{r.retencao}%</div>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <div className="fc-card-hd">
            <div>
              <div className="fc-h3">Aulas com mais dúvidas</div>
              <div className="fc-small" style={{ marginTop: 2 }}>Ranking por volume de perguntas</div>
            </div>
          </div>
          <div className="fc-stack fc-gap-2">
            {M.duvidasPorAula.map((a, i) => (
              <div key={a.aulaId} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < M.duvidasPorAula.length - 1 ? '1px solid var(--fc-gray-100)' : 'none' }}>
                <div style={{ width: 24, textAlign: 'center', fontSize: 12, fontWeight: 700, color: 'var(--fc-gray-500)' }}>{i + 1}</div>
                <div style={{ flex: 1, fontSize: 13 }}>{a.titulo}</div>
                <Badge tone="gold">{a.count} dúvidas</Badge>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function KpiCard({ label, value, delta, negative, icon: IconEl, deltaPrefix = '', suffix = '' }) {
  const up = negative ? delta < 0 : delta > 0;
  return (
    <Card style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div className="fc-caption" style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}>{label}</div>
        <IconEl size={16} style={{ color: 'var(--fc-gray-400)' }} />
      </div>
      <div style={{ fontSize: 28, fontWeight: 700, color: 'var(--fc-azul-profundo)', letterSpacing: '-0.02em', lineHeight: 1 }}>{value}</div>
      <div style={{ marginTop: 8, fontSize: 12, fontWeight: 600, color: up ? 'var(--fc-success)' : 'var(--fc-error)', display: 'flex', alignItems: 'center', gap: 4 }}>
        {up ? <I.trendUp size={12} /> : <I.trendDown size={12} />}
        {deltaPrefix}{Math.abs(delta).toLocaleString('pt-BR')}{suffix} vs. mês anterior
      </div>
    </Card>
  );
}

function LineChart({ data }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const w = 600, h = 180, pad = 20;
  const points = data.map((v, i) => [
    pad + (i / (data.length - 1)) * (w - 2 * pad),
    h - pad - ((v - min) / (max - min || 1)) * (h - 2 * pad),
  ]);
  const pathD = points.map((p, i) => (i === 0 ? 'M' : 'L') + p.join(' ')).join(' ');
  const areaD = pathD + ` L ${points[points.length - 1][0]} ${h - pad} L ${points[0][0]} ${h - pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 200 }}>
      <defs>
        <linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#C8A84B" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#C8A84B" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaD} fill="url(#lg)" />
      <path d={pathD} stroke="#C8A84B" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {points.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill="#1B2A4A" />)}
    </svg>
  );
}

function PlanoDist({ dist }) {
  const total = dist.mensal + dist.semestral + dist.anual;
  const items = [
    { key: 'mensal', label: 'Mensal', val: dist.mensal, color: '#2E4A7A' },
    { key: 'semestral', label: 'Semestral', val: dist.semestral, color: '#C8A84B' },
    { key: 'anual', label: 'Anual (Premium)', val: dist.anual, color: '#1B2A4A' },
  ];
  // Simple bar distribution
  return (
    <div>
      <div style={{ display: 'flex', height: 10, borderRadius: 6, overflow: 'hidden', marginBottom: 18 }}>
        {items.map(it => <div key={it.key} style={{ width: (it.val / total * 100) + '%', background: it.color }} />)}
      </div>
      <div className="fc-stack fc-gap-2">
        {items.map(it => (
          <div key={it.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 10, height: 10, background: it.color, borderRadius: 2 }} />
              <span style={{ fontSize: 13 }}>{it.label}</span>
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fc-azul-profundo)' }}>
              {it.val} <span style={{ color: 'var(--fc-gray-500)', fontWeight: 400 }}>({Math.round(it.val / total * 100)}%)</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ ADMIN AULAS ============
function AdminAulas({ onEditar }) {
  const [busca, setBusca] = React.useState('');
  const filt = FC_AULAS.filter(a => a.titulo.toLowerCase().includes(busca.toLowerCase()));

  return (
    <div className="fc-stack fc-gap-6">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 14 }}>
        <div>
          <div className="fc-h1">Gestão de aulas</div>
          <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>39 itens · 36 aulas + 3 bônus</div>
        </div>
        <button className="fc-btn fc-btn-primary" onClick={() => onEditar('nova')}><I.plus size={14} /> Nova aula</button>
      </div>

      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
          <I.search size={16} style={{ position: 'absolute', left: 14, top: 13, color: 'var(--fc-gray-500)' }} />
          <input className="fc-input" style={{ paddingLeft: 38 }} placeholder="Buscar aula…" value={busca} onChange={e => setBusca(e.target.value)} />
        </div>
        <select className="fc-select" style={{ maxWidth: 180 }}>
          <option>Todos os módulos</option>
          {FC_MODULOS.map(m => <option key={m.id}>M{m.numero}: {m.nome}</option>)}
        </select>
        <select className="fc-select" style={{ maxWidth: 160 }}>
          <option>Status: todos</option>
          <option>Publicada</option>
          <option>Rascunho</option>
        </select>
      </div>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--fc-gray-50)', borderBottom: '1px solid var(--fc-gray-200)' }}>
              <th style={thCell}>#</th>
              <th style={thCell}>Título</th>
              <th style={thCell}>Módulo</th>
              <th style={thCell}>Status</th>
              <th style={thCell}>Dúvidas</th>
              <th style={thCell}>Publicação</th>
              <th style={thCell}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {filt.slice(0, 20).map((a, i) => {
              const mod = FC_MODULOS.find(m => m.id === a.modulo);
              const duv = FC_DUVIDAS.filter(d => d.aulaId === a.id && !d.resposta).length;
              return (
                <tr key={a.id} style={{ borderBottom: '1px solid var(--fc-gray-100)' }}>
                  <td style={tdCell}><span style={{ fontFamily: 'var(--fc-font-mono)', fontSize: 12 }}>{a.num}</span></td>
                  <td style={{ ...tdCell, fontWeight: 500 }}>
                    {a.titulo}
                    <div className="fc-caption" style={{ marginTop: 2 }}>{a.duracao}</div>
                  </td>
                  <td style={tdCell}>
                    <Badge tone="blue">M{mod.numero}</Badge>
                  </td>
                  <td style={tdCell}><StatusPill status="publicada" /></td>
                  <td style={tdCell}>
                    {duv > 0 ? <Badge tone="yellow">{duv} pendente{duv>1?'s':''}</Badge> : <span style={{ color: 'var(--fc-gray-500)', fontSize: 13 }}>—</span>}
                  </td>
                  <td style={tdCell}><span className="fc-small">14/01/2026</span></td>
                  <td style={tdCell}>
                    <div style={{ display: 'flex', gap: 4 }}>
                      <button className="fc-btn fc-btn-ghost fc-btn-sm" onClick={() => onEditar(a.id)}><I.edit size={14} /></button>
                      <button className="fc-btn fc-btn-ghost fc-btn-sm"><I.trash size={14} /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

const thCell = { textAlign: 'left', padding: '12px 16px', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--fc-gray-500)' };
const tdCell = { padding: '14px 16px', fontSize: 13, color: 'var(--fc-gray-800)', verticalAlign: 'middle' };

// ============ ADMIN AULA EDIT ============
function AdminAulaEdit({ aulaId, onBack }) {
  const aula = aulaId === 'nova' ? null : FC_AULAS.find(a => a.id === aulaId);
  const [materiais, setMateriais] = React.useState(FC_MATERIAIS[aulaId] || []);
  const [questoes, setQuestoes] = React.useState(FC_QUESTOES.filter(q => q.aulaId === aulaId));
  const toast = useToast();

  return (
    <div className="fc-stack fc-gap-6">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button className="fc-btn fc-btn-ghost fc-btn-sm" onClick={onBack}><I.chevronLeft size={16} /> Voltar</button>
      </div>
      <div>
        <div className="fc-h1">{aula ? 'Editar aula' : 'Nova aula'}</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>
          {aula ? `Aula ${aula.num} · ${aula.titulo}` : 'Crie uma aula do zero. Salve como rascunho e publique quando estiver pronto.'}
        </div>
      </div>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>Dados básicos</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
          <div><label className="fc-label">Número</label><input className="fc-input" defaultValue={aula?.num || ''} /></div>
          <div style={{ gridColumn: 'span 3' }}><label className="fc-label">Título</label><input className="fc-input" defaultValue={aula?.titulo || ''} /></div>
          <div><label className="fc-label">Módulo</label>
            <select className="fc-select">{FC_MODULOS.map(m => <option key={m.id}>M{m.numero}: {m.nome}</option>)}</select>
          </div>
          <div><label className="fc-label">Duração estimada</label><input className="fc-input" defaultValue={aula?.duracao || ''} placeholder="52min" /></div>
          <div style={{ gridColumn: 'span 2' }}><label className="fc-label">Tipo</label>
            <select className="fc-select"><option>Aula em vídeo</option><option>Material bônus (PDF)</option></select>
          </div>
        </div>
      </Card>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>Vídeo</div>
        <label className="fc-label">ID do vídeo no Panda Video</label>
        <div style={{ display: 'flex', gap: 10 }}>
          <input className="fc-input" placeholder="ex: a9f87e21-..." defaultValue={aula ? 'panda-' + aula.id : ''} />
          <button className="fc-btn fc-btn-secondary">Buscar na Panda</button>
        </div>
        <div className="fc-caption" style={{ marginTop: 8 }}>Integração real: API da Panda Video + signed URL com expiração curta (ver SECURITY.md).</div>
        {aula && (
          <div style={{ marginTop: 14, maxWidth: 420 }}>
            <VideoPlayer aulaTitulo={aula.titulo} email="preview@admin" />
          </div>
        )}
      </Card>

      <Card>
        <div className="fc-card-hd">
          <div className="fc-h3">Materiais complementares</div>
          <div className="fc-small">Arraste para reordenar</div>
        </div>
        <div style={{
          border: '2px dashed var(--fc-gray-300)', borderRadius: 8, padding: 20, textAlign: 'center',
          background: 'var(--fc-gray-50)', cursor: 'pointer',
        }} onClick={() => setMateriais([...materiais, { tipo: 'pdf', nome: 'Novo arquivo.pdf', tamanho: '1.2 MB' }])}>
          <I.upload size={20} style={{ color: 'var(--fc-gray-500)', marginBottom: 8 }} />
          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fc-gray-700)' }}>Arraste arquivos aqui, ou clique para escolher</div>
          <div className="fc-caption" style={{ marginTop: 4 }}>PDF, DOCX, PPTX até 50MB</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
          <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.link size={14} /> Adicionar link externo</button>
          <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.text size={14} /> Adicionar texto/resumo</button>
        </div>
        {materiais.length > 0 && (
          <div className="fc-stack fc-gap-2" style={{ marginTop: 18 }}>
            {materiais.map((m, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: 'var(--fc-gray-50)', borderRadius: 6 }}>
                <I.dragHandle size={16} style={{ color: 'var(--fc-gray-400)', cursor: 'grab' }} />
                <I.filePdf size={16} style={{ color: 'var(--fc-error)' }} />
                <div style={{ flex: 1, fontSize: 13 }}>{m.nome}</div>
                <div className="fc-caption">{m.tamanho}</div>
                <button className="fc-btn fc-btn-ghost fc-btn-sm" onClick={() => setMateriais(materiais.filter((_, j) => j !== i))}><I.trash size={14} /></button>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card>
        <div className="fc-card-hd">
          <div className="fc-h3">Questões desta aula</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.upload size={14} /> Importar CSV</button>
            <button className="fc-btn fc-btn-primary fc-btn-sm"><I.plus size={14} /> Adicionar questão</button>
          </div>
        </div>
        {questoes.length === 0 ? (
          <div className="fc-small" style={{ padding: 20, textAlign: 'center', color: 'var(--fc-gray-500)' }}>Nenhuma questão cadastrada. Clique em "Adicionar questão".</div>
        ) : (
          <div className="fc-stack fc-gap-2">
            {questoes.map((q, i) => (
              <div key={q.id} style={{ padding: 12, background: 'var(--fc-gray-50)', borderRadius: 6, display: 'flex', gap: 10 }}>
                <Badge tone="blue">Q{i+1}</Badge>
                <div style={{ flex: 1, fontSize: 13 }}>{q.enunciado}</div>
                <Badge tone="gold">{q.banca} {q.ano}</Badge>
                <button className="fc-btn fc-btn-ghost fc-btn-sm"><I.edit size={14} /></button>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>Publicação</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div><label className="fc-label">Status</label>
            <select className="fc-select"><option>Rascunho</option><option>Publicada</option></select>
          </div>
          <div><label className="fc-label">Data de publicação</label>
            <input className="fc-input" type="date" defaultValue="2026-04-22" />
          </div>
        </div>
      </Card>

      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
        <button className="fc-btn fc-btn-ghost" onClick={onBack}>Cancelar</button>
        <button className="fc-btn fc-btn-secondary" onClick={() => toast('Rascunho salvo')}><I.save size={14} /> Salvar rascunho</button>
        <button className="fc-btn fc-btn-primary" onClick={() => { toast('Aula publicada!', { gold: true }); onBack(); }}>
          <I.check size={14} /> Publicar
        </button>
      </div>
    </div>
  );
}

// ============ ADMIN ALUNOS ============
function AdminAlunos({ onVerAluno }) {
  const [busca, setBusca] = React.useState('');
  const [filtroStatus, setFiltroStatus] = React.useState('todos');
  const filt = FC_ALUNOS.filter(a => {
    if (filtroStatus !== 'todos' && a.status !== filtroStatus) return false;
    if (busca && !(a.nome.toLowerCase().includes(busca.toLowerCase()) || a.email.includes(busca.toLowerCase()))) return false;
    return true;
  });

  return (
    <div className="fc-stack fc-gap-6">
      <div>
        <div className="fc-h1">Alunos</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>{FC_ALUNOS.length} alunos cadastrados</div>
      </div>

      <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 240 }}>
          <I.search size={16} style={{ position: 'absolute', left: 14, top: 13, color: 'var(--fc-gray-500)' }} />
          <input className="fc-input" style={{ paddingLeft: 38 }} placeholder="Buscar por nome ou e-mail…" value={busca} onChange={e => setBusca(e.target.value)} />
        </div>
        <select className="fc-select" style={{ maxWidth: 180 }} value={filtroStatus} onChange={e => setFiltroStatus(e.target.value)}>
          <option value="todos">Todos os status</option>
          <option value="ativo">Ativo</option>
          <option value="expirado">Expirado</option>
          <option value="inadimplente">Inadimplente</option>
          <option value="cancelado">Cancelado</option>
          <option value="inativo-14d">Inativo 14d+</option>
        </select>
        <select className="fc-select" style={{ maxWidth: 160 }}>
          <option>Todos os planos</option><option>Mensal</option><option>Semestral</option><option>Anual</option>
        </select>
      </div>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--fc-gray-50)', borderBottom: '1px solid var(--fc-gray-200)' }}>
              <th style={thCell}>Aluno</th>
              <th style={thCell}>Plano</th>
              <th style={thCell}>Cadastro</th>
              <th style={thCell}>Progresso</th>
              <th style={thCell}>Último login</th>
              <th style={thCell}>Status</th>
              <th style={thCell}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {filt.map(a => (
              <tr key={a.id} style={{ borderBottom: '1px solid var(--fc-gray-100)' }}>
                <td style={tdCell}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div className="fc-avatar" style={{ width: 32, height: 32, fontSize: 12, background: 'var(--fc-cream-deep)', color: 'var(--fc-azul-profundo)' }}>{a.nome.charAt(0)}</div>
                    <div>
                      <div style={{ fontWeight: 500 }}>{a.nome}</div>
                      <div className="fc-caption">{a.email}</div>
                    </div>
                  </div>
                </td>
                <td style={tdCell}><Badge tone={a.plano === 'anual' ? 'gold' : a.plano === 'cortesia' ? 'blue' : 'gray'}>{a.plano}</Badge></td>
                <td style={tdCell}><span className="fc-small">{new Date(a.cadastro).toLocaleDateString('pt-BR')}</span></td>
                <td style={tdCell}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 80 }}><Progress value={a.progresso} size="xs" /></div>
                    <span className="fc-small" style={{ fontWeight: 600 }}>{a.progresso}%</span>
                  </div>
                </td>
                <td style={tdCell}><span className="fc-small">{new Date(a.ultLogin).toLocaleDateString('pt-BR')}</span></td>
                <td style={tdCell}><StatusPill status={a.status} /></td>
                <td style={tdCell}>
                  <button className="fc-btn fc-btn-secondary fc-btn-sm" onClick={() => onVerAluno(a.id)}>Ver detalhes</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ============ ADMIN DÚVIDAS (moderação) ============
function AdminDuvidas() {
  const pendentes = FC_DUVIDAS.filter(d => !d.resposta);
  const respondidas = FC_DUVIDAS.filter(d => d.resposta);
  const [tab, setTab] = React.useState('pendentes');
  const [respostas, setRespostas] = React.useState({});
  const toast = useToast();

  const lista = tab === 'pendentes' ? pendentes : respondidas;

  return (
    <div className="fc-stack fc-gap-6">
      <div>
        <div className="fc-h1">Moderação de dúvidas</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>
          {pendentes.length} pendentes · {respondidas.length} respondidas
        </div>
      </div>

      <div className="fc-tabs">
        <button className={'fc-tab' + (tab === 'pendentes' ? ' active' : '')} onClick={() => setTab('pendentes')}>
          Pendentes <span className="fc-tab-count">{pendentes.length}</span>
        </button>
        <button className={'fc-tab' + (tab === 'respondidas' ? ' active' : '')} onClick={() => setTab('respondidas')}>
          Respondidas <span className="fc-tab-count">{respondidas.length}</span>
        </button>
      </div>

      <div className="fc-stack fc-gap-3">
        {lista.map(d => {
          const aula = FC_AULAS.find(a => a.id === d.aulaId);
          return (
            <Card key={d.id}>
              <div style={{ display: 'flex', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
                <Badge tone="blue">Aula {aula?.num}: {aula?.titulo}</Badge>
                {!d.publica && <Badge tone="gray">Privada</Badge>}
                <Badge tone="gray">{d.autor} · {new Date(d.data).toLocaleDateString('pt-BR')}</Badge>
              </div>
              <div className="fc-body" style={{ color: 'var(--fc-gray-800)', marginBottom: 14 }}>{d.pergunta}</div>
              {d.resposta ? (
                <div style={{ background: 'var(--fc-cream)', borderLeft: '3px solid var(--fc-dourado)', padding: 12, borderRadius: 6 }}>
                  <div className="fc-overline" style={{ marginBottom: 6 }}>Sua resposta</div>
                  <div className="fc-body" style={{ color: 'var(--fc-gray-800)' }}>{d.resposta}</div>
                </div>
              ) : (
                <div>
                  <textarea className="fc-textarea" placeholder="Escreva a resposta para o aluno…" value={respostas[d.id] || ''} onChange={e => setRespostas({ ...respostas, [d.id]: e.target.value })} />
                  <div style={{ display: 'flex', gap: 8, marginTop: 10, justifyContent: 'flex-end' }}>
                    <button className="fc-btn fc-btn-ghost fc-btn-sm"><I.eyeOff size={14} /> Ocultar dúvida</button>
                    <button className="fc-btn fc-btn-primary fc-btn-sm" onClick={() => toast('Resposta enviada!', { gold: true })}>
                      <I.send size={14} /> Responder e marcar como resolvida
                    </button>
                  </div>
                </div>
              )}
            </Card>
          );
        })}
      </div>
    </div>
  );
}

// ============ ADMIN MÉTRICAS ============
function AdminMetricas() {
  const M = FC_METRICAS;
  return (
    <div className="fc-stack fc-gap-6">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 14 }}>
        <div>
          <div className="fc-h1">Métricas detalhadas</div>
          <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>Analytics para decisões didáticas e de negócio</div>
        </div>
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--fc-white)', borderRadius: 8, border: '1px solid var(--fc-gray-200)' }}>
          {['7d', '30d', '90d', '12m'].map(p => (
            <button key={p} className="fc-btn fc-btn-sm" style={{ background: p === '30d' ? 'var(--fc-azul-profundo)' : 'transparent', color: p === '30d' ? 'white' : 'var(--fc-gray-600)' }}>{p}</button>
          ))}
        </div>
      </div>

      <Card>
        <div className="fc-card-hd">
          <div className="fc-h3">Retenção por aula</div>
          <div className="fc-small">% de alunos que começam vs. terminam cada aula</div>
        </div>
        <div className="fc-stack fc-gap-2">
          {M.retencaoPiores.map((r, i) => (
            <div key={r.aulaId} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px 0', borderBottom: i < M.retencaoPiores.length - 1 ? '1px solid var(--fc-gray-100)' : 'none' }}>
              <div style={{ flex: 1, fontSize: 14 }}>{r.titulo}</div>
              <div style={{ width: 200 }}><Progress value={r.retencao} size="sm" /></div>
              <div style={{ width: 60, textAlign: 'right', fontSize: 14, fontWeight: 600 }}>{r.retencao}%</div>
              <div style={{ width: 50, textAlign: 'right', fontSize: 12, color: 'var(--fc-error)', fontWeight: 600 }}>{r.drop}%</div>
            </div>
          ))}
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <Card>
          <div className="fc-card-hd">
            <div className="fc-h3">Funil de onboarding</div>
            <div className="fc-small">Primeiros 7 dias</div>
          </div>
          <div className="fc-stack fc-gap-3">
            {[
              { label: 'Cadastrou', val: 100, count: 47 },
              { label: 'Logou no app', val: 91, count: 43 },
              { label: 'Assistiu Aula 00', val: 74, count: 35 },
              { label: 'Completou Módulo 1', val: 51, count: 24 },
              { label: 'Postou 1ª dúvida', val: 28, count: 13 },
            ].map((s, i) => (
              <div key={i}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span style={{ fontSize: 13 }}>{s.label}</span>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{s.val}% <span className="fc-caption">({s.count})</span></span>
                </div>
                <Progress value={s.val} size="sm" />
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <div className="fc-card-hd">
            <div className="fc-h3">Alunos em risco</div>
            <div className="fc-small">Sem login há mais de 14 dias</div>
          </div>
          <div className="fc-stack fc-gap-2">
            {FC_ALUNOS.filter(a => a.status === 'inativo-14d' || a.status === 'inadimplente').map(a => (
              <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: '1px solid var(--fc-gray-100)' }}>
                <div className="fc-avatar" style={{ width: 28, height: 28, fontSize: 11, background: 'var(--fc-cream-deep)', color: 'var(--fc-azul-profundo)' }}>{a.nome.charAt(0)}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{a.nome}</div>
                  <div className="fc-caption">Último login: {new Date(a.ultLogin).toLocaleDateString('pt-BR')}</div>
                </div>
                <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.mail size={14} /></button>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

// ============ ADMIN CONFIG ============
function AdminConfig() {
  const toast = useToast();
  return (
    <div className="fc-stack fc-gap-6" style={{ maxWidth: 800 }}>
      <div>
        <div className="fc-h1">Configurações</div>
        <div className="fc-body" style={{ color: 'var(--fc-gray-600)', marginTop: 6 }}>Regras de negócio, e-mails e integrações.</div>
      </div>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>Regras de acesso</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div>
            <label className="fc-label">Carência para liberar Módulos 3 e 4 (dias)</label>
            <input className="fc-input" type="number" defaultValue={7} />
          </div>
          <div>
            <label className="fc-label">% mínimo para emitir certificado</label>
            <input className="fc-input" type="number" defaultValue={100} />
          </div>
        </div>
      </Card>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>E-mails automáticos</div>
        {['Boas-vindas (após pagamento)', 'Senha redefinida', 'Acesso expirando em 15 dias', 'Acesso expirado', 'Certificado emitido'].map(e => (
          <div key={e} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 0', borderBottom: '1px solid var(--fc-gray-100)' }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{e}</div>
              <div className="fc-caption">Ativo</div>
            </div>
            <button className="fc-btn fc-btn-secondary fc-btn-sm"><I.edit size={14} /> Editar texto</button>
          </div>
        ))}
      </Card>

      <Card>
        <div className="fc-h3" style={{ marginBottom: 18 }}>Integrações</div>
        {[
          { nome: 'Kiwify (pagamentos)', status: 'conectado', desc: 'Webhooks: compra, refund, chargeback, cancelamento' },
          { nome: 'Panda Video (streaming)', status: 'conectado', desc: 'Signed URLs com expiração de 2h · watermark por aluno ativo' },
          { nome: 'Resend (e-mail)', status: 'conectado', desc: 'Envios transacionais · ~34 e-mails/dia' },
          { nome: 'Google Meet (mentoria)', status: 'conectado', desc: 'Link dinâmico 1h antes do encontro' },
        ].map(int => (
          <div key={int.nome} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: '1px solid var(--fc-gray-100)' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{int.nome}</div>
              <div className="fc-caption" style={{ marginTop: 2 }}>{int.desc}</div>
            </div>
            <Badge tone="green" icon={I.check}>Conectado</Badge>
          </div>
        ))}
      </Card>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <button className="fc-btn fc-btn-primary" onClick={() => toast('Configurações salvas', { gold: true })}><I.save size={14} /> Salvar alterações</button>
      </div>
    </div>
  );
}

Object.assign(window, { AdminDashboard, AdminAulas, AdminAulaEdit, AdminAlunos, AdminDuvidas, AdminMetricas, AdminConfig });
