// admin.jsx — área do vendedor: login, dashboard, CRUD form

const AUTH_KEY = "moliterni_auth_v1";

// Híbrido: no modo "api" a sessão é validada pelo servidor (session.php / login.php);
// no modo "demo" usa um flag local contra as credenciais chumbadas (ADMIN_CRED).
function useAuth(mode) {
  const [authed, setAuthed] = React.useState(false);
  const [checking, setChecking] = React.useState(true);

  React.useEffect(() => {
    if (mode === "loading") return;
    let alive = true;
    if (mode === "api") {
      fetch(API_BASE + "session.php", { credentials: "include" })
        .then((r) => r.json())
        .then((d) => { if (alive) { setAuthed(!!d.authed); setChecking(false); } })
        .catch(() => { if (alive) setChecking(false); });
    } else {
      try { setAuthed(localStorage.getItem(AUTH_KEY) === "1"); } catch (e) {}
      setChecking(false);
    }
    return () => { alive = false; };
  }, [mode]);

  const login = () => {
    if (mode === "demo") { try { localStorage.setItem(AUTH_KEY, "1"); } catch (e) {} }
    setAuthed(true);
  };
  const logout = () => {
    if (mode === "api") { fetch(API_BASE + "logout.php", { credentials: "include" }).catch(() => {}); }
    else { try { localStorage.removeItem(AUTH_KEY); } catch (e) {} }
    setAuthed(false);
  };
  return { authed, login, logout, checking };
}

