/* ============================================================
   CAPITALIZE HUB — ADMIN  (ch-admin.jsx)
   CMS completo com autenticação JWT e REST API
   ============================================================ */

const COLOR_OPTIONS = ['#4d5bf9', '#2ecc71', '#f5c542', '#e07845', '#e74c3c', '#141221'];

/* ── API helper ──────────────────────────────────────────── */
async function apiCall(method, path, body) {
  const token = localStorage.getItem('ch_token');
  const opts = {
    method,
    headers: { 'Content-Type': 'application/json' },
  };
  if (token) opts.headers['Authorization'] = 'Bearer ' + token;
  if (body) opts.body = JSON.stringify(body);
  const res = await fetch('/api/' + path.replace(/^\//, ''), opts);
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Erro desconhecido' }));
    throw new Error(err.error || err.message || 'Erro ' + res.status);
  }
  if (res.status === 204) return null;
  return res.json();
}

/* ── Admin Page (manages login state) ─────────────────────── */
function AdminPage({ onNavigate }) {
  const [loggedIn, setLoggedIn] = React.useState(!!localStorage.getItem('ch_token'));
  const [userRole, setUserRole] = React.useState(null);

  const handleLogin = (token, role) => {
    localStorage.setItem('ch_token', token);
    setUserRole(role || null);
    setLoggedIn(true);
  };

  const handleLogout = () => {
    localStorage.removeItem('ch_token');
    setLoggedIn(false);
    setUserRole(null);
  };

  if (!loggedIn) return <LoginScreen onLogin={handleLogin} onBack={() => onNavigate && onNavigate('landing')} />;
  return <AdminPanel onLogout={handleLogout} onNavigate={onNavigate} userRole={userRole} />;
}

/* ── Login Screen ─────────────────────────────────────────── */
function LoginScreen({ onLogin, onBack }) {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const data = await apiCall('POST', 'auth/login', { email, password: pass });
      onLogin(data.token, data.role || data.user?.role);
    } catch (err) {
      setError(err.message || 'Falha ao fazer login');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'var(--bg-dark)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 24,
    }}>
      {/* Logo */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 32 }}>
        <div style={{ width: 24, height: 28 }}><Icons.logoLight /></div>
        <span style={{ fontSize: '1.05rem', fontWeight: 700, color: 'rgba(240,235,225,.7)', letterSpacing: '-.02em' }}>
          Capitalize <span style={{ fontWeight: 400, opacity: .5 }}>Hub</span>
        </span>
      </div>

      {/* Card */}
      <form onSubmit={handleSubmit} style={{
        background: '#fff',
        borderRadius: 'var(--r-lg)',
        padding: '36px 40px',
        width: '100%',
        maxWidth: 420,
      }}>
        <h2 style={{ fontSize: '1.45rem', marginBottom: 6, color: 'var(--text)' }}>Área administrativa</h2>
        <p style={{ fontSize: '.85rem', color: 'var(--text-muted)', marginBottom: 28 }}>
          Acesso para gerenciar categorias e vídeos.
        </p>

        {error && (
          <div style={{
            background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 'var(--r-sm)',
            padding: '10px 14px', fontSize: '.82rem', color: '#dc2626', marginBottom: 16,
          }}>
            {error}
          </div>
        )}

        <label style={{ fontSize: '.8rem', fontWeight: 600, color: 'var(--text)', display: 'block', marginBottom: 6 }}>E-mail</label>
        <input
          className="input"
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
          placeholder="admin@capitalizehub.com.br"
          style={{ marginBottom: 18, background: '#fff', border: '1.5px solid var(--border)' }}
        />

        <label style={{ fontSize: '.8rem', fontWeight: 600, color: 'var(--text)', display: 'block', marginBottom: 6 }}>Senha</label>
        <input
          className="input"
          type="password"
          value={pass}
          onChange={e => setPass(e.target.value)}
          placeholder="••••••••"
          style={{ marginBottom: 24, background: '#fff', border: '1.5px solid var(--border)' }}
        />

        <button type="submit" className="btn btn-primary" disabled={loading} style={{ width: '100%', borderRadius: 'var(--r-sm)', padding: '12px', opacity: loading ? 0.7 : 1 }}>
          {loading ? 'Entrando...' : 'Entrar'}
        </button>

        <p style={{
          textAlign: 'center', marginTop: 16, fontSize: '.7rem',
          fontFamily: "'Geist Mono', monospace", color: 'var(--text-muted)', letterSpacing: '.04em',
        }}>
          Acesso restrito
        </p>
      </form>

      {/* Back link */}
      <button
        onClick={onBack}
        style={{
          marginTop: 32, background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: "'Geist Mono', monospace", fontSize: '.7rem', fontWeight: 600,
          color: 'rgba(240,235,225,.3)', letterSpacing: '.1em', textTransform: 'uppercase',
        }}
      >
        ← Voltar ao site
      </button>
    </div>
  );
}

