// === Mania De Jeans CG — Admin + Institutional ===
const { useState, useEffect, useCallback } = React;

function AdminLogin({ onSuccess, toast }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    try {
      const sb = window.MJ_getSupabase();
      const { error: err } = await sb.auth.signInWithPassword({ email: email.trim(), password });
      if (err) throw err;
      toast("Login realizado");
      onSuccess();
    } catch (err) {
      setError(err.message || "Não foi possível entrar. Verifique e-mail e senha.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="admin-page" style={{maxWidth:420, margin:"40px auto"}}>
      <h1 style={{fontFamily:'var(--font-display)', fontSize:28, margin:'0 0 8px', color:'var(--denim-900)'}}>Entrar no painel</h1>
      <p style={{color:'var(--ink-500)', fontSize:14, margin:'0 0 24px'}}>
        Use o usuário criado em Supabase → Authentication → Users.
      </p>
      <form className="form-card" style={{padding:22}} onSubmit={handleSubmit}>
        <div className="form-field" style={{marginBottom:14}}>
          <label>E-mail</label>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email"/>
        </div>
        <div className="form-field" style={{marginBottom:14}}>
          <label>Senha</label>
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="current-password"/>
        </div>
        {error && (
          <div style={{fontSize:13, color:'var(--promo)', marginBottom:12, padding:'10px 12px', background:'#fff5f5', borderRadius:6}}>
            {error}
          </div>
        )}
        <button type="submit" className="btn btn-primary btn-block" disabled={loading}>
          {loading ? "Entrando…" : "Entrar"}
        </button>
      </form>
    </div>
  );
}

function ScreenAdmin({ go, toast }) {
  const [section, setSection] = useState("products");
  const [editing, setEditing] = useState(null);
  const [products, setProducts] = useState([]);
  const [loadingProducts, setLoadingProducts] = useState(true);
  const [catalogCategories, setCatalogCategories] = useState(() => window.MJ_CATEGORY_NAMES || []);
  const [catalogWashes, setCatalogWashes] = useState(() => window.MJ_WASH_OPTIONS || []);
  const [session, setSession] = useState(null);
  const [authReady, setAuthReady] = useState(false);

  const loadProducts = useCallback(async () => {
    setLoadingProducts(true);
    try {
      const list = await window.MJ_fetchProducts();
      setProducts(list);
    } catch (err) {
      console.error(err);
      toast("Erro ao carregar produtos: " + (err.message || "verifique a conexão"));
    } finally {
      setLoadingProducts(false);
    }
  }, [toast]);

  useEffect(() => {
    try {
      const sb = window.MJ_getSupabase();
      sb.auth.getSession().then(({ data: { session: s } }) => {
        setSession(s);
        setAuthReady(true);
      });
      const { data: { subscription } } = sb.auth.onAuthStateChange((_event, s) => setSession(s));
      return () => subscription.unsubscribe();
    } catch (err) {
      setAuthReady(true);
      toast(err.message || "Supabase não configurado");
    }
  }, [toast]);

  const loadLookups = useCallback(async () => {
    if (!window.MJ_loadCatalogLookups) return;
    try {
      const data = await window.MJ_loadCatalogLookups();
      setCatalogCategories(data.categories || []);
      setCatalogWashes(data.washes || []);
    } catch (err) {
      console.error(err);
    }
  }, []);

  useEffect(() => {
    if (session) {
      loadProducts();
      loadLookups();
    }
  }, [session, loadProducts, loadLookups]);

  const handleLogout = async () => {
    try {
      await window.MJ_getSupabase().auth.signOut();
      setProducts([]);
      toast("Sessão encerrada");
    } catch (err) {
      toast(err.message || "Erro ao sair");
    }
  };

  if (!authReady) {
    return (
      <div className="admin-page" style={{padding:40, textAlign:'center', color:'var(--ink-500)'}}>
        Carregando…
      </div>
    );
  }

  if (!session) {
    return <AdminLogin onSuccess={() => {}} toast={toast}/>;
  }

  return (
    <div className="admin-page">
      <div className="crumbs">
        <a onClick={() => go("home")}><Icon.Home s={12}/></a>
        <span className="sep">/</span>
        <span className="curr">Painel administrativo</span>
      </div>
      <h1 style={{fontFamily:'var(--font-display)', fontSize:32, letterSpacing:'-0.03em', margin:'0 0 4px', color:'var(--denim-900)'}}>Painel da loja</h1>
      <p style={{color:'var(--ink-500)', fontSize:14, margin:'0 0 24px'}}>Cadastre calças, estoque por tamanho e acompanhe pedidos.</p>

      <div className="admin-layout">
        <aside className="admin-side">
          <div className="it" style={{background:'var(--cream-50)', marginBottom:10}}>
            <div style={{width:32, height:32, borderRadius:'50%', background:'var(--denim-700)', color:'#fff', display:'grid', placeItems:'center', fontWeight:700, fontSize:13}}>A</div>
            <div>
              <div style={{fontSize:13, fontWeight:700, color:'var(--denim-900)'}}>Admin</div>
              <div style={{fontSize:11, color:'var(--ink-500)', fontWeight:500, wordBreak:'break-all'}}>{session.user?.email}</div>
            </div>
          </div>
          <h4>Visão geral</h4>
          <div className={"it" + (section === "dash" ? " on" : "")} onClick={() => setSection("dash")}><Icon.Chart s={16}/> Dashboard</div>
          <div className={"it" + (section === "orders" ? " on" : "")} onClick={() => setSection("orders")}><Icon.Box s={16}/> Pedidos</div>
          <h4>Catálogo</h4>
          <div className={"it" + (section === "products" ? " on" : "")} onClick={() => setSection("products")}><Icon.Tag s={16}/> Produtos</div>
          <div className={"it" + (section === "new" ? " on" : "")} onClick={() => { setEditing(null); setSection("new"); }}><Icon.Plus s={16}/> Cadastrar produto</div>
          <div className={"it" + (section === "stock" ? " on" : "")} onClick={() => setSection("stock")}><Icon.Box s={16}/> Controle de estoque</div>
          <h4>Configurações</h4>
          <div className={"it" + (section === "settings" ? " on" : "")} onClick={() => setSection("settings")}><Icon.Settings s={16}/> Loja e pagamento</div>
          <a
            href={new URL("../Mania De Jeans CG.html", window.location.href).href}
            target="_blank"
            rel="noopener noreferrer"
            className="btn btn-outline btn-sm"
            style={{ marginTop: 16, width: "100%", textDecoration: "none", gap: 6 }}
          >
            <Icon.Home s={14}/> Ver site
          </a>
          <button className="btn btn-ghost btn-sm" style={{marginTop:8, width:'100%'}} onClick={handleLogout}>Sair</button>
        </aside>

        <main className="admin-main">
          {section === "dash" && <AdminDashboard productCount={products.length}/>}
          {section === "orders" && <AdminOrders/>}
          {section === "products" && (
            <AdminProducts
              products={products}
              loading={loadingProducts}
              categories={catalogCategories}
              onEdit={(p) => { setEditing(p); setSection("new"); }}
              onRefresh={loadProducts}
              toast={toast}
            />
          )}
          {section === "new" && (
            <AdminProductForm
              product={editing}
              categories={catalogCategories}
              washes={catalogWashes}
              toast={toast}
              onCancel={() => { setEditing(null); setSection("products"); }}
              onSaved={() => { setEditing(null); setSection("products"); loadProducts(); }}
              onLookupRefresh={loadLookups}
            />
          )}
          {section === "stock" && <AdminStock products={products} loading={loadingProducts} toast={toast}/>}
          {section === "settings" && <AdminSettings/>}
        </main>
      </div>
    </div>
  );
}

function AdminEmpty({ IconComp, title, desc }) {
  return (
    <div className="cart-empty" style={{padding:'36px 20px'}}>
      <div className="icon-circle"><IconComp s={28}/></div>
      <h3>{title}</h3>
      {desc && <p style={{marginBottom:0}}>{desc}</p>}
    </div>
  );
}

function AdminDashboard({ productCount = 0 }) {
  return (
    <>
      <h2>Dashboard</h2>
      <p className="sub">Visão geral dos últimos 30 dias.</p>
      <div className="admin-stats">
        <div className="stat-card"><div className="lab">Produtos no catálogo</div><div className="val">{productCount}</div><div className="delta" style={{color:'var(--ink-500)'}}>Cadastrados no Supabase</div></div>
        <div className="stat-card"><div className="lab">Pedidos</div><div className="val">0</div><div className="delta" style={{color:'var(--ink-500)'}}>Nenhum pedido ainda</div></div>
        <div className="stat-card"><div className="lab">Ticket médio</div><div className="val">—</div><div className="delta" style={{color:'var(--ink-500)'}}>Aguardando pedidos</div></div>
        <div className="stat-card"><div className="lab">Conversão</div><div className="val">—</div><div className="delta" style={{color:'var(--ink-500)'}}>Sem histórico</div></div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:18, marginBottom:18}}>
        <div style={{background:'var(--cream-50)', borderRadius:10, padding:22}}>
          <div style={{fontSize:13, fontWeight:700, color:'var(--denim-900)', letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:14}}>Vendas por dia</div>
          <AdminEmpty IconComp={Icon.Chart} title="Sem dados de vendas" desc="O gráfico será exibido quando houver pedidos concluídos."/>
        </div>
        <div style={{background:'var(--cream-50)', borderRadius:10, padding:22}}>
          <div style={{fontSize:13, fontWeight:700, color:'var(--denim-900)', letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:14}}>Mais vendidos</div>
          <AdminEmpty IconComp={Icon.Tag} title="Nenhuma venda ainda" desc="Os produtos mais vendidos aparecerão aqui."/>
        </div>
      </div>

      <div style={{background:'var(--cream-50)', borderRadius:10, padding:22}}>
        <div style={{fontSize:13, fontWeight:700, color:'var(--denim-900)', letterSpacing:'0.06em', textTransform:'uppercase', marginBottom:14}}>Pedidos recentes</div>
        <AdminEmpty IconComp={Icon.Box} title="Nenhum pedido recente" desc="Os pedidos da loja serão listados aqui."/>
      </div>
    </>
  );
}

