(() => {
const DS = window.LeonardoSousaBJJDesignSystem_2cc6b8;
const { Card, Photo, Badge, Button, Chip, Input, Select, Dialog, ProgressBar, Icon, DataTable, Avatar, Tabs, Checkbox, KpiCard } = DS;
const A = window.LSAdmin;
const EV_BLANK = { title: '', type: 'Seminário', date: '', wd: 'Sáb', time: '10:00', place: 'Dojo Centro', price: '', cap: 40, ins: 0, publico: 'Todos os alunos' };
const MES = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
const WD = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
const toISO = (e) => { const [d, m] = (e.date || '').split(' '); const mi = MES.indexOf(m); return mi < 0 ? '' : `2026-${String(mi + 1).padStart(2, '0')}-${d.padStart(2, '0')}`; };

function EventForm({ item, onClose, onSave }) {
  const [f, setF] = React.useState({ ...item, iso: toISO(item) || '2026-11-14' });
  const set = (k) => (v) => setF((x) => ({ ...x, [k]: v && v.target ? v.target.value : v }));
  const submit = () => {
    const dt = new Date(f.iso + 'T12:00:00');
    onSave({ ...f, date: `${String(dt.getDate()).padStart(2, '0')} ${MES[dt.getMonth()]}`, wd: WD[dt.getDay()], price: f.price || 'Gratuito', cap: Number(f.cap) });
  };
  return (
    <Dialog open title={item.id ? 'Editar evento' : 'Novo evento'} onClose={onClose} width={560}
      footer={<><Button variant="secondary" onClick={onClose}>Cancelar</Button><Button disabled={!f.title.trim()} onClick={submit}>{item.id ? 'Salvar' : 'Criar evento'}</Button></>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 12 }}>
        <Input label="Nome do evento" placeholder="Ex.: Seminário de guarda" required value={f.title} onChange={set('title')} style={{ gridColumn: 'span 2' }} />
        <Select label="Tipo" options={['Seminário', 'Graduação', 'Campeonato', 'Kids', 'Open Mat']} value={f.type} onChange={set('type')} />
        <Input label="Data" type="date" value={f.iso} onChange={set('iso')} />
        <Input label="Horário" value={f.time} onChange={set('time')} placeholder="10:00–13:00" />
        <Input label="Local" value={f.place} onChange={set('place')} />
        <Input label="Vagas" type="number" value={f.cap} onChange={set('cap')} />
        <Input label="Valor" value={f.price === 'Gratuito' ? '' : f.price} onChange={set('price')} placeholder="R$ 0,00" hint="Vazio = gratuito" />
        <Select label="Quem pode se inscrever" options={['Todos os alunos', 'Somente adultos', 'Somente kids', 'Aberto ao público']} value={f.publico || 'Todos os alunos'} onChange={set('publico')} style={{ gridColumn: 'span 2' }} />
      </div>
    </Dialog>
  );
}

function EventsPage({ role, toast }) {
  const [items, setItems] = React.useState(A.events);
  const [open, setOpen] = React.useState(null);
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const admin = role === 'admin';
  const sync = (l) => { A.events = l; setItems(l); };
  const save = (f) => {
    if (f.id) { sync(items.map((x) => (x.id === f.id ? f : x))); toast('Evento atualizado'); }
    else { sync([...items, { ...f, id: 'e' + Date.now(), status: 'aberto' }]); toast('Evento criado e publicado no app'); }
    setForm(null);
  };
  const remove = () => { sync(items.filter((x) => x.id !== del.id)); toast(`${del.title} excluído`); setDel(null); };
  const inscritos = [
    { id: 1, nome: 'Ana Lima', faixa: 'Roxa', pag: 'pago' }, { id: 2, nome: 'Rafael Costa', faixa: 'Azul', pag: 'pago' },
    { id: 3, nome: 'Juliana Rocha', faixa: 'Marrom', pag: 'pendente' }, { id: 4, nome: 'Bruno Teixeira', faixa: 'Azul', pag: 'pago' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Grid cols="repeat(auto-fit, minmax(170px, 1fr))">
        <KpiCard label="Próximos eventos" value={items.length} icon="calendar-days" />
        <KpiCard label="Inscrições" value={items.reduce((a, e) => a + e.ins, 0)} icon="ticket" delta="+22" trend="up" hint="esta semana" />
        <KpiCard label="Receita de eventos" value="R$ 8.940" icon="wallet" hint="outubro" />
      </Grid>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <h3 style={{ fontSize: 17 }}>Próximos</h3><div style={{ flex: 1 }} />
        {admin ? <Button iconLeft="plus" onClick={() => setForm(EV_BLANK)}>Novo evento</Button> : null}
      </div>
      <Grid cols="repeat(auto-fill, minmax(300px, 1fr))">
        {items.map((e) => (
          <Card key={e.id} padding={0} interactive onClick={() => setOpen(e)} style={{ overflow: 'hidden' }}>
            <Photo ratio="16/7" radius="0" placeholder={e.type === 'Campeonato' ? 'Atletas no pódio' : 'Seminário no tatame'} scrim="bottom">
              <span style={{ position: 'absolute', top: 12, left: 12, width: 52, borderRadius: 12, background: '#fff', textAlign: 'center', padding: '6px 0' }}>
                <span style={{ display: 'block', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: 'var(--brand-primary)' }}>{e.date.split(' ')[1]}</span>
                <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, lineHeight: '22px', color: 'var(--text-strong)' }}>{e.date.split(' ')[0]}</span>
              </span>
              <span style={{ position: 'absolute', top: 12, right: 12, display: 'flex', gap: 6, alignItems: 'center' }}>
                <Badge size="sm" tone="dark">{e.type}</Badge>
                {admin ? <CardActions dark onEdit={() => setForm(e)} onDelete={() => setDel(e)} /> : null}
              </span>
            </Photo>
            <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, color: 'var(--text-strong)' }}>{e.title}</div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', display: 'flex', flexDirection: 'column', gap: 4 }}>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="clock" size={14} />{e.wd}, {e.date} · {e.time}</span>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="map-pin" size={14} />{e.place}</span>
              </div>
              <ProgressBar value={e.ins} max={e.cap} size="sm" tone={e.ins >= e.cap ? 'warning' : 'dark'} />
              <div style={{ display: 'flex', alignItems: 'center', fontSize: 13 }}>
                <span style={{ fontWeight: 600, color: e.ins >= e.cap ? 'var(--warning)' : 'var(--text-strong)' }}>{e.ins >= e.cap ? 'Lotado' : `${e.ins}/${e.cap} inscritos`}</span>
                <span style={{ flex: 1 }} /><span style={{ fontWeight: 600, color: 'var(--text-strong)' }}>{e.price}</span>
              </div>
            </div>
          </Card>
        ))}
      </Grid>
      {open ? (
        <Dialog open title={open.title} description={`${open.wd}, ${open.date} · ${open.time} · ${open.place}`} onClose={() => setOpen(null)} width={600}
          footer={<><Button variant="secondary" onClick={() => setOpen(null)}>Fechar</Button><Button variant="secondary" iconLeft="download">Exportar lista</Button><Button iconLeft="megaphone" onClick={() => { setOpen(null); toast('Aviso do evento enviado'); }}>Divulgar</Button></>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <ProgressBar label="Inscrições" value={open.ins} max={open.cap} valueLabel={`${open.ins}/${open.cap}`} showValue />
            {open.ins ? (
              <div style={{ border: '1px solid var(--border-subtle)', borderRadius: 12, overflow: 'hidden' }}>
                <DataTable dense rows={inscritos} columns={[
                  { key: 'nome', label: 'Inscrito', render: (r) => <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Avatar name={r.nome} size={26} /><b style={{ fontWeight: 600, color: 'var(--text-strong)' }}>{r.nome}</b></div> },
                  { key: 'faixa', label: 'Faixa' },
                  { key: 'pag', label: 'Pagamento', render: (r) => open.price === 'Gratuito' ? <Badge status="isento" /> : <Badge status={r.pag} /> },
                ]} />
              </div>
            ) : <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Nenhuma inscrição ainda.</div>}
          </div>
        </Dialog>
      ) : null}
      {form ? <EventForm item={form} onClose={() => setForm(null)} onSave={save} /> : null}
      {del ? <ConfirmDelete title="Excluir evento?" description={`${del.title} sai do app. Inscritos serão avisados do cancelamento.`} onCancel={() => setDel(null)} onConfirm={remove} /> : null}
    </div>
  );
}

