(() => {
const DS = window.LeonardoSousaBJJDesignSystem_2cc6b8;
const { Card, Badge, Button, Chip, Dialog, Input, Select, ProgressBar, Avatar, SegmentedControl, Icon } = DS;
const A = window.LSAdmin;
const DIAS = ['Seg 21', 'Ter 22', 'Qua 23', 'Qui 24', 'Sex 25', 'Sáb 26'];
const DN = ['Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
const MODC = { Gi: 'var(--ls-black)', 'No-Gi': 'var(--gray-500)', Kids: 'var(--info)', Feminino: 'var(--belt-purple)' };
const BLANK = { turma: '', mod: 'Gi', prof: 'Leonardo Sousa', dia: 0, ini: '19:00', fim: '20:30', sala: 'Tatame 1', cap: 24, ins: 0 };

function Slot({ s, onClick }) {
  const full = s.ins >= s.cap;
  return (
    <button onClick={onClick} style={{ textAlign: 'left', width: '100%', border: '1px solid var(--border-subtle)', background: 'var(--surface-card)', borderRadius: 12, padding: 10, cursor: 'pointer', boxShadow: 'var(--shadow-xs)', display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: MODC[s.mod] }} />
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 600, color: 'var(--text-strong)' }}>{s.ini}</span>
        <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>– {s.fim}</span>
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, lineHeight: '17px', color: 'var(--text-strong)' }}>{s.turma}</div>
      <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{s.prof.split(' ')[0]} · {s.sala}</div>
      <ProgressBar value={s.ins} max={s.cap} size="sm" tone={full ? 'warning' : 'dark'} />
      <div style={{ fontSize: 11, fontWeight: 600, color: full ? 'var(--warning)' : 'var(--text-muted)' }}>{full ? 'Lotada' : `${s.ins}/${s.cap} vagas`}</div>
    </button>
  );
}

function ClassForm({ item, onClose, onSave }) {
  const [f, setF] = React.useState(item);
  const set = (k) => (v) => setF((x) => ({ ...x, [k]: v && v.target ? v.target.value : v }));
  const ok = f.turma.trim() && f.ini < f.fim;
  return (
    <Dialog open title={item.id ? 'Editar turma' : 'Nova turma'} description="A turma aparece na agenda dos alunos assim que for salva." onClose={onClose} width={560}
      footer={<><Button variant="secondary" onClick={onClose}>Cancelar</Button><Button disabled={!ok} onClick={() => onSave({ ...f, dia: Number(f.dia), cap: Number(f.cap) })}>{item.id ? 'Salvar' : 'Criar turma'}</Button></>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 12 }}>
        <Input label="Nome da turma" placeholder="Ex.: Adulto Gi — Intermediário" required value={f.turma} onChange={set('turma')} style={{ gridColumn: 'span 2' }} />
        <Select label="Modalidade" options={['Gi', 'No-Gi', 'Kids', 'Feminino']} value={f.mod} onChange={set('mod')} />
        <Select label="Professor" options={A.instructors.map((i) => i.nome)} value={f.prof} onChange={set('prof')} />
        <Select label="Dia da semana" options={DN.map((d, i) => ({ value: String(i), label: d }))} value={String(f.dia)} onChange={set('dia')} />
        <Select label="Local" options={['Tatame 1', 'Tatame 2']} value={f.sala} onChange={set('sala')} />
        <Input label="Início" type="time" value={f.ini} onChange={set('ini')} />
        <Input label="Fim" type="time" value={f.fim} onChange={set('fim')} error={f.ini >= f.fim ? 'O fim precisa ser depois do início.' : undefined} />
        <Input label="Capacidade" type="number" value={f.cap} onChange={set('cap')} />
      </div>
    </Dialog>
  );
}

