(() => {
const DS = window.LeonardoSousaBJJDesignSystem_2cc6b8;
const { Card, Avatar, BeltBadge, Badge, Button, Tabs, ProgressBar, ProgressRing, BarChart, Input, Alert, ListItem, Icon } = DS;
const A = window.LSAdmin;

function Field({ l, v }) {
  return <div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{l}</div><div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-strong)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v}</div></div>;
}

function StudentProfilePage({ student, role, onBack, go, toast = () => {} }) {
  const s = student || A.students[1];
  const [tab, setTab] = React.useState('geral');
  const pays = A.payments.filter((p) => p.aluno === s.nome);
  const grads = A.gradHistory.filter((g) => g.nome === s.nome);
  const kid = s.turma.startsWith('Kids');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <button onClick={onBack} style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 6, border: 0, background: 'transparent', color: 'var(--text-muted)', fontSize: 13, fontWeight: 600, cursor: 'pointer', padding: 0 }}><Icon name="arrow-left" size={16} />Alunos</button>
      <Card padding={24}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
          <Avatar name={s.nome} size={80} ring={`var(--belt-${{ branca: 'white', cinza: 'gray', amarela: 'yellow', azul: 'blue', roxa: 'purple', marrom: 'brown', preta: 'black' }[s.faixa] || 'white'})`} />
          <div style={{ flex: 1, minWidth: 320, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <h2 style={{ fontSize: 24, lineHeight: '32px' }}>{s.nome}</h2>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <BeltBadge belt={s.faixa} stripes={s.g} kidsStripe={s.kids} showLabel />
              <Badge status={s.matricula} /><Badge status={s.status} />
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{A.dojoName(s.dojo)} · {s.turma} · Aluno desde mar 2022 · #{String(s.id).padStart(4, '0')}</div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <a href={waLink(s.tel, `Olá, ${s.nome.split(' ')[0]}! Aqui é da Leonardo Sousa BJJ.`)} target="_blank" rel="noopener" style={{ textDecoration: 'none' }}><Button variant="secondary" iconLeft="message-circle">WhatsApp</Button></a>
            <Button variant="secondary" iconLeft="pencil">Editar</Button>
            <Button iconLeft="award" onClick={() => go('graduacoes')}>Graduar</Button>
          </div>
        </div>
      </Card>
      <Tabs items={[{ value: 'geral', label: 'Visão geral' }, { value: 'pres', label: 'Presenças', count: 42 }, { value: 'grad', label: 'Graduações' }, { value: 'saude', label: 'Anamnese e emergência' }, { value: 'fin', label: 'Financeiro' }, { value: 'notas', label: 'Notas privadas' }]} value={tab} onChange={setTab} />
      {tab === 'saude' ? <HealthTab s={s} toast={toast} /> : tab === 'geral' ? (
        <Grid cols="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr)">
          <Card title="Frequência" subtitle="Últimos 30 dias">
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <ProgressRing value={s.freq} size={96} />
              <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Última presença<br /><b style={{ color: 'var(--text-strong)' }}>{s.ultima}</b></div>
            </div>
          </Card>
          <Card title="Graduação" subtitle="Avaliada pelo professor">
            <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 12 }}><Field l="Na faixa atual desde" v="jun 2025" /><Field l="Última avaliação" v="Prof. Leonardo" /></div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 12 }}>Não há contagem de aulas: o professor indica o aluno quando ele está pronto.</div>
          </Card>
          <Card title="Dados">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12 }}>
              <Field l="Dojo" v={A.dojoName(s.dojo)} /><Field l="Professor responsável" v={`Prof. ${(A.dojos.find((d) => d.id === s.dojo) || {}).prof || '—'}`} />
              <Field l="E-mail" v={s.email} /><Field l="WhatsApp" v={s.tel} />
              <Field l="Nascimento" v={kid ? '12/03/2018' : '08/07/1994'} /><Field l={kid ? 'Responsável' : 'Plano'} v={kid ? 'Carla Mendes' : 'Mensal Adulto'} />
            </div>
          </Card>
          <Card title="Aulas por semana" style={{ gridColumn: 'span 3' }}><BarChart height={140} data={[{ label: '17/8', value: 2 }, { label: '24/8', value: 3 }, { label: '31/8', value: 3 }, { label: '7/9', value: 4 }, { label: '14/9', value: 3 }, { label: '21/9', value: 2 }]} showValues /></Card>
        </Grid>
      ) : tab === 'pres' ? (
        <Card padding="4px 20px">{A.studentAttendance.map((h, i) => <ListItem key={i} icon="check" title={h.c} subtitle={`${h.d} · ${h.t}`} trailing={<Badge size="sm" tone={h.via === 'App' ? 'info' : 'neutral'} icon={h.via === 'App' ? 'qr-code' : 'user-round'}>{h.via === 'App' ? 'Check-in pelo app' : 'Marcado pelo professor'}</Badge>} divider={i < A.studentAttendance.length - 1} />)}</Card>
      ) : tab === 'grad' ? (
        <Card padding="4px 20px">
          {(grads.length ? grads : [{ de: [s.faixa, Math.max(0, s.g - 1)], para: [s.faixa, s.g], data: '14 jun 2026', prof: 'Leonardo Sousa' }]).map((g, i) => (
            <ListItem key={i} leading={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><BeltBadge belt={g.de[0]} stripes={g.de[1]} kidsStripe={s.kids} size="sm" /><Icon name="arrow-right" size={12} /><BeltBadge belt={g.para[0]} stripes={g.para[1]} kidsStripe={s.kids} size="sm" /></span>} title={`Prof. ${g.prof}`} meta={g.data} />
          ))}
        </Card>
      ) : tab === 'fin' ? (
        role !== 'admin' ? <Alert tone="locked" title="Acesso restrito">Somente administradores veem os dados financeiros do aluno.</Alert> : (
          <Card padding="4px 20px">{(pays.length ? pays : A.payments.slice(3, 5)).map((p, i) => <ListItem key={p.id} icon="receipt" title={`${p.plano} · venc. ${p.venc}`} subtitle={p.metodo === '—' ? 'Aguardando pagamento' : p.metodo} trailing={<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}><b style={{ color: 'var(--text-strong)' }}>{p.valor}</b><Badge status={p.status} /></div>} divider={i < 1} />)}</Card>
        )
      ) : (
        <Card title="Notas privadas" subtitle="Visíveis apenas para professores e administração">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ padding: 12, borderRadius: 12, background: 'var(--surface-sunken)', fontSize: 14 }}><b>Prof. Leonardo · 21 set</b><div style={{ color: 'var(--text-body)', marginTop: 4 }}>Evoluindo bem na guarda. Trabalhar postura na passagem.</div></div>
            <Input multiline rows={3} placeholder="Escreva uma observação sobre o aluno…" />
            <div><Button size="sm">Salvar nota</Button></div>
          </div>
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { StudentProfilePage });
})();