function AdminOrders() {
  return (
    <>
      <h2>Pedidos</h2>
      <p className="sub">Acompanhe e gerencie todos os pedidos da loja.</p>
      <div style={{display:'flex', gap:8, marginBottom:18, flexWrap:'wrap'}}>
        <button className="btn btn-dark btn-sm">Todos</button>
        <button className="btn btn-ghost btn-sm" disabled>Aguardando pagamento</button>
        <button className="btn btn-ghost btn-sm" disabled>Pagos</button>
        <button className="btn btn-ghost btn-sm" disabled>Enviados</button>
        <button className="btn btn-ghost btn-sm" disabled>Cancelados</button>
      </div>
      <AdminEmpty IconComp={Icon.Box} title="Nenhum pedido" desc="Quando clientes finalizarem compras, os pedidos aparecerão nesta lista."/>
    </>
  );
}

function AdminProducts({ products, loading, categories = [], onEdit, onRefresh, toast }) {
  const handleDelete = async (p) => {
    if (!confirm(`Excluir "${p.name}"? Esta ação não pode ser desfeita.`)) return;
    try {
      await window.MJ_deleteProduct(p.id);
      toast("Produto excluído");
      onRefresh();
    } catch (err) {
      toast("Erro ao excluir: " + (err.message || "tente novamente"));
    }
  };

  if (loading) {
    return (
      <>
        <h2>Produtos</h2>
        <p className="sub" style={{color:'var(--ink-500)'}}>Carregando catálogo…</p>
      </>
    );
  }

  return (
    <>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8, flexWrap:'wrap', gap:10}}>
        <div>
          <h2>Produtos</h2>
          <p className="sub">{products.length} produtos no catálogo · {products.filter(p => p.available).length} ativos</p>
        </div>
        <div style={{display:'flex', gap:8}}>
          <button className="btn btn-ghost btn-sm" onClick={onRefresh}>Atualizar</button>
          <button className="btn btn-primary" onClick={() => onEdit(null)}><Icon.Plus s={14}/> Novo produto</button>
        </div>
      </div>
      <div style={{display:'flex', gap:8, marginBottom:18, flexWrap:'wrap'}}>
        <div className="search" style={{maxWidth:280, padding:'8px 14px', margin:0}}>
          <Icon.Search s={14}/>
          <input placeholder="Buscar produto..."/>
        </div>
        <select className="sort-select" style={{padding:'7px 14px'}}>
          <option>Todas as categorias</option>
          {categories.map((c) => <option key={c}>{c}</option>)}
        </select>
        <select className="sort-select" style={{padding:'7px 14px'}}>
          <option>Todos os status</option><option>Disponível</option><option>Indisponível</option><option>Estoque baixo</option>
        </select>
      </div>
      {products.length === 0 ? (
        <AdminEmpty
          IconComp={Icon.Tag}
          title="Nenhum produto cadastrado"
          desc='Clique em "Novo produto" para cadastrar sua primeira peça no Supabase.'
        />
      ) : (
      <table className="admin-table">
        <thead>
          <tr><th>Produto</th><th>Categoria</th><th>Preço</th><th>Estoque</th><th>Status</th><th>Ações</th></tr>
        </thead>
        <tbody>
          {products.map(p => {
            const total = Object.values(p.stock).reduce((a, b) => a + b, 0);
            const lowStock = total < 20;
            return (
              <tr key={p.id}>
                <td className="prod">
                  <div className="mini-img"><ProductPhoto src={p.fotoListing || p.foto1 || p.imageUrl || p.images?.[0]} seed={p.id} tone={p.colorHex} alt=""/></div>
                  <div>
                    <div className="mini-name">{p.name}</div>
                    <div className="mini-sku">{p.sku}</div>
                  </div>
                </td>
                <td>{p.category}</td>
                <td>
                  <div style={{fontWeight:700, color:'var(--denim-900)'}}>{fmt(p.price)}</div>
                  {p.priceOld && <div style={{fontSize:11, color:'var(--ink-500)', textDecoration:'line-through'}}>{fmt(p.priceOld)}</div>}
                </td>
                <td>{total} un {lowStock && <span style={{color:'oklch(50% 0.13 70)', fontSize:11, fontWeight:700, marginLeft:4}}>baixo</span>}</td>
                <td>
                  {p.available
                    ? <span className="tag tag-on">Disponível</span>
                    : <span className="tag tag-off">Indisponível</span>}
                </td>
                <td>
                  <div style={{display:'flex', gap:4}}>
                    <button className="btn btn-ghost btn-sm" onClick={() => onEdit(p)} title="Editar"><Icon.Edit s={14}/></button>
                    <button className="btn btn-ghost btn-sm" title="Visualizar"><Icon.Eye s={14}/></button>
                    <button className="btn btn-ghost btn-sm" onClick={() => handleDelete(p)} title="Excluir" style={{color:'var(--promo)'}}><Icon.Trash s={14}/></button>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      )}
    </>
  );
}

function emptyImageSlot(listingUrl = "", productUrl = "", kind = "processed") {
  const url = productUrl || listingUrl;
  return {
    kind,
    listingUrl,
    productUrl,
    imageUrl: url,
    pendingFile: null,
    previewUrl: url,
    removed: false,
  };
}

function AdminPicklistWithAdd({ label, required, value, options, getValue, getLabel, onChange, onAdd, placeholder, toast }) {
  const [adding, setAdding] = React.useState(false);
  const [newName, setNewName] = React.useState("");
  const [saving, setSaving] = React.useState(false);

  const handleAdd = async () => {
    const trimmed = newName.trim();
    if (!trimmed) return;
    setSaving(true);
    try {
      const created = await onAdd(trimmed);
      onChange(created);
      setNewName("");
      setAdding(false);
      toast && toast("Adicionado com sucesso");
    } catch (err) {
      toast && toast(err.message || "Erro ao adicionar");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="form-field">
      <label>{label}{required ? " *" : ""}</label>
      {!adding ? (
        <>
          <select value={value} onChange={(e) => onChange(e.target.value)}>
            {options.map((opt) => {
              const v = getValue(opt);
              const l = getLabel(opt);
              return <option key={v} value={v}>{l}</option>;
            })}
          </select>
          <button
            type="button"
            className="btn btn-ghost btn-sm"
            style={{ marginTop: 6, padding: "4px 0", fontSize: 12 }}
            onClick={() => setAdding(true)}
          >
            + Adicionar {label.toLowerCase().includes("categoria") ? "categoria" : "cor/lavagem"}
          </button>
        </>
      ) : (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          <input
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder={placeholder}
            style={{ flex: "1 1 160px", minWidth: 120 }}
            onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); handleAdd(); } }}
          />
          <button type="button" className="btn btn-primary btn-sm" onClick={handleAdd} disabled={saving}>
            {saving ? "Salvando…" : "Salvar"}
          </button>
          <button type="button" className="btn btn-ghost btn-sm" onClick={() => { setAdding(false); setNewName(""); }} disabled={saving}>
            Cancelar
          </button>
        </div>
      )}
    </div>
  );
}