function ClassesPage({ role, toast, go }) {
  const [items, setItems] = React.useState(A.schedule);
  const [mod, setMod] = React.useState('Todas');
  const [open, setOpen] = React.useState(null);
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const [view, setView] = React.useState('semana');
  const admin = role === 'admin';
  const sync = (l) => { A.schedule = l; setItems(l); };
  const list = items.filter((s) => mod === 'Todas' || s.mod === mod);
  const save = (f) => {
    if (f.id) { sync(items.map((x) => (x.id === f.id ? f : x))); toast('Turma atualizada'); }
    else { sync([...items, { ...f, id: 's' + Date.now() }]); toast(`${f.turma} criada · ${DN[f.dia]} ${f.ini}`); }
    setForm(null); setOpen(null);
  };
  const remove = () => { sync(items.filter((x) => x.id !== del.id)); toast(`${del.turma} excluída`); setDel(null); setOpen(null); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        {['Todas', 'Gi', 'No-Gi', 'Kids', 'Feminino'].map((m) => <Chip key={m} selected={mod === m} onClick={() => setMod(m)}>{m}</Chip>)}
        <div style={{ flex: 1 }} />
        <SegmentedControl size="sm" options={[{ value: 'semana', label: 'Semana' }, { value: 'lista', label: 'Lista' }]} value={view} onChange={setView} />
        {admin ? <Button iconLeft="plus" onClick={() => setForm(BLANK)}>Nova turma</Button> : null}
      </div>
      {view === 'semana' ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(140px, 1fr))', gap: 12, overflowX: 'auto' }}>
          {DIAS.map((d, i) => {
            const day = list.filter((s) => s.dia === i).sort((a, b) => a.ini.localeCompare(b.ini));
            return (
              <div key={d} style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
                <div style={{ padding: '8px 10px', borderRadius: 10, background: i === 2 ? 'var(--ls-black)' : 'var(--surface-sunken)', color: i === 2 ? '#fff' : 'var(--text-strong)', fontSize: 13, fontWeight: 600, display: 'flex', justifyContent: 'space-between' }}>
                  {d}{i === 2 ? <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--brand-primary)', alignSelf: 'center' }} /> : null}
                </div>
                {day.map((s) => <Slot key={s.id} s={s} onClick={() => setOpen(s)} />)}
                {day.length === 0 ? <div style={{ fontSize: 12, color: 'var(--text-subtle)', textAlign: 'center', padding: 12, border: '1px dashed var(--border-default)', borderRadius: 12 }}>Sem aulas</div> : null}
              </div>
            );
          })}
        </div>
      ) : (
        <Card padding="4px 20px">
          {[...list].sort((a, b) => a.dia - b.dia || a.ini.localeCompare(b.ini)).map((s, i, arr) => (
            <div key={s.id} onClick={() => setOpen(s)} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--border-subtle)' : 0, cursor: 'pointer' }}>
              <span style={{ width: 64, fontSize: 13, color: 'var(--text-muted)' }}>{DIAS[s.dia].split(' ')[0]}</span>
              <span style={{ width: 96, fontFamily: 'var(--font-display)', fontWeight: 600, color: 'var(--text-strong)' }}>{s.ini}–{s.fim}</span>
              <span style={{ flex: 1, fontWeight: 600, color: 'var(--text-strong)' }}>{s.turma}</span>
              <span style={{ width: 150, fontSize: 13, color: 'var(--text-muted)' }}>Prof. {s.prof}</span>
              <Badge>{s.mod}</Badge>
              <span style={{ width: 60, textAlign: 'right', fontSize: 13, fontWeight: 600 }}>{s.ins}/{s.cap}</span>
              {admin ? <CardActions onEdit={() => setForm(s)} onDelete={() => setDel(s)} /> : null}
            </div>
          ))}
        </Card>
      )}
      {open && !form && !del ? (
        <Dialog open title={open.turma} description={`${DN[open.dia]} · ${open.ini}–${open.fim} · ${open.sala}`} onClose={() => setOpen(null)} width={520}
          footer={<>{admin ? <Button variant="ghost" iconLeft="trash-2" onClick={() => setDel(open)} style={{ marginRight: 'auto' }}>Excluir</Button> : null}{admin ? <Button variant="secondary" iconLeft="pencil" onClick={() => setForm(open)}>Editar</Button> : null}<Button iconLeft="clipboard-check" onClick={() => { setOpen(null); go && go('presenca'); }}>Abrir chamada</Button></>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}><Avatar name={open.prof} size={40} /><div><div style={{ fontWeight: 600, color: 'var(--text-strong)' }}>Prof. {open.prof}</div><div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Responsável pela turma</div></div><div style={{ flex: 1 }} /><Badge>{open.mod}</Badge></div>
            <ProgressBar label="Ocupação" value={open.ins} max={open.cap} valueLabel={`${open.ins}/${open.cap} alunos`} showValue tone={open.ins >= open.cap ? 'warning' : 'brand'} />
          </div>
        </Dialog>
      ) : null}
      {form ? <ClassForm item={form} onClose={() => setForm(null)} onSave={save} /> : null}
      {del ? <ConfirmDelete title="Excluir turma?" description={`${del.turma} (${DN[del.dia]} ${del.ini}) sai da agenda dos alunos.`} onCancel={() => setDel(null)} onConfirm={remove} /> : null}
    </div>
  );
}

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