(() => {
const DS = window.LeonardoSousaBJJDesignSystem_2cc6b8;
const { Card, Button, Badge, Avatar, Icon, Dialog, Input, Select, KpiCard } = DS;
const A = window.LSAdmin;

function DojoPhoto({ id }) {
  return (
    <div style={{ position: 'relative', aspectRatio: '16/9', background: 'var(--surface-sunken)' }}>
      {React.createElement('image-slot', { id: `dojo-${id}`, shape: 'rect', placeholder: 'Arraste a foto do dojo', style: { position: 'absolute', inset: 0, width: '100%', height: '100%' } })}
    </div>
  );
}

function DojosPage({ role, toast, go }) {
  const [dojos, setDojos] = React.useState(A.dojos);
  const [edit, setEdit] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const remove = () => { A.dojos = A.dojos.filter((x) => x.id !== del.id); setDojos([...A.dojos]); toast(`${del.nome} excluído`); setDel(null); };
  const admin = role === 'admin';
  const save = () => {
    if (!edit.nome || !edit.end) return;
    if (edit.novo) { const d = { ...edit, id: 'd' + Date.now(), turmas: 0, alunos: 0, tatames: 1, novo: undefined }; A.dojos.push(d); setDojos([...A.dojos]); toast(`${d.nome} criado`); }
    else { Object.assign(A.dojos.find((d) => d.id === edit.id), edit); setDojos([...A.dojos]); toast('Dojo atualizado'); }
    setEdit(null);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Grid cols="repeat(auto-fit, minmax(170px, 1fr))">
        <KpiCard label="Dojos" value={dojos.length} icon="map-pin" />
        <KpiCard label="Alunos em todos os dojos" value={dojos.reduce((a, d) => a + d.alunos, 0)} icon="users" />
        <KpiCard label="Turmas semanais" value={dojos.reduce((a, d) => a + d.turmas, 0)} icon="calendar-days" />
      </Grid>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Passe o mouse sobre a foto para trocar a imagem de cada dojo.</div>
        <div style={{ flex: 1 }} />
        {admin ? <Button iconLeft="plus" onClick={() => setEdit({ nome: '', end: '', prof: 'Leonardo Sousa', tel: '', horario: '', novo: true })}>Novo dojo</Button> : null}
      </div>
      <Grid cols="repeat(auto-fill, minmax(300px, 1fr))">
        {dojos.map((d) => (
          <Card key={d.id} padding={0} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            <div style={{ position: 'relative' }}>
              <DojoPhoto id={d.id} />
              {d.sede ? <span style={{ position: 'absolute', top: 12, left: 12, pointerEvents: 'none' }}><Badge size="sm" tone="dark">Sede</Badge></span> : null}
            </div>
            <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--text-strong)' }}>{d.nome}</div>
              <a href={A.mapsUrl(d.end)} target="_blank" rel="noopener" style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 13, fontWeight: 500, color: 'var(--text-body)', textDecoration: 'none' }}>
                <Icon name="map-pin" size={16} color="var(--brand-primary)" style={{ marginTop: 1 }} /><span style={{ textWrap: 'pretty' }}>{d.end}</span>
              </a>
              <div style={{ display: 'flex', gap: 16, fontSize: 13, color: 'var(--text-muted)', flexWrap: 'wrap' }}>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="clock" size={14} />{d.horario || '—'}</span>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="phone" size={14} />{d.tel || '—'}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 12, borderRadius: 12, background: 'var(--surface-sunken)' }}>
                <Avatar name={d.prof} size={36} ring="var(--belt-black)" />
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Professor responsável</div><div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>Prof. {d.prof}</div></div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 8 }}>
                {[['Alunos', d.alunos], ['Turmas', d.turmas], ['Tatames', d.tatames]].map(([l, v]) => <div key={l}><div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>{v}</div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{l}</div></div>)}
              </div>
              <div style={{ flex: 1 }} />
              <div style={{ display: 'flex', gap: 8 }}>
                <a href={A.mapsUrl(d.end)} target="_blank" rel="noopener" style={{ flex: 1, textDecoration: 'none' }}><Button fullWidth variant="secondary" iconLeft="map">Abrir no Maps</Button></a>
                <Button variant="secondary" iconLeft="users" onClick={() => go('alunos', d.id)}>Alunos</Button>
                {admin ? <CardActions onEdit={() => setEdit({ ...d })} onDelete={() => setDel(d)} /> : null}
              </div>
            </div>
          </Card>
        ))}
      </Grid>
      {del ? <ConfirmDelete title="Excluir dojo?" description={`${del.nome} sai da lista. Os ${del.alunos} alunos vinculados precisarão ser movidos para outro dojo.`} onCancel={() => setDel(null)} onConfirm={remove} /> : null}
      {edit ? (
        <Dialog open title={edit.novo ? 'Novo dojo' : `Editar ${edit.nome}`} onClose={() => setEdit(null)} width={560}
          footer={<><Button variant="secondary" onClick={() => setEdit(null)}>Cancelar</Button><Button onClick={save} disabled={!edit.nome || !edit.end}>{edit.novo ? 'Criar dojo' : 'Salvar'}</Button></>}>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 12 }}>
            <Input label="Nome do dojo" required value={edit.nome} onChange={(e) => setEdit({ ...edit, nome: e.target.value })} placeholder="Ex.: Dojo Pinheiros" style={{ gridColumn: 'span 2' }} />
            <Input label="Endereço completo" required iconLeft="map-pin" value={edit.end} onChange={(e) => setEdit({ ...edit, end: e.target.value })} placeholder="Rua, número · bairro, cidade – UF" hint="Usado no botão Abrir no Maps" style={{ gridColumn: 'span 2' }} />
            <Select label="Professor responsável" options={A.instructors.map((i) => i.nome)} value={edit.prof} onChange={(v) => setEdit({ ...edit, prof: v })} />
            <Input label="Telefone" value={edit.tel} onChange={(e) => setEdit({ ...edit, tel: e.target.value })} />
            <Input label="Horário de funcionamento" value={edit.horario} onChange={(e) => setEdit({ ...edit, horario: e.target.value })} placeholder="Seg a Sex · 07h–22h" style={{ gridColumn: 'span 2' }} />
          </div>
        </Dialog>
      ) : null}
    </div>
  );
}

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