(() => {
const DS = window.LeonardoSousaBJJDesignSystem_2cc6b8;
const { Card, Photo, Badge, Button, IconButton, Chip, Input, Select, Dialog, Checkbox, Icon, EmptyState, SegmentedControl, DataTable } = DS;
const A = window.LSAdmin;
const LV = { Iniciante: 'success', Intermediário: 'warning', Avançado: 'dark' };
const TURMAS = ['Adulto Gi', 'Iniciantes', 'No-Gi', 'Treino Feminino', 'Kids 6–9'];
const BLANK = { title: '', cat: 'Raspagens', mod: 'Gi', level: 'Iniciante', desc: '', turmas: ['Adulto Gi'], prof: 'Leonardo Sousa', dur: '0:00', views: 0, status: 'publicado' };

function ContentForm({ item, onClose, onSave }) {
  const [f, setF] = React.useState({ desc: '', ...item });
  const [err, setErr] = React.useState('');
  const editing = !!item.id;
  const set = (k) => (v) => setF((x) => ({ ...x, [k]: v && v.target ? v.target.value : v }));
  const toggle = (t) => setF((x) => ({ ...x, turmas: x.turmas.includes(t) ? x.turmas.filter((y) => y !== t) : [...x.turmas, t] }));
  const submit = (status) => { if (!f.title.trim()) { setErr('Informe o título da técnica.'); return; } onSave({ ...f, status }); };
  return (
    <Dialog open title={editing ? 'Editar técnica' : 'Nova técnica'} description={editing ? 'As alterações aparecem no app dos alunos na hora.' : 'O vídeo fica disponível no app para as turmas selecionadas.'} onClose={onClose} width={600}
      footer={<><Button variant="secondary" onClick={() => submit('rascunho')}>{editing && f.status === 'publicado' ? 'Despublicar' : 'Salvar rascunho'}</Button><Button iconLeft={editing ? 'check' : 'send'} onClick={() => submit('publicado')}>{editing ? 'Salvar e publicar' : 'Publicar'}</Button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {editing ? (
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', padding: 10, borderRadius: 12, background: 'var(--surface-sunken)' }}>
            <Photo ratio="16/9" radius="8px" placeholder="" style={{ width: 96 }} />
            <div style={{ flex: 1, fontSize: 13, color: 'var(--text-muted)' }}>Vídeo atual · {f.dur}</div>
            <Button size="sm" variant="secondary" iconLeft="replace">Trocar vídeo</Button>
          </div>
        ) : (
          <div style={{ border: '1.5px dashed var(--border-strong)', borderRadius: 14, padding: 24, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, color: 'var(--text-muted)', fontSize: 13 }}>
            <Icon name="upload-cloud" size={28} color="var(--text-strong)" /><b style={{ color: 'var(--text-strong)' }}>Arraste o vídeo aqui</b>MP4 ou MOV, até 2 GB · ou <a href="#" onClick={(e) => e.preventDefault()}>escolher arquivo</a>
          </div>
        )}
        <Input label="Título" placeholder="Ex.: Raspagem de gancho" required value={f.title} onChange={(e) => { setErr(''); set('title')(e); }} error={err} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12 }}>
          <Select label="Categoria" options={['Raspagens', 'Passagens', 'Finalizações', 'Quedas', 'Defesa']} value={f.cat} onChange={set('cat')} />
          <Select label="Modalidade" options={['Gi', 'No-Gi', 'Feminino', 'Kids']} value={f.mod} onChange={set('mod')} />
          <Select label="Nível" options={['Iniciante', 'Intermediário', 'Avançado']} value={f.level} onChange={set('level')} />
        </div>
        <Input label="Descrição" multiline rows={2} placeholder="Pontos-chave, erros comuns…" value={f.desc} onChange={set('desc')} />
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', marginBottom: 8 }}>Visível para</div>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>{TURMAS.map((t) => <Checkbox key={t} checked={f.turmas.includes(t)} onChange={() => toggle(t)} label={t} />)}</div>
        </div>
      </div>
    </Dialog>
  );
}

function ContentPage({ role, toast }) {
  const [items, setItems] = React.useState(A.content);
  const [cat, setCat] = React.useState('Todas');
  const [view, setView] = React.useState('grade');
  const [form, setForm] = React.useState(null);
  const [del, setDel] = React.useState(null);
  const [q, setQ] = React.useState('');
  const sync = (l) => { A.content = l; setItems(l); };
  const cats = ['Todas', ...new Set(items.map((c) => c.cat))];
  const list = items.filter((c) => (cat === 'Todas' || c.cat === cat) && c.title.toLowerCase().includes(q.toLowerCase()));
  const save = (f) => {
    if (f.id) { sync(items.map((x) => (x.id === f.id ? f : x))); toast(f.status === 'publicado' ? 'Técnica atualizada' : 'Técnica salva como rascunho'); }
    else { sync([{ ...f, id: 'v' + Date.now(), dur: '7:15' }, ...items]); toast(f.status === 'publicado' ? 'Técnica publicada' : 'Rascunho salvo'); }
    setForm(null);
  };
  const remove = () => { sync(items.filter((x) => x.id !== del.id)); toast(`"${del.title}" excluída`); setDel(null); };
  const Actions = ({ c }) => (
    <div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
      <IconButton icon="pencil" label="Editar" size="sm" onClick={() => setForm(c)} />
      <IconButton icon="trash-2" label="Excluir" size="sm" onClick={() => setDel(c)} />
    </div>
  );
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <Input iconLeft="search" placeholder="Buscar técnica" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 260 }} />
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{cats.map((c) => <Chip key={c} selected={cat === c} onClick={() => setCat(c)}>{c}</Chip>)}</div>
        <div style={{ flex: 1 }} />
        <SegmentedControl size="sm" options={[{ value: 'grade', label: 'Grade', icon: 'layout-grid' }, { value: 'lista', label: 'Lista', icon: 'list' }]} value={view} onChange={setView} />
        <Button iconLeft="upload" onClick={() => setForm(BLANK)}>Nova técnica</Button>
      </div>
      {list.length === 0 ? <Card><EmptyState icon="circle-play" title="Nenhuma técnica encontrada" description="Ajuste a busca ou publique um novo vídeo." action={<Button variant="secondary" iconLeft="upload" onClick={() => setForm(BLANK)}>Nova técnica</Button>} /></Card> : view === 'grade' ? (
        <Grid cols="repeat(auto-fill, minmax(240px, 1fr))">
          {list.map((c) => (
            <Card key={c.id} padding={0} style={{ overflow: 'hidden' }}>
              <Photo ratio="16/9" radius="0" placeholder="Professor demonstrando técnica" scrim="bottom">
                <span style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6 }}><Badge size="sm" tone="dark">{c.mod}</Badge>{c.status === 'rascunho' ? <Badge size="sm" tone="warning">Rascunho</Badge> : null}</span>
                <span style={{ position: 'absolute', right: 10, bottom: 10, fontSize: 12, fontWeight: 600, color: '#fff' }}>{c.dur}</span>
                <span style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)', width: 44, height: 44, borderRadius: '50%', background: 'var(--brand-primary)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="play" size={18} /></span>
              </Photo>
              <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>{c.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{c.cat} · Prof. {c.prof.split(' ')[0]}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                  <Badge size="sm" tone={LV[c.level]}>{c.level}</Badge>
                  <span style={{ fontSize: 12, color: 'var(--text-muted)', display: 'inline-flex', gap: 4, alignItems: 'center', marginLeft: 4 }}><Icon name="eye" size={13} />{c.views}</span>
                  <span style={{ flex: 1 }} /><Actions c={c} />
                </div>
              </div>
            </Card>
          ))}
        </Grid>
      ) : (
        <Card padding={0} style={{ overflow: 'hidden' }}>
          <DataTable rows={list} columns={[
            { key: 'title', label: 'Técnica', render: (r) => <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}><Photo ratio="16/9" radius="8px" placeholder="" style={{ width: 64 }} /><div><div style={{ fontWeight: 600, color: 'var(--text-strong)' }}>{r.title}</div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{r.cat} · {r.dur}</div></div></div> },
            { key: 'mod', label: 'Modalidade', render: (r) => <Badge>{r.mod}</Badge> },
            { key: 'level', label: 'Nível', render: (r) => <Badge tone={LV[r.level]}>{r.level}</Badge> },
            { key: 'turmas', label: 'Visível para', render: (r) => <span style={{ fontSize: 13 }}>{r.turmas.join(', ')}</span> },
            { key: 'status', label: 'Status', render: (r) => r.status === 'publicado' ? <Badge tone="success" dot>Publicado</Badge> : <Badge tone="warning" dot>Rascunho</Badge> },
            { key: 'a', label: '', align: 'right', render: (r) => <Actions c={r} /> },
          ]} />
        </Card>
      )}
      {form ? <ContentForm item={form} onClose={() => setForm(null)} onSave={save} /> : null}
      {del ? (
        <Dialog open title="Excluir técnica?" description={`"${del.title}" sai da biblioteca dos alunos. Essa ação não pode ser desfeita.`} onClose={() => setDel(null)} width={440}
          footer={<><Button variant="secondary" onClick={() => setDel(null)}>Cancelar</Button><Button iconLeft="trash-2" onClick={remove}>Excluir</Button></>} />
      ) : null}
    </div>
  );
}

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