/* ── Admin Panel ──────────────────────────────────────────── */
function AdminPanel({ onLogout, onNavigate, userRole }) {
  const [tab, setTab] = React.useState('videos');
  const [categories, setCategories] = React.useState([]);
  const [videos, setVideos] = React.useState([]);
  const [products, setProducts] = React.useState([]);
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  const fetchAll = () => {
    setLoading(true);
    Promise.all([
      apiCall('GET', 'videos').catch(() => []),
      apiCall('GET', 'categories').catch(() => []),
      apiCall('GET', 'products').catch(() => []),
      apiCall('GET', 'users').catch(() => []),
    ]).then(([vids, cats, prods, usrs]) => {
      setVideos(Array.isArray(vids) ? vids : []);
      setCategories(Array.isArray(cats) ? cats : []);
      setProducts(Array.isArray(prods) ? prods : []);
      setUsers(Array.isArray(usrs) ? usrs : []);
    }).finally(() => setLoading(false));
  };

  React.useEffect(() => { fetchAll(); }, []);

  const handleSeed = async () => {
    try {
      await apiCall('POST', 'seed');
      fetchAll();
    } catch (err) {
      alert('Erro ao restaurar: ' + err.message);
    }
  };

  const isSuperAdmin = userRole === 'superadmin';

  const tabs = [
    { id: 'videos', label: 'Vídeos', count: videos.length },
    { id: 'categories', label: 'Categorias', count: categories.length },
    { id: 'products', label: 'Produtos', count: products.length },
  ];
  if (isSuperAdmin) {
    tabs.push({ id: 'users', label: 'Usuários', count: users.length });
  }

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)' }}>
      {/* Admin Navbar */}
      <nav className="navbar" style={{ background: 'var(--bg-dark)', borderBottom: 'none' }}>
        <div className="navbar-left">
          <div className="navbar-logo">
            <div style={{ width: 24, height: 28 }}><Icons.logoLight /></div>
            <span style={{ color: '#fff' }}>Capitalize <em style={{ opacity: .5 }}>Hub</em></span>
          </div>
          <span style={{
            fontFamily: "'Geist Mono', monospace", fontSize: '.6rem', fontWeight: 700,
            letterSpacing: '.1em', color: 'rgba(255,255,255,.4)', background: 'rgba(255,255,255,.08)',
            padding: '3px 8px', borderRadius: 4, textTransform: 'uppercase',
          }}>Admin</span>
        </div>
        <div className="navbar-right">
          <button className="btn btn-outline btn-sm" style={{ borderColor: 'rgba(255,255,255,.15)', color: '#fff' }}
            onClick={() => onNavigate && onNavigate('landing')}>
            Ver site ↗
          </button>
          <button className="btn btn-outline btn-sm" style={{ borderColor: 'rgba(255,255,255,.15)', color: '#fff' }}
            onClick={onLogout}>
            Sair
          </button>
        </div>
      </nav>

      {/* Content */}
      <div className="container" style={{ paddingTop: 40, paddingBottom: 60 }}>
        {/* Header */}
        <div className="flex items-center justify-between" style={{ marginBottom: 28, flexWrap: 'wrap', gap: 12 }}>
          <h2 style={{ fontSize: '1.6rem' }}>Conteúdo</h2>
          <button className="btn btn-outline btn-sm" onClick={handleSeed}>↻ Restaurar demo</button>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 24, borderBottom: '1.5px solid var(--border)', marginBottom: 32 }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              fontSize: '.85rem', fontWeight: tab === t.id ? 700 : 500,
              color: tab === t.id ? 'var(--text)' : 'var(--text-muted)',
              paddingBottom: 12, borderBottom: tab === t.id ? '2px solid var(--text)' : '2px solid transparent',
              marginBottom: -1.5,
            }}>
              {t.label} <span style={{ fontFamily: "'Geist Mono',monospace", fontSize: '.7rem', opacity: .5, marginLeft: 4 }}>{t.count}</span>
            </button>
          ))}
        </div>

        {/* Tab content */}
        {loading ? (
          <p style={{ color: 'var(--text-muted)', textAlign: 'center', padding: 40 }}>Carregando...</p>
        ) : (
          <React.Fragment>
            {tab === 'videos' && <VideosTab videos={videos} categories={categories} onRefresh={fetchAll} />}
            {tab === 'categories' && <CategoriesTab categories={categories} videos={videos} onRefresh={fetchAll} />}
            {tab === 'products' && <ProductsTab products={products} onRefresh={fetchAll} />}
            {tab === 'users' && isSuperAdmin && <UsersTab users={users} onRefresh={fetchAll} />}
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

/* ── Videos Tab ───────────────────────────────────────────── */
function VideosTab({ videos, categories, onRefresh }) {
  const [url, setUrl] = React.useState('');
  const [title, setTitle] = React.useState('');
  const [catId, setCatId] = React.useState(categories[0]?.id || '');
  const [desc, setDesc] = React.useState('');
  const [attachments, setAttachments] = React.useState([]);
  const [attachInput, setAttachInput] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const extractThumb = (videoUrl) => {
    try {
      const u = new URL(videoUrl);
      let vid = u.searchParams.get('v');
      if (!vid && u.hostname.includes('youtu.be')) vid = u.pathname.slice(1);
      if (vid) return `https://i.ytimg.com/vi/${vid}/hqdefault.jpg`;
    } catch {}
    return '';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!url || !title) return;
    setSaving(true);
    try {
      await apiCall('POST', 'videos', {
        url, title, catId: Number(catId), desc,
        thumb: extractThumb(url),
        source: url.includes('vimeo') ? 'vimeo' : 'youtube',
        attachments: [...attachments],
      });
      setUrl(''); setTitle(''); setDesc(''); setAttachments([]);
      onRefresh();
    } catch (err) {
      alert('Erro ao publicar vídeo: ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (id) => {
    try {
      await apiCall('DELETE', 'videos/' + id);
      onRefresh();
    } catch (err) {
      alert('Erro ao excluir: ' + err.message);
    }
  };

  const addAttach = () => {
    if (attachInput.trim()) {
      setAttachments(prev => [...prev, attachInput.trim()]);
      setAttachInput('');
    }
  };

  const getCatName = (id) => categories.find(c => c.id === id)?.name || '—';

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'flex-start' }}>
      {/* Form */}
      <form onSubmit={handleSubmit} className="card" style={{ background: '#fff' }}>
        <h3 style={{ fontSize: '1.05rem', marginBottom: 20 }}>Anexar vídeo</h3>

        <FieldLabel>Link do YouTube ou Vimeo</FieldLabel>
        <input className="input" placeholder="https://youtube.com/watch?v=..." value={url} onChange={e => setUrl(e.target.value)} style={{ marginBottom: 16 }} />

        <FieldLabel>Título</FieldLabel>
        <input className="input" placeholder="Título do vídeo" value={title} onChange={e => setTitle(e.target.value)} style={{ marginBottom: 16 }} />

        <FieldLabel>Categoria</FieldLabel>
        <select className="input" value={catId} onChange={e => setCatId(e.target.value)} style={{ marginBottom: 16, cursor: 'pointer' }}>
          {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>

        <FieldLabel>Descrição</FieldLabel>
        <textarea className="input" placeholder="Sobre o vídeo" rows={3} value={desc} onChange={e => setDesc(e.target.value)} style={{ marginBottom: 16, resize: 'vertical' }} />

        <FieldLabel>Anexos (PDF, planilha)</FieldLabel>
        <div className="flex gap-sm" style={{ marginBottom: 20 }}>
          <input className="input" placeholder="Ex: Apresentação.pdf" value={attachInput} onChange={e => setAttachInput(e.target.value)} style={{ flex: 1 }} />
          <button type="button" className="btn btn-outline btn-sm" onClick={addAttach}>+ Add</button>
        </div>
        {attachments.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16 }}>
            {attachments.map((a, i) => (
              <span key={i} className="badge" style={{ cursor: 'pointer' }} onClick={() => setAttachments(prev => prev.filter((_, j) => j !== i))}>
                📎 {a} ×
              </span>
            ))}
          </div>
        )}

        <button type="submit" className="btn btn-primary" disabled={saving} style={{ width: '100%', borderRadius: 'var(--r-sm)', padding: '12px', opacity: saving ? 0.7 : 1 }}>
          {saving ? 'Publicando...' : '+ Publicar vídeo'}
        </button>
      </form>

      {/* Video list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {videos.map(v => (
          <div key={v.id} className="card" style={{ background: '#fff', padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
            <img
              src={v.thumb}
              alt={v.title}
              style={{ width: 80, height: 52, objectFit: 'cover', borderRadius: 6, flexShrink: 0, background: 'var(--border)' }}
            />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: '.88rem', color: 'var(--text)', marginBottom: 4 }}>{v.title}</div>
              <div style={{ fontFamily: "'Geist Mono',monospace", fontSize: '.6rem', color: 'var(--text-muted)', letterSpacing: '.02em' }}>
                <span style={{ color: 'var(--brand)' }}>{getCatName(v.catId || v.category_id)}</span>
                {' · '}{v.source}
                {(v.attachments || []).length > 0 && <span> · {v.attachments.length} anexo{v.attachments.length > 1 ? 's' : ''}</span>}
              </div>
            </div>
            <button className="btn btn-outline btn-sm" onClick={() => handleRemove(v.id)}>Excluir</button>
          </div>
        ))}
        {videos.length === 0 && (
          <p style={{ color: 'var(--text-muted)', fontSize: '.85rem', padding: 20 }}>Nenhum vídeo publicado.</p>
        )}
      </div>

      <style>{`@media(max-width:768px){.admin-main>div>div:first-child{grid-template-columns:1fr!important;}}`}</style>
    </div>
  );
}

/* ── Categories Tab ───────────────────────────────────────── */
function CategoriesTab({ categories, videos, onRefresh }) {
  const [name, setName] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [color, setColor] = React.useState(COLOR_OPTIONS[0]);
  const [saving, setSaving] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    setSaving(true);
    try {
      await apiCall('POST', 'categories', { name: name.trim(), desc, color });
      setName(''); setDesc('');
      onRefresh();
    } catch (err) {
      alert('Erro ao criar categoria: ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (id) => {
    try {
      await apiCall('DELETE', 'categories/' + id);
      onRefresh();
    } catch (err) {
      alert('Erro ao excluir: ' + err.message);
    }
  };

  const countVideos = (catId) => videos.filter(v => (v.catId || v.category_id) === catId).length;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'flex-start' }}>
      {/* Form */}
      <form onSubmit={handleSubmit} className="card" style={{ background: '#fff' }}>
        <h3 style={{ fontSize: '1.05rem', marginBottom: 20 }}>Nova categoria</h3>

        <FieldLabel>Nome</FieldLabel>
        <input className="input" placeholder="Ex: Construção & Obras" value={name} onChange={e => setName(e.target.value)} style={{ marginBottom: 16 }} />

        <FieldLabel>Descrição</FieldLabel>
        <textarea className="input" placeholder="Sobre o que é esta categoria" rows={3} value={desc} onChange={e => setDesc(e.target.value)} style={{ marginBottom: 16, resize: 'vertical' }} />

        <FieldLabel>Cor de destaque</FieldLabel>
        <div className="flex gap-sm" style={{ marginBottom: 24 }}>
          {COLOR_OPTIONS.map(c => (
            <button
              type="button"
              key={c}
              onClick={() => setColor(c)}
              style={{
                width: 28, height: 28, borderRadius: '50%', background: c, border: 'none', cursor: 'pointer',
                outline: color === c ? '2.5px solid var(--text)' : '2px solid transparent',
                outlineOffset: 2, transition: 'outline .15s',
              }}
            />
          ))}
        </div>

        <button type="submit" className="btn btn-primary" disabled={saving} style={{ width: '100%', borderRadius: 'var(--r-sm)', padding: '12px', opacity: saving ? 0.7 : 1 }}>
          {saving ? 'Criando...' : '+ Criar categoria'}
        </button>
      </form>

      {/* Category list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {categories.map(c => (
          <div key={c.id} className="card" style={{ background: '#fff', padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 12, height: 12, borderRadius: '50%', background: c.color, flexShrink: 0 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: '.88rem', color: 'var(--text)' }}>{c.name}</div>
              <div style={{ fontFamily: "'Geist Mono',monospace", fontSize: '.6rem', color: 'var(--text-muted)', letterSpacing: '.02em' }}>
                {c.slug} · {countVideos(c.id)} vídeo{countVideos(c.id) !== 1 ? 's' : ''}
              </div>
            </div>
            <button className="btn btn-outline btn-sm" onClick={() => handleRemove(c.id)}>Excluir</button>
          </div>
        ))}
        {categories.length === 0 && (
          <p style={{ color: 'var(--text-muted)', fontSize: '.85rem', padding: 20 }}>Nenhuma categoria criada.</p>
        )}
      </div>
    </div>
  );
}

/* ── Products Tab ─────────────────────────────────────────── */
function ProductsTab({ products, onRefresh }) {
  const statusLabels = { disponivel: 'Disponível', breve: 'Em breve' };
  const statusBadge = { disponivel: 'badge-green', breve: 'badge-amber' };

  const [localLinks, setLocalLinks] = React.useState({});
  const [saveStatus, setSaveStatus] = React.useState({});
  const debounceTimers = React.useRef({});

  const handleLinkChange = (key, value) => {
    setLocalLinks(prev => ({ ...prev, [key]: value }));

    if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key]);
    debounceTimers.current[key] = setTimeout(async () => {
      try {
        await apiCall('PUT', 'products/' + key, { redirect_url: value });
        setSaveStatus(prev => ({ ...prev, [key]: 'saved' }));
        setTimeout(() => setSaveStatus(prev => ({ ...prev, [key]: '' })), 2000);
      } catch (err) {
        setSaveStatus(prev => ({ ...prev, [key]: 'error' }));
      }
    }, 800);
  };

  return (
    <div style={{ maxWidth: 640 }}>
      <p style={{ fontSize: '.85rem', color: 'var(--text-muted)', marginBottom: 24 }}>
        Configure o link de redirecionamento de cada produto. Quando o visitante clicar no card do produto na página inicial, será direcionado para o endereço configurado.
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {products.map(p => {
          const productKey = p.key || p.id;
          const linkVal = localLinks[productKey] !== undefined ? localLinks[productKey] : (p.redirect_url || p.link || '');
          const status = saveStatus[productKey];

          return (
            <div key={productKey} className="card" style={{ background: '#fff' }}>
              <div className="flex items-center justify-between" style={{ marginBottom: 14 }}>
                <div className="flex items-center gap-sm">
                  <h3 style={{ fontSize: '1rem' }}>{p.name}</h3>
                </div>
                <span className={`badge ${statusBadge[p.status] || ''}`}>{statusLabels[p.status] || p.status}</span>
              </div>

              <FieldLabel>Link de redirecionamento</FieldLabel>
              <input
                className="input"
                placeholder={p.status === 'disponivel' ? 'https://app.capitalizehub.com.br/construcao' : 'Deixe vazio para "Em breve"'}
                value={linkVal}
                onChange={e => handleLinkChange(productKey, e.target.value)}
                style={{ marginBottom: 8 }}
              />
              <p style={{ fontSize: '.7rem', color: status === 'saved' ? 'var(--green-text)' : status === 'error' ? '#dc2626' : 'var(--text-muted)', margin: 0, fontFamily: "'Geist Mono',monospace" }}>
                {status === 'saved' ? '✓ Salvo com sucesso' : status === 'error' ? '✗ Erro ao salvar' : linkVal ? '🔗 Ativo — clique no card redireciona para: ' + linkVal : '⏸ Sem link — card não redireciona'}
              </p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Users Tab (superadmin only) ──────────────────────────── */
function UsersTab({ users, onRefresh }) {
  const [email, setEmail] = React.useState('');
  const [name, setName] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email.trim() || !name.trim() || !password.trim()) return;
    setSaving(true);
    try {
      await apiCall('POST', 'users', { email: email.trim(), name: name.trim(), password });
      setEmail(''); setName(''); setPassword('');
      onRefresh();
    } catch (err) {
      alert('Erro ao criar usuário: ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleRemove = async (id) => {
    if (!confirm('Remover este administrador?')) return;
    try {
      await apiCall('DELETE', 'users/' + id);
      onRefresh();
    } catch (err) {
      alert('Erro ao remover: ' + err.message);
    }
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'flex-start' }}>
      {/* Form */}
      <form onSubmit={handleSubmit} className="card" style={{ background: '#fff' }}>
        <h3 style={{ fontSize: '1.05rem', marginBottom: 20 }}>Novo administrador</h3>

        <FieldLabel>Nome</FieldLabel>
        <input className="input" placeholder="Nome completo" value={name} onChange={e => setName(e.target.value)} style={{ marginBottom: 16 }} />

        <FieldLabel>E-mail</FieldLabel>
        <input className="input" type="email" placeholder="email@exemplo.com" value={email} onChange={e => setEmail(e.target.value)} style={{ marginBottom: 16 }} />

        <FieldLabel>Senha</FieldLabel>
        <input className="input" type="password" placeholder="Mínimo 6 caracteres" value={password} onChange={e => setPassword(e.target.value)} style={{ marginBottom: 24 }} />

        <button type="submit" className="btn btn-primary" disabled={saving} style={{ width: '100%', borderRadius: 'var(--r-sm)', padding: '12px', opacity: saving ? 0.7 : 1 }}>
          {saving ? 'Criando...' : '+ Criar administrador'}
        </button>
      </form>

      {/* User list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {users.map(u => (
          <div key={u.id} className="card" style={{ background: '#fff', padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 36, height: 36, borderRadius: '50%', background: 'var(--brand)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: '.82rem', fontWeight: 700, flexShrink: 0,
            }}>
              {(u.name || u.email || '?').charAt(0).toUpperCase()}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: '.88rem', color: 'var(--text)' }}>{u.name || '—'}</div>
              <div style={{ fontFamily: "'Geist Mono',monospace", fontSize: '.6rem', color: 'var(--text-muted)', letterSpacing: '.02em' }}>
                {u.email}
                {u.role && <span> · {u.role}</span>}
              </div>
            </div>
            <button className="btn btn-outline btn-sm" onClick={() => handleRemove(u.id)}>Excluir</button>
          </div>
        ))}
        {users.length === 0 && (
          <p style={{ color: 'var(--text-muted)', fontSize: '.85rem', padding: 20 }}>Nenhum usuário cadastrado.</p>
        )}
      </div>
    </div>
  );
}

/* ── Field Label helper ───────────────────────────────────── */
function FieldLabel({ children }) {
  return (
    <label style={{ display: 'block', fontSize: '.78rem', fontWeight: 600, color: 'var(--text)', marginBottom: 6 }}>
      {children}
    </label>
  );
}