function AdminImageField({ label, hint, slotIndex, slot, fileRef, dragOver, required, showUrlField, onDragOver, onDragLeave, onDrop, onPickFile, onClear, onUrlChange }) {
  const show = !slot.removed && (slot.previewUrl || slot.productUrl || slot.imageUrl);
  return (
    <div className="upload-slot">
      <h4>{label}{required ? " *" : ""}</h4>
      {hint && <p style={{ fontSize: 11.5, color: "var(--ink-500)", margin: "0 0 8px" }}>{hint}</p>}
      <input
        ref={fileRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        style={{ display: "none" }}
        onChange={(e) => { onPickFile(e.target.files?.[0]); e.target.value = ""; }}
      />
      {show ? (
        <div className="upload-preview">
          <div className="thumb">
            <img src={slot.previewUrl || slot.productUrl || slot.imageUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
          </div>
          <div className="meta">
            <div style={{ fontWeight: 700, color: "var(--denim-900)", marginBottom: 4, fontSize: 12 }}>
              {slot.pendingFile ? slot.pendingFile.name : "Imagem salva"}
            </div>
            <button type="button" className="btn btn-ghost btn-sm" onClick={onClear}>Remover</button>
            <button type="button" className="btn btn-outline btn-sm" style={{ marginLeft: 6 }} onClick={() => fileRef.current?.click()}>Trocar</button>
          </div>
        </div>
      ) : null}
      <div
        className={"upload-zone" + (dragOver ? " drag-over" : "")}
        onClick={() => fileRef.current?.click()}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
      >
        <strong>Foto {slotIndex}</strong>
        Clique ou arraste · JPG, PNG, WEBP · 5 MB
        {slot.kind === "processed" && <span style={{ display: "block", fontSize: 11, fontWeight: 500, marginTop: 4, opacity: 0.85 }}>Será convertida para WebP (listagem + detalhe)</span>}
        {slot.kind === "direct" && <span style={{ display: "block", fontSize: 11, fontWeight: 500, marginTop: 4, opacity: 0.85 }}>Upload direto, sem conversão</span>}
      </div>
      {showUrlField && (
        <div className="form-field" style={{ marginTop: 8, marginBottom: 0 }}>
          <label style={{ fontSize: 11.5 }}>Ou URL (opcional)</label>
          <input
            value={slot.productUrl || slot.imageUrl}
            onChange={(e) => onUrlChange(e.target.value)}
            placeholder="https://..."
            disabled={!!slot.pendingFile}
          />
        </div>
      )}
    </div>
  );
}

function AdminVideoField({ slot, fileRef, dragOver, onDragOver, onDragLeave, onDrop, onPickFile, onClear }) {
  const show = !slot.removed && (slot.previewUrl || slot.videoUrl);
  return (
    <div className="upload-slot">
      <h4>Vídeo (opcional)</h4>
      <p style={{ fontSize: 11.5, color: "var(--ink-500)", margin: "0 0 8px" }}>MP4, WEBM ou MOV · até 50 MB · sem compressão</p>
      <input
        ref={fileRef}
        type="file"
        accept="video/mp4,video/webm,video/quicktime"
        style={{ display: "none" }}
        onChange={(e) => { onPickFile(e.target.files?.[0]); e.target.value = ""; }}
      />
      {show ? (
        <div className="upload-preview">
          <div className="meta" style={{ width: "100%" }}>
            <div style={{ fontWeight: 700, color: "var(--denim-900)", marginBottom: 4, fontSize: 12 }}>
              {slot.pendingFile ? slot.pendingFile.name : "Vídeo salvo"}
            </div>
            {slot.previewUrl && slot.pendingFile && (
              <video src={slot.previewUrl} controls style={{ width: "100%", maxHeight: 160, borderRadius: 6, marginBottom: 8 }}/>
            )}
            <button type="button" className="btn btn-ghost btn-sm" onClick={onClear}>Remover</button>
            <button type="button" className="btn btn-outline btn-sm" style={{ marginLeft: 6 }} onClick={() => fileRef.current?.click()}>Trocar</button>
          </div>
        </div>
      ) : null}
      <div
        className={"upload-zone" + (dragOver ? " drag-over" : "")}
        onClick={() => fileRef.current?.click()}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
      >
        <strong>Vídeo do produto</strong>
        Clique ou arraste · MP4, WEBM, MOV
      </div>
    </div>
  );
}

function AdminProductForm({ product, categories = [], washes = [], toast, onCancel, onSaved, onLookupRefresh }) {
  const isEdit = !!product;
  const emptyStock = () => {
    const s = {};
    window.MJ_SIZES.forEach((sz) => { s[sz] = 0; });
    return s;
  };

  const fileRef1 = React.useRef(null);
  const fileRef2 = React.useRef(null);
  const fileRef3 = React.useRef(null);
  const fileRefVideo = React.useRef(null);

  const [form, setForm] = useState(() => ({
    id: product?.id || null,
    name: product?.name || "",
    sku: product?.sku || "",
    category: product?.category || categories[0] || "Wide leg",
    price: product?.price != null ? String(product.price).replace(".", ",") : "",
    priceOld: product?.priceOld != null ? String(product.priceOld).replace(".", ",") : "",
    wash: product?.wash || "media",
    desc: product?.desc || "",
    descLong: product?.descLong || "",
    mainPhoto: emptyImageSlot(product?.fotoListing, product?.foto1 || product?.imageUrl, "processed"),
    secondPhoto: emptyImageSlot(product?.foto2Listing, product?.foto2 || product?.imageUrl2, "processed"),
    thirdPhoto: emptyImageSlot("", product?.foto3, "direct"),
    video: { videoUrl: product?.video || "", pendingFile: null, previewUrl: "", removed: false },
    origMain: { listing: product?.fotoListing || "", product: product?.foto1 || product?.imageUrl || "" },
    origSecond: { listing: product?.foto2Listing || "", product: product?.foto2 || product?.imageUrl2 || "" },
    origThird: product?.foto3 || "",
    origVideo: product?.video || "",
    available: product?.available !== false,
    isNew: !!product?.isNew,
    isPromo: !!product?.isPromo,
    stock: product?.stock ? { ...product.stock } : emptyStock(),
  }));
  const [saving, setSaving] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [dragOver, setDragOver] = useState([false, false, false, false]);
  const [formError, setFormError] = useState("");

  useEffect(() => {
    return () => {
      [form.mainPhoto, form.secondPhoto, form.thirdPhoto].forEach((s) => {
        if (s.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(s.previewUrl);
      });
      if (form.video.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(form.video.previewUrl);
    };
  }, []);

  const set = (key, val) => setForm((f) => ({ ...f, [key]: val }));
  const colorHex = window.MJ_WASH_HEX?.[form.wash] || "#4a6b8a";
  const previewPrice = parseFloat(String(form.price).replace(",", ".")) || 0;
  const stockTotal = Object.values(form.stock).reduce((a, b) => a + (parseInt(b, 10) || 0), 0);

  const hasMainPhoto = () => {
    const s = form.mainPhoto;
    return !s.removed && (s.pendingFile || s.productUrl || s.listingUrl);
  };

  const pickImageFile = (slotKey, file) => {
    if (!file) return;
    try {
      if (!file.type.startsWith("image/")) throw new Error("Selecione uma imagem.");
      if (file.size > 5 * 1024 * 1024) throw new Error("Imagem até 5 MB.");
      setForm((f) => {
        const cur = f[slotKey];
        if (cur.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(cur.previewUrl);
        return {
          ...f,
          [slotKey]: {
            ...cur,
            pendingFile: file,
            previewUrl: URL.createObjectURL(file),
            productUrl: "",
            listingUrl: "",
            imageUrl: "",
            removed: false,
          },
        };
      });
      setFormError("");
    } catch (err) {
      setFormError(err.message);
    }
  };

  const clearImage = (slotKey) => {
    setForm((f) => {
      const cur = f[slotKey];
      if (cur.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(cur.previewUrl);
      return { ...f, [slotKey]: { ...emptyImageSlot("", "", cur.kind), removed: true } };
    });
  };

  const pickVideoFile = (file) => {
    if (!file) return;
    try {
      if (!file.type.startsWith("video/")) throw new Error("Selecione um vídeo.");
      if (file.size > 50 * 1024 * 1024) throw new Error("Vídeo até 50 MB.");
      setForm((f) => {
        if (f.video.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(f.video.previewUrl);
        return {
          ...f,
          video: {
            pendingFile: file,
            previewUrl: URL.createObjectURL(file),
            videoUrl: "",
            removed: false,
          },
        };
      });
      setFormError("");
    } catch (err) {
      setFormError(err.message);
    }
  };

  const clearVideo = () => {
    setForm((f) => {
      if (f.video.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(f.video.previewUrl);
      return { ...f, video: { videoUrl: "", pendingFile: null, previewUrl: "", removed: true } };
    });
  };

  const handleSave = async () => {
    if (!form.name.trim()) { setFormError("Informe o nome do produto."); return; }
    if (!form.sku.trim()) { setFormError("Informe o SKU."); return; }
    if (!form.price) { setFormError("Informe o preço."); return; }
    if (!form.desc.trim()) { setFormError("Informe a descrição curta."); return; }
    if (!isEdit && !hasMainPhoto()) {
      setFormError("A foto principal é obrigatória no cadastro.");
      return;
    }

    setSaving(true);
    setFormError("");
    setUploadingImage(true);
    try {
      const productId = await window.MJ_saveProduct({
        id: form.id,
        name: form.name,
        sku: form.sku,
        category: form.category,
        price: form.price,
        priceOld: form.priceOld,
        wash: form.wash,
        colorHex,
        desc: form.desc,
        descLong: form.descLong,
        available: form.available,
        isNew: form.isNew,
        isPromo: form.isPromo,
        stock: form.stock,
        fotoListing: form.mainPhoto.removed ? null : (form.mainPhoto.listingUrl || null),
        foto1: form.mainPhoto.removed ? null : (form.mainPhoto.productUrl || null),
        foto2Listing: form.secondPhoto.removed ? null : (form.secondPhoto.listingUrl || null),
        foto2: form.secondPhoto.removed ? null : (form.secondPhoto.productUrl || null),
        foto3: form.thirdPhoto.removed ? null : (form.thirdPhoto.productUrl || null),
        video: form.video.removed ? null : (form.video.videoUrl || null),
      });

      const media = {};

      if (form.mainPhoto.removed) {
        await window.MJ_deleteMainPhotoPair(productId, form.category, form.origMain.listing, form.origMain.product);
        media.fotoListing = null;
        media.foto1 = null;
      } else if (form.mainPhoto.pendingFile) {
        if (form.origMain.listing || form.origMain.product) {
          await window.MJ_deleteMainPhotoPair(productId, form.category, form.origMain.listing, form.origMain.product);
        }
        Object.assign(media, await window.MJ_uploadMainPhoto(form.mainPhoto.pendingFile, productId, form.category));
      }

      if (form.secondPhoto.removed) {
        await window.MJ_deleteSecondPhotoPair(productId, form.category, form.origSecond.listing, form.origSecond.product);
        media.foto2Listing = null;
        media.foto2 = null;
      } else if (form.secondPhoto.pendingFile) {
        if (form.origSecond.listing || form.origSecond.product) {
          await window.MJ_deleteSecondPhotoPair(productId, form.category, form.origSecond.listing, form.origSecond.product);
        }
        Object.assign(media, await window.MJ_uploadSecondPhoto(form.secondPhoto.pendingFile, productId, form.category));
      }

      if (form.thirdPhoto.removed) {
        if (form.origThird) await window.MJ_removePhoto3(window.MJ_getBucketForCategory(form.category), productId, form.origThird);
        media.foto3 = null;
      } else if (form.thirdPhoto.pendingFile) {
        if (form.origThird) await window.MJ_removePhoto3(window.MJ_getBucketForCategory(form.category), productId, form.origThird);
        Object.assign(media, await window.MJ_uploadThirdPhoto(form.thirdPhoto.pendingFile, productId, form.category));
      }

      if (form.video.removed) {
        if (form.origVideo) await window.MJ_removeVideo(window.MJ_getBucketForCategory(form.category), productId, form.origVideo);
        media.video = null;
      } else if (form.video.pendingFile) {
        if (form.origVideo) await window.MJ_removeVideo(window.MJ_getBucketForCategory(form.category), productId, form.origVideo);
        Object.assign(media, await window.MJ_uploadProductVideo(form.video.pendingFile, productId, form.category));
      }

      if (Object.keys(media).length) {
        await window.MJ_updateProductMedia(productId, media);
      }

      toast(isEdit ? "Produto atualizado" : "Produto cadastrado");
      onSaved();
    } catch (err) {
      setFormError(err.message || "Erro ao salvar. Verifique login e permissões no Supabase.");
    } finally {
      setSaving(false);
      setUploadingImage(false);
    }
  };

  return (
    <>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8, flexWrap:'wrap', gap:10}}>
        <div>
          <h2>{isEdit ? "Editar produto" : "Cadastrar produto"}</h2>
          <p className="sub">{isEdit ? "Atualize as informações da peça" : "Os dados serão salvos no Supabase"}</p>
        </div>
        <div style={{display:'flex', gap:8}}>
          <button className="btn btn-ghost" onClick={onCancel} disabled={saving}>Cancelar</button>
          <button className="btn btn-primary" onClick={handleSave} disabled={saving || uploadingImage}>
            {uploadingImage ? "Enviando fotos…" : saving ? "Salvando…" : (isEdit ? "Salvar alterações" : "Cadastrar produto")}
          </button>
        </div>
      </div>

      {formError && (
        <div style={{marginBottom:16, padding:'12px 14px', background:'#fff5f5', borderRadius:8, fontSize:13, color:'var(--promo)'}}>
          {formError}
        </div>
      )}

      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:18}}>
        <div>
          <div className="form-card" style={{padding:22}}>
            <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Informações básicas</h3>
            <div className="form-grid">
              <div className="form-field f-6">
                <label>Nome do produto *</label>
                <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Ex: Pantalona Cintura Alta — Lavagem Média"/>
              </div>
              <div className="form-field f-3">
                <label>SKU *</label>
                <input value={form.sku} onChange={(e) => set("sku", e.target.value)} placeholder="WIDE-007" disabled={isEdit}/>
              </div>
              <div className="form-field f-3">
                <AdminPicklistWithAdd
                  label="Categoria"
                  required
                  value={form.category}
                  options={(categories.length ? categories : window.MJ_CATEGORY_NAMES || []).map((name) => ({ name }))}
                  getValue={(o) => o.name}
                  getLabel={(o) => o.name}
                  onChange={(v) => set("category", v)}
                  onAdd={async (name) => {
                    const created = await window.MJ_addCategory(name);
                    onLookupRefresh && await onLookupRefresh();
                    return created;
                  }}
                  placeholder="Ex: Barrel"
                  toast={toast}
                />
              </div>
              <div className="form-field f-2">
                <label>Preço *</label>
                <input value={form.price} onChange={(e) => set("price", e.target.value)} placeholder="199,90"/>
              </div>
              <div className="form-field f-2">
                <label>Preço de "DE"</label>
                <input value={form.priceOld} onChange={(e) => set("priceOld", e.target.value)} placeholder="249,90"/>
              </div>
              <div className="form-field f-2">
                <AdminPicklistWithAdd
                  label="Cor / Lavagem"
                  value={form.wash}
                  options={(washes.length ? washes : window.MJ_WASH_OPTIONS || []).map((w) => ({ slug: w.slug, label: w.label }))}
                  getValue={(o) => o.slug}
                  getLabel={(o) => o.label}
                  onChange={(v) => set("wash", v)}
                  onAdd={async (label) => {
                    const slug = await window.MJ_addWash(label);
                    onLookupRefresh && await onLookupRefresh();
                    return slug;
                  }}
                  placeholder="Ex: Caramelo"
                  toast={toast}
                />
              </div>
              <div className="form-field f-6">
                <label>Descrição curta *</label>
                <input value={form.desc} onChange={(e) => set("desc", e.target.value)} placeholder="Resumo da peça (1-2 linhas)"/>
              </div>
              <div className="form-field f-6">
                <label>Descrição completa</label>
                <textarea value={form.descLong} onChange={(e) => set("descLong", e.target.value)} rows={4} style={{border:'1px solid var(--denim-200)', borderRadius:6, padding:'11px 12px', fontSize:14, resize:'vertical', width:'100%', boxSizing:'border-box'}} placeholder="Detalhes de tecido, modelagem..."/>
              </div>
            </div>
          </div>

          <div className="form-card" style={{padding:22}}>
            <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Fotos e vídeo</h3>
            <p style={{fontSize:12.5, color:'var(--ink-500)', marginTop:0, marginBottom:14}}>
              Fotos 1 e 2 viram WebP no navegador: <strong>listing.webp</strong> (miniatura, até ~100 KB) e <strong>product.webp</strong> (detalhe, 60–120 KB). Foto 3 e vídeo vão no formato original.
            </p>
            {window.MJ_checkWebPExportSupport && !window.MJ_checkWebPExportSupport() && (
              <p style={{ fontSize: 12.5, color: "var(--promo)", marginBottom: 14 }}>
                Seu navegador não exporta WebP. Use Chrome ou Edge e recarregue com Ctrl+F5.
              </p>
            )}
            <div className="upload-grid-2">
              <AdminImageField
                label="Foto principal"
                hint="Obrigatória no cadastro · usada na listagem (miniatura) e no detalhe (ampliada)"
                slotIndex={1}
                required
                slot={form.mainPhoto}
                fileRef={fileRef1}
                dragOver={dragOver[0]}
                onDragOver={(e) => { e.preventDefault(); setDragOver([true, dragOver[1], dragOver[2], dragOver[3]]); }}
                onDragLeave={() => setDragOver([false, dragOver[1], dragOver[2], dragOver[3]])}
                onDrop={(e) => { e.preventDefault(); setDragOver([false, dragOver[1], dragOver[2], dragOver[3]]); pickImageFile("mainPhoto", e.dataTransfer.files?.[0]); }}
                onPickFile={(file) => pickImageFile("mainPhoto", file)}
                onClear={() => clearImage("mainPhoto")}
              />
              <AdminImageField
                label="Segunda foto"
                hint="Opcional · mesma conversão WebP da principal"
                slotIndex={2}
                slot={form.secondPhoto}
                fileRef={fileRef2}
                dragOver={dragOver[1]}
                onDragOver={(e) => { e.preventDefault(); setDragOver([dragOver[0], true, dragOver[2], dragOver[3]]); }}
                onDragLeave={() => setDragOver([dragOver[0], false, dragOver[2], dragOver[3]])}
                onDrop={(e) => { e.preventDefault(); setDragOver([dragOver[0], false, dragOver[2], dragOver[3]]); pickImageFile("secondPhoto", e.dataTransfer.files?.[0]); }}
                onPickFile={(file) => pickImageFile("secondPhoto", file)}
                onClear={() => clearImage("secondPhoto")}
              />
              <AdminImageField
                label="Terceira foto"
                hint="Opcional · arquivo original (JPG, PNG ou WebP)"
                slotIndex={3}
                slot={form.thirdPhoto}
                fileRef={fileRef3}
                dragOver={dragOver[2]}
                onDragOver={(e) => { e.preventDefault(); setDragOver([dragOver[0], dragOver[1], true, dragOver[3]]); }}
                onDragLeave={() => setDragOver([dragOver[0], dragOver[1], false, dragOver[3]])}
                onDrop={(e) => { e.preventDefault(); setDragOver([dragOver[0], dragOver[1], false, dragOver[3]]); pickImageFile("thirdPhoto", e.dataTransfer.files?.[0]); }}
                onPickFile={(file) => pickImageFile("thirdPhoto", file)}
                onClear={() => clearImage("thirdPhoto")}
              />
              <AdminVideoField
                slot={form.video}
                fileRef={fileRefVideo}
                dragOver={dragOver[3]}
                onDragOver={(e) => { e.preventDefault(); setDragOver([dragOver[0], dragOver[1], dragOver[2], true]); }}
                onDragLeave={() => setDragOver([dragOver[0], dragOver[1], dragOver[2], false])}
                onDrop={(e) => { e.preventDefault(); setDragOver([dragOver[0], dragOver[1], dragOver[2], false]); pickVideoFile(e.dataTransfer.files?.[0]); }}
                onPickFile={pickVideoFile}
                onClear={clearVideo}
              />
            </div>
          </div>

          <div className="form-card" style={{padding:22}}>
            <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Estoque por tamanho</h3>
            <p style={{fontSize:12.5, color:'var(--ink-500)', marginBottom:14, marginTop:0}}>Quantidade disponível de cada número.</p>
            <div className="stock-grid">
              {window.MJ_SIZES.map(s => (
                <div key={s} className="stock-cell">
                  <div className="s">{s}</div>
                  <input
                    type="number"
                    value={form.stock[s] || 0}
                    onChange={(e) => setForm((f) => ({
                      ...f,
                      stock: { ...f.stock, [s]: parseInt(e.target.value, 10) || 0 },
                    }))}
                    min={0}
                  />
                </div>
              ))}
            </div>
            <div style={{marginTop:14, fontSize:13, color:'var(--ink-700)', display:'flex', justifyContent:'space-between'}}>
              <span>Total em estoque:</span>
              <strong style={{color:'var(--denim-900)'}}>{stockTotal} peças</strong>
            </div>
          </div>
        </div>

        <div>
          <div className="form-card" style={{padding:22}}>
            <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Disponibilidade</h3>
            <label style={{display:'flex', alignItems:'center', gap:10, padding:'10px 0', cursor:'pointer'}}>
              <input type="checkbox" checked={form.available} onChange={(e) => set("available", e.target.checked)} style={{accentColor:'var(--denim-700)'}}/>
              <span style={{fontWeight:700, color:'var(--denim-900)', fontSize:14}}>Produto disponível no site</span>
            </label>
            <label className="filter-opt" style={{padding:'6px 0'}}>
              <input type="checkbox" checked={form.isNew} onChange={(e) => set("isNew", e.target.checked)} style={{accentColor:'var(--denim-700)'}}/>
              Marcar como "Novo"
            </label>
            <label className="filter-opt" style={{padding:'6px 0'}}>
              <input type="checkbox" checked={form.isPromo} onChange={(e) => set("isPromo", e.target.checked)} style={{accentColor:'var(--denim-700)'}}/>
              Marcar como "Promoção"
            </label>
          </div>

          <div className="form-card" style={{padding:22}}>
            <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Pré-visualização</h3>
            <div style={{maxWidth:200, margin:'0 auto'}}>
              <div className="card style-minimal" style={{cursor:'default'}}>
                <div className="ph-wrap">
                  <ProductPhoto
                    src={form.mainPhoto.previewUrl || form.mainPhoto.listingUrl || form.mainPhoto.productUrl}
                    seed={(form.id || "new") + "_prev"}
                    tone={colorHex}
                    alt="Pré-visualização"
                  />
                </div>
                <div className="name">{form.name || "Nome do produto"}</div>
                <div className="price">{previewPrice ? fmt(previewPrice) : "R$ 0,00"}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function AdminStock({ products, loading, toast }) {
  if (loading) {
    return (
      <>
        <h2>Controle de estoque</h2>
        <p className="sub" style={{color:'var(--ink-500)'}}>Carregando…</p>
      </>
    );
  }

  return (
    <>
      <h2>Controle de estoque</h2>
      <p className="sub">Edite pelo formulário do produto (salva no Supabase).</p>
      <div style={{display:'flex', gap:8, marginBottom:18}}>
        <div className="search" style={{maxWidth:280, padding:'8px 14px', margin:0}}>
          <Icon.Search s={14}/>
          <input placeholder="Buscar produto..."/>
        </div>
      </div>
      <table className="admin-table">
        <thead>
          <tr>
            <th>Produto</th>
            {window.MJ_SIZES.map(s => <th key={s} style={{textAlign:'center'}}>{s}</th>)}
            <th style={{textAlign:'right'}}>Total</th>
          </tr>
        </thead>
        <tbody>
          {products.map(p => {
            const total = Object.values(p.stock).reduce((a, b) => a + b, 0);
            return (
              <tr key={p.id}>
                <td className="prod">
                  <div className="mini-img"><ProductPhoto src={p.fotoListing || p.foto1 || p.imageUrl || p.images?.[0]} seed={p.id} tone={p.colorHex} alt=""/></div>
                  <div>
                    <div className="mini-name" style={{fontSize:12.5}}>{p.name}</div>
                    <div className="mini-sku">{p.sku}</div>
                  </div>
                </td>
                {window.MJ_SIZES.map(s => (
                  <td key={s} style={{textAlign:'center'}}>
                    <input type="number" defaultValue={p.stock[s] || 0} min={0}
                      style={{
                        width: 44,
                        border:'1px solid var(--denim-100)',
                        borderRadius:4,
                        padding:'5px',
                        textAlign:'center',
                        fontSize:13,
                        background: (p.stock[s] || 0) === 0 ? 'var(--cream-100)' : '#fff',
                        color: (p.stock[s] || 0) === 0 ? 'var(--ink-500)' : 'var(--denim-900)',
                        fontWeight:600
                      }}/>
                  </td>
                ))}
                <td style={{textAlign:'right', fontWeight:700, color:'var(--denim-900)'}}>{total}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
}

function AdminSettings() {
  return (
    <>
      <h2>Configurações da loja</h2>
      <p className="sub">Dados da loja, pagamento, frete e integrações.</p>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
        <div className="form-card" style={{padding:22}}>
          <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Dados da loja</h3>
          <div className="form-grid">
            <div className="form-field f-6"><label>Nome</label><input placeholder="Nome da loja"/></div>
            <div className="form-field f-6"><label>CNPJ</label><input placeholder="00.000.000/0000-00"/></div>
            <div className="form-field f-6"><label>Endereço</label><input placeholder="Rua, número — cidade/UF"/></div>
            <div className="form-field f-6"><label>WhatsApp</label><input placeholder="(00) 0 0000-0000"/></div>
          </div>
        </div>
        <div className="form-card" style={{padding:22}}>
          <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Pagamento</h3>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> PIX</label>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> Cartão de crédito (até 3x sem juros)</label>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> Boleto bancário</label>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> WhatsApp (atendimento)</label>
          <div style={{marginTop:14, padding:14, background:'var(--cream-50)', borderRadius:6, fontSize:12.5, color:'var(--ink-700)', display:'flex', gap:10}}>
            <Icon.Alert s={14}/>
            <div>Conecte um gateway (Mercado Pago, Stripe, PagSeguro) para processar pagamentos online.</div>
          </div>
        </div>
        <div className="form-card" style={{padding:22}}>
          <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Frete</h3>
          <div className="form-grid">
            <div className="form-field f-6"><label>Frete grátis acima de (desativado)</label><input placeholder="—" disabled/></div>
            <div className="form-field f-6"><label>Frete fixo Brasil</label><input placeholder="R$ 0,00"/></div>
          </div>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> Integração Correios (SEDEX + PAC)</label>
          <label className="filter-opt" style={{padding:'10px 0'}}><input type="checkbox" style={{accentColor:'var(--denim-700)'}}/> Transportadora parceira</label>
        </div>
        <div className="form-card" style={{padding:22}}>
          <h3 style={{fontFamily:'var(--font-display)', fontSize:16, marginTop:0, marginBottom:14, color:'var(--denim-900)'}}>Integrações</h3>
          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            {["Mercado Pago", "Correios", "Google Analytics", "Meta Pixel", "Mailchimp"].map((it) => (
              <div key={it} style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', background:'var(--cream-50)', borderRadius:6}}>
                <div style={{fontSize:13, fontWeight:600, color:'var(--denim-900)'}}>{it}</div>
                <span className="tag tag-low">Conectar</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

// === Institutional ===
function ScreenInstitutional({ route, go }) {
  const tab = route.params?.tab || "sobre";
  const setTab = (t) => go("inst", { tab: t });
  const [openFaq, setOpenFaq] = useState(0);

  return (
    <div className="inst-page">
      <div className="crumbs">
        <a onClick={() => go("home")}><Icon.Home s={12}/></a>
        <span className="sep">/</span>
        <span className="curr">Institucional</span>
      </div>

      <div className="inst-tabs">
        {[
          {id:"sobre", label:"Sobre a loja"},
          {id:"entrega", label:"Política de entrega"},
          {id:"trocas", label:"Trocas e devoluções"},
          {id:"contato", label:"Contato"},
          {id:"faq", label:"FAQ"},
          {id:"privacidade", label:"Privacidade"},
        ].map(t => (
          <button key={t.id} className={"tab-btn" + (tab === t.id ? " on" : "")} onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === "sobre" && (
        <div className="inst-grid">
          <div>
            <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Quem somos</span>
            <h1>Mania De Jeans CG — direto de Campo Grande para todo o Brasil.</h1>
            <div className="inst-body">
              <p>A história da Mania de Jeans se inicia com uma amizade de duas amigas e um sonho de construir algo para fazer a diferença na vida das mulheres com um objetivo maior do que estilo, trazendo conforto, qualidade, autoestima e confiabilidade para nossos clientes.</p>
              <p>A <strong>Mania De Jeans CG</strong> nasceu em Campo Grande, Mato Grosso do Sul, com um propósito simples: oferecer calças jeans femininas <strong>bem feitas, com caimento testado e por um preço justo</strong>.</p>
            </div>
          </div>
          <div>
            <div style={{position:'relative', borderRadius:12, overflow:'hidden', aspectRatio:'4/5', marginBottom:14}}>
              <DenimPlaceholder label="Foto · Equipe Mania" seed="sobre-1" tone="#2a4769"/>
            </div>
            <div className="inst-card">
              <div style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', fontWeight:700, color:'var(--ink-500)', marginBottom:6}}>Nossa loja</div>
              <div style={{fontWeight:700, color:'var(--denim-900)', marginBottom:8, fontSize:15}}>Campo Grande - MS</div>
              <div style={{fontSize:13, color:'var(--ink-700)', lineHeight:1.6, marginBottom:14}}>
                Centro de operações e showroom para atendimento agendado.<br/>
                Seg a Sex · 9h às 18h · Sáb · 9h às 14h
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, fontSize:12, color:'var(--ink-700)'}}>
                <div><strong style={{color:'var(--denim-900)'}}>WhatsApp</strong><br/>{window.MJ_WHATSAPP.display}</div>
                <div><strong style={{color:'var(--denim-900)'}}>E-mail</strong><br/>oi@maniadejeanscg.com.br</div>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === "entrega" && (
        <div className="inst-grid">
          <div>
            <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Entrega</span>
            <h1>Política de entrega</h1>
            <div className="inst-body">
              <p><strong>Enviamos para todo o Brasil</strong> via Correios (SEDEX e PAC) e transportadoras parceiras. O prazo começa a contar a partir da confirmação do pagamento.</p>
              <h3>Prazos por região</h3>
              <p><strong>Centro-Oeste:</strong> 1 a 3 dias úteis<br/>
              <strong>Sudeste e Sul:</strong> 3 a 6 dias úteis<br/>
              <strong>Nordeste:</strong> 5 a 8 dias úteis<br/>
              <strong>Norte:</strong> 6 a 10 dias úteis</p>
              <h3>Valor do frete</h3>
              <p>Calculamos automaticamente pelo seu CEP (PAC e SEDEX dos Correios).</p>
              <h3>Rastreamento</h3>
              <p>Assim que o pedido é despachado, enviamos o código de rastreio por e-mail e WhatsApp.</p>
            </div>
          </div>
          <div className="inst-card">
            <div style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', fontWeight:700, color:'var(--ink-500)', marginBottom:14}}>Resumo</div>
            <div style={{display:'flex', flexDirection:'column', gap:14}}>
              {[
                {ic: <Icon.Truck s={20}/>, t:"Frete pelos Correios", s:"PAC e SEDEX conforme seu CEP"},
                {ic: <Icon.Box s={20}/>, t:"Embalagem cuidada", s:"Suas peças chegam impecáveis"},
                {ic: <Icon.Pin s={16}/>, t:"De Campo Grande - MS", s:"Despachamos em até 24h úteis"},
                {ic: <Icon.Bolt s={16}/>, t:"Pedidos até 14h", s:"Saem no mesmo dia útil"},
              ].map((it, i) => (
                <div key={i} style={{display:'flex', gap:14, alignItems:'flex-start'}}>
                  <div style={{width:40, height:40, borderRadius:'50%', background:'var(--denim-700)', color:'#fff', display:'grid', placeItems:'center', flexShrink:0}}>{it.ic}</div>
                  <div>
                    <div style={{fontWeight:700, color:'var(--denim-900)', fontSize:14}}>{it.t}</div>
                    <div style={{fontSize:13, color:'var(--ink-700)', marginTop:2}}>{it.s}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {tab === "trocas" && (
        <div className="inst-grid">
          <div>
            <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Trocas e devoluções</span>
            <h1>Trocou de ideia? Tudo certo.</h1>
            <div className="inst-body">
              <p>Você tem <strong>7 dias corridos</strong> a partir do recebimento para solicitar troca ou devolução. Basta nos chamar no WhatsApp.</p>
              <h3>O que precisa</h3>
              <p>· A peça <strong>sem uso</strong>, com etiqueta original e na embalagem<br/>
              · Nota fiscal ou o número do pedido<br/>
              · Combinar com nosso atendimento o motivo (troca de tamanho, modelo ou devolução)</p>
              <h3>Quem paga o frete</h3>
              <p>A <strong>primeira troca por tamanho é gratuita</strong> — emitimos o código de postagem reversa. Para devoluções por arrependimento, o frete de retorno é por sua conta.</p>
              <h3>Reembolso</h3>
              <p>Após recebermos a peça e conferirmos, o reembolso é feito em até 5 dias úteis pelo mesmo meio de pagamento da compra.</p>
            </div>
          </div>
          <div className="inst-card">
            <div style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', fontWeight:700, color:'var(--ink-500)', marginBottom:14}}>Passo a passo</div>
            {["Chame no WhatsApp em até 7 dias","Combine o tipo de troca ou devolução","Postamos o código reverso para você","Despache a peça nos Correios","Em até 5 dias úteis processamos o reembolso ou enviamos o novo tamanho"].map((s, i) => (
              <div key={i} style={{display:'flex', gap:12, alignItems:'flex-start', marginBottom:12}}>
                <div style={{width:24, height:24, borderRadius:'50%', background:'var(--denim-700)', color:'#fff', display:'grid', placeItems:'center', fontSize:12, fontWeight:700, flexShrink:0}}>{i+1}</div>
                <div style={{fontSize:13.5, color:'var(--ink-700)', lineHeight:1.5}}>{s}</div>
              </div>
            ))}
            <a className="btn btn-wp btn-block" style={{marginTop:12}} href={window.MJ_WHATSAPP.url} target="_blank" rel="noopener noreferrer"><Icon.WhatsApp s={16}/> Iniciar pelo WhatsApp</a>
          </div>
        </div>
      )}

      {tab === "contato" && (
        <div className="inst-grid">
          <div>
            <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Atendimento</span>
            <h1>Fale com a gente</h1>
            <div className="inst-body">
              <p>Estamos aqui para ajudar com dúvidas sobre tamanho, lavagem, prazos ou qualquer outra coisa. <strong>Resposta em até 15 minutos</strong> no horário comercial.</p>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:18}}>
              <a href={window.MJ_WHATSAPP.url} target="_blank" rel="noopener noreferrer" style={{background:'var(--wp)', color:'#fff', borderRadius:10, padding:20, display:'block'}}>
                <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:10}}>
                  <Icon.WhatsApp s={28}/>
                  <strong style={{fontSize:14, letterSpacing:'0.06em', textTransform:'uppercase'}}>WhatsApp</strong>
                </div>
                <div style={{fontFamily:'var(--font-display)', fontSize:22, fontWeight:700, letterSpacing:'-0.02em'}}>{window.MJ_WHATSAPP.display}</div>
                <div style={{fontSize:12, marginTop:6, opacity:0.85}}>Resposta em até 15 min</div>
              </a>
              <div style={{background:'var(--denim-700)', color:'#fff', borderRadius:10, padding:20}}>
                <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:10}}>
                  <Icon.User s={20}/>
                  <strong style={{fontSize:14, letterSpacing:'0.06em', textTransform:'uppercase'}}>E-mail</strong>
                </div>
                <div style={{fontFamily:'var(--font-display)', fontSize:18, fontWeight:700, letterSpacing:'-0.01em'}}>oi@maniadejeanscg.com.br</div>
                <div style={{fontSize:12, marginTop:6, opacity:0.85}}>Resposta em até 24h</div>
              </div>
            </div>
            <div style={{marginTop:18, padding:18, background:'var(--cream-50)', borderRadius:10}}>
              <div style={{fontSize:12, color:'var(--ink-500)', fontWeight:700, letterSpacing:'0.12em', textTransform:'uppercase', marginBottom:6}}><Icon.Pin s={12} style={{verticalAlign:'middle'}}/> Endereço</div>
              <div style={{fontSize:14, color:'var(--denim-900)', fontWeight:600}}>Rua Exemplo, 123 — Centro<br/>Campo Grande - MS · CEP 79002-000</div>
              <div style={{fontSize:12.5, color:'var(--ink-500)', marginTop:6}}>Atendimento presencial somente com agendamento</div>
            </div>
          </div>

          <div className="inst-card">
            <div style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', fontWeight:700, color:'var(--ink-500)', marginBottom:14}}>Envie sua mensagem</div>
            <div className="form-grid">
              <div className="form-field f-6"><label>Nome</label><input/></div>
              <div className="form-field f-6"><label>E-mail</label><input/></div>
              <div className="form-field f-6"><label>WhatsApp</label><input placeholder="(00) 00000-0000"/></div>
              <div className="form-field f-6"><label>Assunto</label>
                <select><option>Dúvida sobre produto</option><option>Pedido / entrega</option><option>Troca ou devolução</option><option>Parceria</option><option>Outro</option></select>
              </div>
              <div className="form-field f-6">
                <label>Mensagem</label>
                <textarea rows={5} style={{border:'1px solid var(--denim-200)', borderRadius:6, padding:'11px 12px', fontSize:14, resize:'vertical'}}/>
              </div>
            </div>
            <button className="btn btn-primary btn-block" style={{marginTop:14}}>Enviar mensagem</button>
          </div>
        </div>
      )}

      {tab === "faq" && (
        <div style={{maxWidth:780, margin:'0 auto'}}>
          <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Suporte</span>
          <h1 style={{fontFamily:'var(--font-display)', fontSize:'clamp(28px,4vw,42px)', letterSpacing:'-0.03em', margin:'10px 0 28px', color:'var(--denim-900)'}}>Perguntas frequentes</h1>
          <div>
            {window.MJ_FAQS.map((f, i) => (
              <div key={i} className={"faq-item" + (openFaq === i ? " open" : "")} onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                <div className="faq-q">{f.q}<span className="ic"><Icon.Plus s={18}/></span></div>
                <div className="faq-a">{f.a}</div>
              </div>
            ))}
          </div>
          <div style={{marginTop:36, padding:22, background:'var(--cream-50)', borderRadius:10, textAlign:'center'}}>
            <div style={{fontWeight:700, color:'var(--denim-900)', marginBottom:6, fontSize:15}}>Não encontrou o que procurava?</div>
            <div style={{fontSize:13, color:'var(--ink-700)', marginBottom:14}}>Fale com a gente direto pelo WhatsApp — respondemos rápido.</div>
            <a className="btn btn-wp" href={window.MJ_WHATSAPP.url} target="_blank" rel="noopener noreferrer"><Icon.WhatsApp s={16}/> Falar no WhatsApp</a>
          </div>
        </div>
      )}

      {tab === "privacidade" && (
        <div style={{maxWidth:780, margin:'0 auto'}}>
          <span style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'var(--ink-500)', fontWeight:700}}>Privacidade</span>
          <h1 style={{fontFamily:'var(--font-display)', fontSize:'clamp(28px,4vw,42px)', letterSpacing:'-0.03em', margin:'10px 0 24px', color:'var(--denim-900)'}}>Política de privacidade</h1>
          <div className="inst-body">
            <p>Esta política descreve como tratamos as informações coletadas no site da Mania De Jeans CG. Estamos em conformidade com a Lei Geral de Proteção de Dados (LGPD).</p>
            <h3>Dados que coletamos</h3>
            <p>Nome, e-mail, WhatsApp, CPF e endereço — usados exclusivamente para processar e entregar seu pedido. Não vendemos seus dados.</p>
            <h3>Segurança</h3>
            <p>Os dados são armazenados em servidores criptografados e o pagamento é processado por gateways certificados (PCI-DSS).</p>
            <h3>Seus direitos</h3>
            <p>Você pode solicitar a qualquer momento o acesso, correção ou exclusão dos seus dados. Basta enviar um e-mail para <strong>privacidade@maniadejeanscg.com.br</strong>.</p>
            <h3>Cookies</h3>
            <p>Usamos cookies essenciais para o funcionamento do site e cookies analíticos (Google Analytics) para melhorar sua experiência. Você pode desativar nas preferências do navegador.</p>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenAdmin, ScreenInstitutional });