const AUD = [['Todos os alunos', '248'], ['Uma turma', '—'], ['Responsáveis', '3'], ['Treino Feminino', '26'], ['Mensalidades pendentes', '14']];

function MessageForm({ item, onClose, onSave }) {
  const [f, setF] = React.useState({ body: '', ...item });
  const set = (k) => (v) => setF((x) => ({ ...x, [k]: v && v.target ? v.target.value : v }));
  const tog = (c) => setF((x) => ({ ...x, canal: x.canal.includes(c) ? x.canal.filter((y) => y !== c) : [...x.canal, c] }));
  const reach = (AUD.find((a) => a[0] === f.to) || [0, '—'])[1];
  const out = (status, date) => onSave({ ...f, status, date, reach, read: status === 'enviado' ? 0 : f.read || 0 });
  return (
    <Dialog open title={item.id ? 'Editar aviso' : 'Novo aviso'} description="Aparece no app de alunos e responsáveis." onClose={onClose} width={600}
      footer={<><Button variant="secondary" onClick={() => out('rascunho', 'Rascunho')} disabled={!f.title.trim()}>Salvar rascunho</Button><Button variant="secondary" iconLeft="clock" onClick={() => out('agendado', 'Agendado · 25/09, 10:00')} disabled={!f.title.trim()}>Agendar</Button><Button iconLeft="send" onClick={() => out('enviado', 'Agora')} disabled={!f.title.trim() || !f.canal.length}>Enviar agora</Button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Input label="Título" placeholder="Ex.: Aula especial de sábado" required value={f.title} onChange={set('title')} />
        <Input label="Mensagem" multiline rows={4} placeholder="Escreva o aviso…" value={f.body} onChange={set('body')} />
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', marginBottom: 8 }}>Público</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{AUD.map(([l, n]) => <Chip key={l} size="sm" selected={f.to === l} onClick={() => set('to')(l)}>{l}{n !== '—' ? ` · ${n}` : ''}</Chip>)}</div>
        </div>
        <div style={{ display: 'flex', gap: 20 }}>
          <Checkbox checked={f.canal.includes('App')} onChange={() => tog('App')} label="Notificação no app" />
          <Checkbox checked={f.canal.includes('E-mail')} onChange={() => tog('E-mail')} label="E-mail" />
          <Checkbox checked={f.canal.includes('WhatsApp')} onChange={() => tog('WhatsApp')} label="WhatsApp" />
        </div>
      </div>
    </Dialog>
  );
}

function CommsPage({ role, toast }) {
  const [items, setItems] = React.useState(A.messages);
  const [tab, setTab] = React.useState('todos');
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const ST = { enviado: ['success', 'Enviado'], agendado: ['info', 'Agendado'], rascunho: ['neutral', 'Rascunho'] };
  const sync = (l) => { A.messages = l; setItems(l); };
  const rows = items.filter((m) => tab === 'todos' || m.status === tab);
  const save = (f) => {
    if (f.id) sync(items.map((x) => (x.id === f.id ? f : x))); else sync([{ ...f, id: 'm' + Date.now() }, ...items]);
    toast(f.status === 'enviado' ? `Aviso enviado para ${f.reach} pessoas` : f.status === 'agendado' ? 'Aviso agendado' : 'Rascunho salvo');
    setForm(null);
  };
  const remove = () => { sync(items.filter((x) => x.id !== del.id)); toast('Aviso excluído'); setDel(null); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12 }}>
        <Tabs items={[{ value: 'todos', label: 'Todos' }, { value: 'enviado', label: 'Enviados' }, { value: 'agendado', label: 'Agendados', count: items.filter((m) => m.status === 'agendado').length }, { value: 'rascunho', label: 'Rascunhos' }]} value={tab} onChange={setTab} style={{ flex: 1 }} />
        <Button iconLeft="megaphone" onClick={() => setForm({ title: '', body: '', to: 'Todos os alunos', canal: ['App'] })} style={{ marginBottom: 8 }}>Novo aviso</Button>
      </div>
      <Card padding={0} style={{ overflow: 'hidden' }}>
        <DataTable rows={rows} onRowClick={(r) => setForm(r)} columns={[
          { key: 'title', label: 'Aviso', render: (r) => <div><div style={{ fontWeight: 600, color: 'var(--text-strong)' }}>{r.title}</div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{r.date}</div></div> },
          { key: 'to', label: 'Público', render: (r) => <span style={{ fontSize: 13, whiteSpace: 'nowrap' }}>{r.to} · {r.reach}</span> },
          { key: 'canal', label: 'Canais', render: (r) => <div style={{ display: 'flex', gap: 4 }}>{r.canal.map((c) => <Badge key={c} size="sm" icon={c === 'App' ? 'smartphone' : c === 'WhatsApp' ? 'message-circle' : 'mail'}>{c}</Badge>)}</div> },
          { key: 'read', label: 'Leitura', render: (r) => r.status === 'enviado' ? <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: 110 }}><ProgressBar value={r.read} size="sm" tone="dark" style={{ flex: 1 }} /><span style={{ fontSize: 12, fontWeight: 600 }}>{r.read}%</span></div> : <span style={{ color: 'var(--text-subtle)' }}>—</span> },
          { key: 'status', label: 'Status', render: (r) => <Badge tone={ST[r.status][0]} dot>{ST[r.status][1]}</Badge> },
          { key: 'a', label: '', align: 'right', render: (r) => <CardActions onEdit={() => setForm(r)} onDelete={() => setDel(r)} /> },
        ]} />
      </Card>
      {form ? <MessageForm item={form} onClose={() => setForm(null)} onSave={save} /> : null}
      {del ? <ConfirmDelete title="Excluir aviso?" description={del.status === 'enviado' ? 'O aviso some do app de quem ainda não abriu.' : undefined} onCancel={() => setDel(null)} onConfirm={remove} /> : null}
    </div>
  );
}

Object.assign(window, { EventsPage, CommsPage });
})();
