// ============================================================
// ADMIN — Login + Dashboard (list, search, filter, manage)
// ============================================================

function AdminApp({ route, navigate }) {
  const [session, setSession] = useState(() => api.getSession());

  if (!session) return <Login onLogin={(s) => setSession(s)} />;

  const sub = route.parts[1]; // 'edit' | 'new' | 'categorias' | undefined
  const id  = route.parts[2];

  let view = null;
  if (sub === 'novo')        view = <Editor onDone={() => navigate('#/admin')} />;
  else if (sub === 'editar') view = <Editor id={id} onDone={() => navigate('#/admin')} />;
  else if (sub === 'categorias') view = <CategoriesManager />;
  else                       view = <Dashboard />;

  return (
    <div className="admin-shell">
      <AdminBar
        user={session.user}
        active={sub}
        onLogout={() => { api.logout(); setSession(null); navigate('#/admin'); }}
      />
      <main className="admin-main">{view}</main>
    </div>
  );
}

// ---------- Login (single password gate) ----------
function Login({ onLogin }) {
  const [pw, setPw] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const [show, setShow] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const s = await api.login(pw);
      onLogin(s);
    } catch (e) {
      setErr(e.message);
      setPw('');
    } finally { setBusy(false); }
  };

  return (
    <div className="login-shell">
      <form className="login-card" onSubmit={submit}>
        <div className="login-mark">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <rect x="5" y="11" width="14" height="10" rx="2" />
            <path d="M8 11V7a4 4 0 0 1 8 0v4" />
          </svg>
        </div>
        <div className="logo">Angelo Santos</div>
        <div className="logo-sub">Painel Editorial</div>
        <h2>Acesso restrito</h2>
        <p>Informe a senha para gerenciar as publicações.</p>

        <label>Senha de acesso</label>
        <div className={`pw-field ${err ? 'has-error' : ''}`}>
          <input
            type={show ? 'text' : 'password'}
            value={pw}
            onChange={e => { setPw(e.target.value); setErr(''); }}
            autoFocus
            required
            autoComplete="current-password"
            placeholder="••••••••"
          />
          <button type="button" className="pw-toggle" onClick={() => setShow(s => !s)} title={show ? 'Ocultar' : 'Mostrar'}>
            {show ? <Icon.eyeOff /> : <Icon.eye />}
          </button>
        </div>

        {err && (
          <div className="login-err">
            <Icon.alert /> {err}
          </div>
        )}

        <button className="submit" type="submit" disabled={busy || !pw}>
          {busy ? 'Verificando…' : 'Entrar no painel'}
        </button>

        <div className="hint">
          Sessão válida por 8 horas neste dispositivo.
        </div>
      </form>

      <a href="#/" className="login-back">← Voltar ao blog</a>
    </div>
  );
}

// ---------- AdminBar ----------
function AdminBar({ user, active, onLogout }) {
  return (
    <header className="admin-bar">
      <div className="brand">
        Angelo Santos
        <small>Painel Editorial</small>
      </div>
      <nav>
        <a href="#/admin" className={!active ? 'active' : ''}>Artigos</a>
        <a href="#/admin/categorias" className={active === 'categorias' ? 'active' : ''}>Editorias</a>
        <a href="#/" target="_blank">Ver site ↗</a>
      </nav>
      <div className="actions">
        <span className="user">olá, <strong style={{ color: 'var(--paper)' }}>{user}</strong></span>
        <button className="logout" onClick={onLogout}>Sair</button>
      </div>
    </header>
  );
}