// ---------- Login ----------
function AdminLogin({ onLogin, onBack, mode }) {
  const [user, setUser] = React.useState("");
  const [pass, setPass] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (mode === "api") {
      setBusy(true); setErr("");
      try {
        const r = await fetch(API_BASE + "login.php", {
          method: "POST", credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ usuario: user.trim(), senha: pass }),
        });
        const d = await r.json();
        if (r.ok && d.ok) onLogin();
        else setErr(d.erro || "Usuário ou senha incorretos.");
      } catch (e) { setErr("Falha ao conectar no servidor."); }
      finally { setBusy(false); }
    } else {
      if (user.trim() === ADMIN_CRED.user && pass === ADMIN_CRED.pass) { setErr(""); onLogin(); }
      else setErr("Usuário ou senha incorretos.");
    }
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24 }}>
      <div className="fade-in" style={{ width: "100%", maxWidth: 400 }}>
        <button onClick={onBack} className="btn btn-ghost btn-sm" style={{ marginBottom: 22 }}><IconArrowLeft size={16} /> Voltar ao site</button>
        <div className="card" style={{ padding: 30, boxShadow: "var(--shadow)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 6 }}>
            <span style={{ width: 42, height: 42, borderRadius: 12, background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center" }}><IconLock size={22} /></span>
            <div>
              <h2 style={{ fontSize: 21 }}>Área do vendedor</h2>
              <div style={{ fontSize: 13, color: "var(--muted)" }}>Moliterni Motos</div>
            </div>
          </div>
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 22 }}>
            <div className="field"><label>Usuário</label><input className="input" value={user} onChange={(e) => setUser(e.target.value)} placeholder="admin" autoFocus /></div>
            <div className="field"><label>Senha</label><input type="password" className="input" value={pass} onChange={(e) => setPass(e.target.value)} placeholder="••••••••" /></div>
            {err && <div style={{ fontSize: 13.5, color: "var(--danger)", fontWeight: 600 }}>{err}</div>}
            <button type="submit" disabled={busy} className="btn btn-primary btn-lg btn-block" style={{ marginTop: 4 }}>{busy ? "Entrando…" : <>Entrar <IconArrowRight size={18} /></>}</button>
          </form>
          {mode !== "api" && (
            <div style={{ marginTop: 20, padding: "12px 14px", borderRadius: 10, background: "var(--surface-2)", border: "1px dashed var(--border)", fontSize: 13, color: "var(--muted)" }}>
              <strong style={{ color: "var(--text)" }}>Demonstração:</strong> usuário <code style={{ color: "var(--accent)" }}>admin</code> · senha <code style={{ color: "var(--accent)" }}>demo123</code>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- Photo URL editor ----------
function PhotoEditor({ fotos, onChange, vehicle, mode }) {
  const [url, setUrl] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const fileRef = React.useRef(null);
  const add = () => { if (url.trim()) { onChange([...(fotos || []), url.trim()]); setUrl(""); } };
  const remove = (i) => onChange(fotos.filter((_, idx) => idx !== i));

  const pickFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = ""; // permite reenviar o mesmo arquivo
    if (!file) return;
    setErr("");
    if (mode === "api") {
      // envia pro servidor; o banco guarda só o caminho devolvido (fotos/xxx.jpg)
      setBusy(true);
      try {
        const fd = new FormData(); fd.append("foto", file);
        const r = await fetch(API_BASE + "upload.php", { method: "POST", credentials: "include", body: fd });
        const d = await r.json();
        if (r.ok && d.ok) onChange([...(fotos || []), d.caminho]);
        else setErr(d.erro || "Falha ao enviar a foto.");
      } catch (e) { setErr("Falha ao enviar a foto."); }
      finally { setBusy(false); }
    } else {
      // modo demo: sem servidor, guarda a imagem como data URL (fica no localStorage)
      const reader = new FileReader();
      reader.onload = () => onChange([...(fotos || []), reader.result]);
      reader.readAsDataURL(file);
    }
  };

  return (
    <div>
      <div style={{ display: "flex", gap: 8 }}>
        <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" onChange={pickFile} style={{ display: "none" }} />
        <button type="button" onClick={() => fileRef.current && fileRef.current.click()} disabled={busy} className="btn btn-primary">
          <IconCamera size={16} /> {busy ? "Enviando…" : "Enviar foto"}
        </button>
      </div>
      {err && <div style={{ fontSize: 12.5, color: "var(--danger)", fontWeight: 600, marginTop: 8 }}>{err}</div>}
      <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
        <input className="input" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="…ou cole o link de uma foto (https://…)"
          onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
        <button type="button" onClick={add} className="btn btn-ghost"><IconPlus size={16} /> Add</button>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 12 }}>
        {(fotos || []).length === 0 && (
          <div style={{ width: 110, aspectRatio: "4/3", borderRadius: 10, overflow: "hidden", position: "relative" }}>
            <VehiclePhoto vehicle={{ ...vehicle, fotos: [] }} style={{ width: "100%", height: "100%" }} rounded={false} />
          </div>
        )}
        {(fotos || []).map((f, i) => (
          <div key={i} style={{ position: "relative", width: 110, aspectRatio: "4/3", borderRadius: 10, overflow: "hidden", border: "1px solid var(--border)" }}>
            <img src={f} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={(e) => { e.target.style.opacity = .2; }} />
            <button type="button" onClick={() => remove(i)} style={{ position: "absolute", top: 4, right: 4, width: 24, height: 24, borderRadius: 7, border: "none", background: "rgba(0,0,0,.65)", color: "#fff", display: "grid", placeItems: "center", cursor: "pointer" }}><IconX size={14} /></button>
            {i === 0 && <span style={{ position: "absolute", bottom: 4, left: 4, fontSize: 10, fontWeight: 700, background: "var(--accent)", color: "var(--accent-ink)", padding: "2px 6px", borderRadius: 5 }}>CAPA</span>}
          </div>
        ))}
      </div>
      <p style={{ fontSize: 12.5, color: "var(--faint)", marginTop: 8 }}>Sem foto? O anúncio mostra um placeholder elegante automaticamente. A primeira foto vira a capa.</p>
    </div>
  );
}

// ---------- Vehicle form ----------
const EMPTY = {
  categoria: "street", marca: "", modelo: "", ano: new Date().getFullYear(), preco: "", precoAntigo: "",
  km: "", cambio: "Manual", combustivel: "Gasolina", cor: "", status: "disponivel",
  descricao: "", opcionais: [], fotos: [], destaque: false,
};

function VehicleForm({ open, onClose, onSave, initial, mode }) {
  const [f, setF] = React.useState(EMPTY);
  const [custom, setCustom] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  React.useEffect(() => { if (open) { setF(initial ? { ...EMPTY, ...initial } : EMPTY); setErr(""); } }, [open, initial]);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const toggleOpc = (o) => setF((p) => ({ ...p, opcionais: p.opcionais.includes(o) ? p.opcionais.filter((x) => x !== o) : [...p.opcionais, o] }));
  const addCustom = () => { const v = custom.trim(); if (v && !f.opcionais.includes(v)) { set("opcionais", [...f.opcionais, v]); setCustom(""); } };

  const valid = f.marca.trim() && f.modelo.trim() && f.preco;
  const save = async () => {
    if (!valid || busy) return;
    setBusy(true); setErr("");
    try {
      await onSave({ ...f, ano: Number(f.ano) || new Date().getFullYear(), preco: Number(f.preco) || 0,
        precoAntigo: Number(f.precoAntigo) || 0, km: Number(f.km) || 0 });
    } catch (e) { setErr(e.message || "Não foi possível salvar."); setBusy(false); }
  };

  return (
    <Modal open={open} onClose={onClose} maxWidth={680} label="Anúncio">
      <ModalHeader title={initial ? "Editar anúncio" : "Novo anúncio"} subtitle="Preencha os dados da moto" onClose={onClose} />
      <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 18 }}>
        {/* segmento */}
        <div className="field">
          <label>Segmento</label>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {SEGMENTOS.map((s) => (
              <button key={s.id} type="button" className="chip" data-active={f.categoria === s.id} onClick={() => set("categoria", s.id)} style={{ flex: "1 1 0", minWidth: 92, justifyContent: "center", padding: "11px 0" }}><IconBike size={16} /> {s.label}</button>
            ))}
          </div>
        </div>

        <div className="form-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div className="field"><label>Marca *</label><input className="input" value={f.marca} onChange={(e) => set("marca", e.target.value)} placeholder="Ex: Honda" /></div>
          <div className="field"><label>Modelo *</label><input className="input" value={f.modelo} onChange={(e) => set("modelo", e.target.value)} placeholder="Ex: CB 500F" /></div>
        </div>

        <div className="form-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
          <div className="field"><label>Ano</label><input type="number" className="input" value={f.ano} onChange={(e) => set("ano", e.target.value)} /></div>
          <div className="field"><label>Quilometragem</label><input type="number" className="input" value={f.km} onChange={(e) => set("km", e.target.value)} placeholder="0" /></div>
          <div className="field"><label>Cor</label><input className="input" value={f.cor} onChange={(e) => set("cor", e.target.value)} placeholder="Ex: Preto" /></div>
        </div>

        <div className="form-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div className="field"><label>Câmbio</label><select className="select" value={f.cambio} onChange={(e) => set("cambio", e.target.value)}>{CAMBIOS.map((c) => <option key={c}>{c}</option>)}</select></div>
          <div className="field"><label>Combustível</label><select className="select" value={f.combustivel} onChange={(e) => set("combustivel", e.target.value)}>{COMBUSTIVEIS.map((c) => <option key={c}>{c}</option>)}</select></div>
        </div>

        <div className="form-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, alignItems: "end" }}>
          <div className="field"><label>Preço (R$) *</label><input type="number" className="input" value={f.preco} onChange={(e) => set("preco", e.target.value)} placeholder="0" /></div>
          <div className="field"><label>Preço antigo</label><input type="number" className="input" value={f.precoAntigo} onChange={(e) => set("precoAntigo", e.target.value)} placeholder="(p/ oferta)" /></div>
          <div className="field"><label>Situação</label><select className="select" value={f.status} onChange={(e) => set("status", e.target.value)}>
            <option value="disponivel">Disponível</option><option value="oferta">Oferta</option><option value="reservado">Reservado</option><option value="vendido">Vendido</option>
          </select></div>
        </div>

        <div className="field"><label>Descrição</label><textarea className="textarea" value={f.descricao} onChange={(e) => set("descricao", e.target.value)} placeholder="Conte os detalhes da moto, estado de conservação, revisões, histórico…" /></div>

        <div className="field">
          <label>Fotos</label>
          <PhotoEditor fotos={f.fotos} vehicle={f} mode={mode} onChange={(v) => set("fotos", v)} />
        </div>

        <div className="field">
          <label>Opcionais</label>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {OPCIONAIS_COMUNS.map((o) => (
              <button key={o} type="button" className="chip" data-active={f.opcionais.includes(o)} onClick={() => toggleOpc(o)} style={{ fontSize: 13, padding: "7px 12px" }}>{o}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
            <input className="input" value={custom} onChange={(e) => setCustom(e.target.value)} placeholder="Outro opcional…" onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addCustom(); } }} />
            <button type="button" onClick={addCustom} className="btn btn-ghost"><IconPlus size={16} /></button>
          </div>
          {f.opcionais.filter((o) => !OPCIONAIS_COMUNS.includes(o)).length > 0 && (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }}>
              {f.opcionais.filter((o) => !OPCIONAIS_COMUNS.includes(o)).map((o) => (
                <span key={o} className="chip" data-active="true" style={{ fontSize: 13 }} onClick={() => toggleOpc(o)}>{o} <IconX size={13} /></span>
              ))}
            </div>
          )}
        </div>

        <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", padding: "12px 14px", borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border-soft)" }}>
          <input type="checkbox" checked={f.destaque} onChange={(e) => set("destaque", e.target.checked)} style={{ accentColor: "var(--accent)", width: 18, height: 18 }} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 14, display: "flex", alignItems: "center", gap: 6 }}><IconStar size={15} style={{ color: "var(--accent)" }} /> Destaque da semana</div>
            <div style={{ fontSize: 12.5, color: "var(--faint)" }}>Aparece em evidência na página inicial</div>
          </div>
        </label>
      </div>
      <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", alignItems: "center", padding: "18px 22px", borderTop: "1px solid var(--border-soft)", position: "sticky", bottom: 0, background: "var(--surface)" }}>
        {err && <span style={{ fontSize: 13, color: "var(--danger)", fontWeight: 600, marginRight: "auto" }}>{err}</span>}
        <button onClick={onClose} className="btn btn-ghost">Cancelar</button>
        <button onClick={save} disabled={!valid || busy} className="btn btn-primary"><IconCheck size={17} /> {busy ? "Salvando…" : "Salvar anúncio"}</button>
      </div>
      <style>{`@media (max-width: 600px){ .form-row{ grid-template-columns: 1fr !important; } }`}</style>
    </Modal>
  );
}