// ---------- Dashboard ----------
function Dashboard() {
  const [articles, setArticles] = useState([]);
  const [filter, setFilter] = useState('all');
  const [q, setQ] = useState('');
  const [toast, setToast] = useState('');
  const [confirmDel, setConfirmDel] = useState(null);

  const reload = () => api.listArticles().then(setArticles);
  useEffect(() => { reload(); }, []);

  const filtered = useMemo(() => {
    let a = articles;
    if (filter !== 'all') a = a.filter(x => x.status === filter);
    if (q) {
      const n = q.toLowerCase();
      a = a.filter(x => (x.title || '').toLowerCase().includes(n)
                     || (x.subtitle || '').toLowerCase().includes(n));
    }
    return a;
  }, [articles, filter, q]);

  const counts = useMemo(() => ({
    all: articles.length,
    published: articles.filter(a => a.status === 'published').length,
    draft: articles.filter(a => a.status === 'draft').length,
    scheduled: articles.filter(a => a.status === 'scheduled').length,
  }), [articles]);

  const onDelete = async (id) => {
    await api.deleteArticle(id);
    setConfirmDel(null);
    setToast('Artigo excluído.');
    reload();
  };

  const onExport = () => {
    const data = api.exportData();
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `angelo-santos-blog-${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
    setToast('Backup exportado.');
  };

  const importRef = useRef(null);
  const onImport = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {
      try {
        await api.importData(reader.result, { merge: true });
        setToast('Publicações importadas.');
        reload();
      } catch (e) {
        setToast('Arquivo inválido.');
      }
    };
    reader.readAsText(file);
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 className="admin-h1">Sala de redação</h1>
          <p className="admin-sub">{counts.all} artigos · {counts.published} publicados · {counts.draft} rascunhos · {counts.scheduled} agendados</p>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button className="btn-ghost" onClick={onExport} title="Baixar um backup de todas as publicações">
            <Icon.download /> &nbsp;Backup
          </button>
          <button className="btn-ghost" onClick={() => importRef.current?.click()} title="Restaurar de um backup">
            <Icon.upload /> &nbsp;Importar
          </button>
          <input ref={importRef} type="file" accept="application/json,.json" hidden onChange={e => { onImport(e.target.files?.[0]); e.target.value = ''; }} />
          <a href="#/admin/novo" className="btn-primary">
            <Icon.plus /> Novo artigo
          </a>
        </div>
      </div>

      <div className="admin-toolbar">
        <div className="search">
          <Icon.search />
          <input
            type="search"
            placeholder="Buscar por título, subtítulo ou tag…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
        </div>
        <div className="filter">
          <button className={filter === 'all' ? 'active' : ''} onClick={() => setFilter('all')}>
            Todos · {counts.all}
          </button>
          <button className={filter === 'published' ? 'active' : ''} onClick={() => setFilter('published')}>
            Publicados · {counts.published}
          </button>
          <button className={filter === 'draft' ? 'active' : ''} onClick={() => setFilter('draft')}>
            Rascunhos · {counts.draft}
          </button>
          <button className={filter === 'scheduled' ? 'active' : ''} onClick={() => setFilter('scheduled')}>
            Agendados · {counts.scheduled}
          </button>
        </div>
      </div>

      <div className="list">
        <div className="list-row header">
          <div>Capa</div>
          <div>Título</div>
          <div className="col-cat">Editoria</div>
          <div>Status</div>
          <div>Data</div>
          <div style={{ textAlign: 'right' }}>Ações</div>
        </div>

        {filtered.length === 0 ? (
          <div className="empty">Nenhum artigo encontrado para os filtros atuais.</div>
        ) : filtered.map(a => {
          const cat = categoryById(a.category);
          return (
            <div className="list-row" key={a.id}>
              <div className="thumb">
                {a.cover ? <img src={a.cover} alt="" /> : null}
              </div>
              <div className="title">
                {a.title}
                {a.subtitle && <small>{a.subtitle}</small>}
              </div>
              <div className="col-cat" style={{
                fontFamily: 'var(--sans)', fontSize: 12,
                color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.08em'
              }}>{cat?.name}</div>
              <div>
                <span className={`badge ${a.status}`}>
                  {a.status === 'published' ? 'Publicado' :
                   a.status === 'scheduled' ? 'Agendado' : 'Rascunho'}
                </span>
              </div>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-3)' }}>
                {a.status === 'scheduled'
                  ? fmtDate(a.scheduledFor)
                  : a.status === 'published'
                  ? fmtDate(a.publishedAt)
                  : `atualizado ${fmtDate(a.updatedAt || a.createdAt)}`}
              </div>
              <div className="row-actions">
                {a.status === 'published' && (
                  <a href={`#/artigo/${a.slug}`} target="_blank" title="Ver no site">
                    <button title="Ver"><Icon.eye /></button>
                  </a>
                )}
                <a href={`#/admin/editar/${a.id}`} title="Editar">
                  <button><Icon.edit /></button>
                </a>
                <button className="danger" title="Excluir" onClick={() => setConfirmDel(a)}>
                  <Icon.trash />
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {confirmDel && (
        <ConfirmModal
          title="Excluir artigo?"
          message={`"${confirmDel.title}" será removido permanentemente. Esta ação não pode ser desfeita.`}
          onCancel={() => setConfirmDel(null)}
          onConfirm={() => onDelete(confirmDel.id)}
        />
      )}

      <Toast message={toast} onDone={() => setToast('')} />
    </div>
  );
}

// ---------- Confirm modal ----------
function ConfirmModal({ title, message, onCancel, onConfirm }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(20,23,28,0.7)',
      zIndex: 100, display: 'grid', placeItems: 'center'
    }}>
      <div style={{
        background: 'var(--paper)', maxWidth: 420, padding: 28,
        border: '1px solid var(--rule)',
        boxShadow: '0 20px 60px rgba(0,0,0,0.4)'
      }}>
        <h3 style={{ fontFamily: 'var(--display)', fontSize: 24, margin: 0, fontWeight: 400 }}>{title}</h3>
        <p style={{
          fontFamily: 'var(--serif)', fontSize: 15, color: 'var(--ink-2)',
          margin: '12px 0 24px', lineHeight: 1.5
        }}>{message}</p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button className="btn-ghost" onClick={onCancel}>Cancelar</button>
          <button className="btn-ghost danger" onClick={onConfirm}>Excluir</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Categories manager ----------