// ---------- Dashboard ----------
function AdminDashboard({ store, onLogout, onExit }) {
  const { vehicles, mode, addVehicle, updateVehicle, deleteVehicle, resetVehicles } = store;
  const [formOpen, setFormOpen] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const [filter, setFilter] = React.useState("todos");

  const stats = React.useMemo(() => ({
    total: vehicles.length,
    disponiveis: vehicles.filter((v) => v.status === "disponivel" || v.status === "oferta").length,
    ofertas: vehicles.filter((v) => v.status === "oferta").length,
    vendidos: vehicles.filter((v) => v.status === "vendido").length,
  }), [vehicles]);

  const list = filter === "todos" ? vehicles : vehicles.filter((v) => v.categoria === filter);

  const openNew = () => { setEditing(null); setFormOpen(true); };
  const openEdit = (v) => { setEditing(v); setFormOpen(true); };
  const handleSave = async (data) => {
    if (editing) await updateVehicle(editing.id, data); else await addVehicle(data);
    setFormOpen(false); setEditing(null);
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
      {/* top bar */}
      <header style={{ position: "sticky", top: 0, zIndex: 50, background: "var(--surface)", borderBottom: "1px solid var(--border-soft)" }}>
        <div className="wrap" style={{ height: 64, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <span style={{ width: 36, height: 36, borderRadius: 10, background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center" }}><IconSliders size={20} /></span>
            <div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>Painel do vendedor</div>
              <div style={{ fontSize: 12, color: "var(--faint)" }}>Moliterni Motos</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={onExit} className="btn btn-ghost btn-sm">Ver site</button>
            <button onClick={onLogout} className="btn btn-ghost btn-sm"><IconLogout size={16} /> Sair</button>
          </div>
        </div>
      </header>

      <div className="wrap" style={{ paddingTop: 28, paddingBottom: 60 }}>
        {/* stats */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 14, marginBottom: 26 }}>
          {[["Total de anúncios", stats.total, IconBike], ["À venda", stats.disponiveis, IconCheckCircle], ["Em oferta", stats.ofertas, IconStar], ["Vendidas", stats.vendidos, IconShield]].map(([label, val, Icon]) => (
            <div key={label} className="card" style={{ padding: "18px 20px" }}>
              <Icon size={20} style={{ color: "var(--accent)" }} />
              <div style={{ fontFamily: "var(--font-display)", fontSize: 30, fontWeight: 700, marginTop: 8 }}>{val}</div>
              <div style={{ fontSize: 13, color: "var(--muted)", fontWeight: 600 }}>{label}</div>
            </div>
          ))}
        </div>

        {/* toolbar */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 18 }}>
          <div style={{ display: "flex", gap: 8 }}>
            {[{ id: "todos", label: "Todas" }, ...SEGMENTOS].map((s) => (
              <button key={s.id} className="chip" data-active={filter === s.id} onClick={() => setFilter(s.id)}>{s.label}</button>
            ))}
          </div>
          <button onClick={openNew} className="btn btn-primary"><IconPlus size={18} /> Novo anúncio</button>
        </div>

        {/* list */}
        <div className="card" style={{ overflow: "hidden" }}>
          {list.length === 0 ? (
            <div style={{ padding: "50px 20px", textAlign: "center", color: "var(--muted)" }}>Nenhum anúncio nesta categoria.</div>
          ) : list.map((v, i) => (
            <div key={v.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", borderTop: i ? "1px solid var(--border-soft)" : "none" }} className="admin-row">
              <div style={{ width: 84, aspectRatio: "4/3", borderRadius: 9, overflow: "hidden", flexShrink: 0 }}>
                <VehiclePhoto vehicle={v} style={{ width: "100%", height: "100%" }} rounded={false} label={false} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                  <strong style={{ fontSize: 15.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{v.marca} {v.modelo}</strong>
                  {v.destaque && <IconStar size={15} style={{ color: "var(--accent)", flexShrink: 0 }} />}
                </div>
                <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 4, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <StatusBadge status={v.status} />
                  <span>{v.ano} · {formatKM(v.km)} · {v.cambio}</span>
                </div>
              </div>
              <div style={{ textAlign: "right", flexShrink: 0 }} className="admin-price">
                <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 700 }}>{formatBRL(v.preco)}</div>
              </div>
              <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
                <button onClick={() => openEdit(v)} className="btn btn-ghost btn-sm" style={{ padding: 9, borderRadius: 9 }} title="Editar"><IconEdit size={17} /></button>
                <button onClick={() => setConfirmDel(v)} className="btn btn-ghost btn-sm" style={{ padding: 9, borderRadius: 9, color: "var(--danger)" }} title="Excluir"><IconTrash size={17} /></button>
              </div>
            </div>
          ))}
        </div>

        {mode === "demo" && (
          <button onClick={() => { if (confirm("Restaurar os anúncios de demonstração? Isso substitui a lista atual.")) resetVehicles(); }}
            className="btn btn-ghost btn-sm" style={{ marginTop: 18, color: "var(--faint)" }}>Restaurar dados de demonstração</button>
        )}
      </div>

      <VehicleForm open={formOpen} onClose={() => { setFormOpen(false); setEditing(null); }} onSave={handleSave} initial={editing} mode={mode} />

      <Modal open={!!confirmDel} onClose={() => setConfirmDel(null)} maxWidth={400} label="Excluir">
        {confirmDel && (
          <div style={{ padding: 26 }}>
            <h3 style={{ fontSize: 19 }}>Excluir anúncio?</h3>
            <p style={{ color: "var(--muted)", marginTop: 8 }}>O anúncio do <strong style={{ color: "var(--text)" }}>{confirmDel.marca} {confirmDel.modelo}</strong> será removido permanentemente.</p>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 22 }}>
              <button onClick={() => setConfirmDel(null)} className="btn btn-ghost">Cancelar</button>
              <button onClick={async () => { try { await deleteVehicle(confirmDel.id); setConfirmDel(null); } catch (e) { alert(e.message || "Não foi possível excluir."); } }} className="btn btn-primary" style={{ background: "var(--danger)", color: "#fff" }}><IconTrash size={16} /> Excluir</button>
            </div>
          </div>
        )}
      </Modal>

      <style>{`@media (max-width: 560px){ .admin-price{ display:none; } }`}</style>
    </div>
  );
}

function AdminArea({ store, onExit }) {
  const { authed, login, logout, checking } = useAuth(store.mode);
  if (store.mode === "loading" || checking) {
    return <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", color: "var(--muted)" }}>Carregando…</div>;
  }
  if (!authed) return <AdminLogin onLogin={login} onBack={onExit} mode={store.mode} />;
  return <AdminDashboard store={store} onLogout={() => { logout(); onExit(); }} onExit={onExit} />;
}

Object.assign(window, { AdminArea, AdminLogin, AdminDashboard, VehicleForm, useAuth });