function CategoriesManager() {
  const [cats, setCats] = useState([]);
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState({ name: '', slug: '', blurb: '' });
  const [toast, setToast] = useState('');

  useEffect(() => { api.listCategories().then(setCats); }, []);

  const save = async (next) => {
    setCats(next);
    await api.saveCategories(next);
    setToast('Editorias atualizadas.');
  };

  const addNew = async () => {
    if (!draft.name) return;
    const slug = draft.slug || slugify(draft.name);
    const next = [...cats, { id: slug, name: draft.name, slug, blurb: draft.blurb || '' }];
    await save(next);
    setAdding(false);
    setDraft({ name: '', slug: '', blurb: '' });
  };

  const remove = async (id) => {
    const next = cats.filter(c => c.id !== id);
    await save(next);
  };

  const update = async (id, field, value) => {
    const next = cats.map(c => c.id === id ? { ...c, [field]: value } : c);
    await save(next);
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
        <div>
          <h1 className="admin-h1">Editorias</h1>
          <p className="admin-sub">Organize as seções do blog. Cada artigo pertence a uma editoria.</p>
        </div>
        {!adding && (
          <button className="btn-primary" onClick={() => setAdding(true)}>
            <Icon.plus /> Nova editoria
          </button>
        )}
      </div>

      {adding && (
        <div style={{
          background: 'var(--paper-2)', border: '1px solid var(--rule)',
          padding: 20, marginBottom: 20, display: 'grid',
          gridTemplateColumns: '1fr 1fr 2fr auto', gap: 12, alignItems: 'end'
        }}>
          <div>
            <label style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-2)', marginBottom: 6 }}>Nome</label>
            <input value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })}
              style={{ width: '100%', padding: 10, border: '1px solid var(--rule)', fontFamily: 'var(--serif)', fontSize: 14 }} />
          </div>
          <div>
            <label style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-2)', marginBottom: 6 }}>Slug (opcional)</label>
            <input value={draft.slug} onChange={e => setDraft({ ...draft, slug: e.target.value })} placeholder={slugify(draft.name)}
              style={{ width: '100%', padding: 10, border: '1px solid var(--rule)', fontFamily: 'var(--mono)', fontSize: 13 }} />
          </div>
          <div>
            <label style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-2)', marginBottom: 6 }}>Descrição curta</label>
            <input value={draft.blurb} onChange={e => setDraft({ ...draft, blurb: e.target.value })}
              style={{ width: '100%', padding: 10, border: '1px solid var(--rule)', fontFamily: 'var(--serif)', fontSize: 14 }} />
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn-ghost" onClick={() => { setAdding(false); setDraft({ name: '', slug: '', blurb: '' }); }}>Cancelar</button>
            <button className="btn-primary" onClick={addNew}>Adicionar</button>
          </div>
        </div>
      )}

      <div className="list">
        <div className="list-row header" style={{ gridTemplateColumns: '1fr 1fr 2fr 100px 130px' }}>
          <div>Nome</div><div>Slug</div><div>Descrição</div><div>Artigos</div><div style={{ textAlign: 'right' }}>Ações</div>
        </div>
        {cats.map(c => (
          <CategoryRow key={c.id} cat={c} onUpdate={(f, v) => update(c.id, f, v)} onRemove={() => remove(c.id)} />
        ))}
      </div>

      <Toast message={toast} onDone={() => setToast('')} />
    </div>
  );
}

function CategoryRow({ cat, onUpdate, onRemove }) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    api.listArticles({ category: cat.id }).then(a => setCount(a.length));
  }, [cat.id]);

  return (
    <div className="list-row" style={{ gridTemplateColumns: '1fr 1fr 2fr 100px 130px' }}>
      <div>
        <input
          defaultValue={cat.name}
          onBlur={e => e.target.value !== cat.name && onUpdate('name', e.target.value)}
          style={{ width: '100%', background: 'transparent', border: 0, fontFamily: 'var(--display)', fontSize: 18, padding: 4, outline: 0 }}
        />
      </div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-3)' }}>{cat.slug}</div>
      <div>
        <input
          defaultValue={cat.blurb}
          onBlur={e => e.target.value !== cat.blurb && onUpdate('blurb', e.target.value)}
          style={{ width: '100%', background: 'transparent', border: 0, fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 13, color: 'var(--ink-2)', padding: 4, outline: 0 }}
        />
      </div>
      <div style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-3)' }}>{count}</div>
      <div className="row-actions">
        <button className="danger" onClick={onRemove} disabled={count > 0} title={count > 0 ? 'Remova ou reatribua os artigos antes' : 'Excluir'}>
          <Icon.trash />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AdminApp, Dashboard, CategoriesManager, Login, AdminBar, ConfirmModal });
