/* ============ Admin Panel ============ */

/* ---------- Reusable: comma-separated list input ----------
 * Avoids the classic bug of binding the input to the joined array — that
 * makes any trailing separator disappear mid-typing because `.filter(Boolean)`
 * eats partial fragments. We keep a local string buffer for the textbox and
 * only update the parent array on every change (without filtering empties).
 * On blur we re-normalize the buffer from the parent array. */
function SizesInput({ value, onChange, placeholder = "5, 6, 7, 8, 9" }) {
  const [text, setText] = useState(() => (value || []).join(", "));
  // Re-sync the buffer when the parent value changes from outside
  // (e.g. switching products in the editor). Compare by serialized contents.
  const joined = (value || []).join("|");
  useEffect(() => { setText((value || []).join(", ")); }, [joined]);
  return (
    <input
      value={text}
      onChange={(e) => {
        const next = e.target.value;
        setText(next);
        onChange(next.split(",").map(s => s.trim()).filter(Boolean));
      }}
      onBlur={() => setText((value || []).join(", "))}
      placeholder={placeholder}
    />
  );
}

/* ---------- Reusable: image uploader (Supabase Storage) ---------- */
function ImageUploader({ value, onChange, label = "Imagen", aspect = "4/5", help, prefix = "site" }) {
  const inputRef = useRef(null);
  const [busy, setBusy] = useState(false);
  async function pick(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    setBusy(true);
    try {
      const url = await window.kiroStorage.uploadImage(file, prefix, { maxW: 1800, quality: 0.88 });
      // best-effort cleanup of the previous image
      if (value) { try { await window.kiroStorage.deleteImageByUrl(value); } catch (_) {} }
      onChange(url);
    } catch (err) {
      alert("No se pudo subir la imagen: " + (err.message || err));
      console.error(err);
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }
  async function clear() {
    if (value) { try { await window.kiroStorage.deleteImageByUrl(value); } catch (_) {} }
    onChange(null);
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--burgundy)", fontWeight: 600 }}>{label}</div>
      <div style={{
        aspectRatio: aspect, position: "relative", background: "var(--cream)",
        border: "1px dashed var(--line)", overflow: "hidden",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        {value ? (
          <img src={value} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
        ) : (
          <div style={{ fontSize: 12, color: "var(--ink-2)", textAlign: "center", padding: 12 }}>
            Sin imagen.<br/>Sube una foto desde tu equipo.
          </div>
        )}
        {busy && (
          <div style={{ position: "absolute", inset: 0, background: "rgba(251,244,241,0.7)",
            display: "flex", alignItems: "center", justifyContent: "center" }}>
            <span className="spinner"/>
          </div>
        )}
      </div>
      <input ref={inputRef} type="file" accept="image/*" onChange={pick} style={{ display: "none" }}/>
      <div style={{ display: "flex", gap: 6 }}>
        <button type="button" className="btn btn-ghost btn-sm" onClick={()=>inputRef.current?.click()} style={{ flex: 1 }}>
          {value ? "Cambiar" : "Subir imagen"}
        </button>
        {value && (
          <button type="button" className="btn btn-ghost btn-sm" onClick={clear}
            style={{ color: "var(--burgundy-soft)" }}>
            Quitar
          </button>
        )}
      </div>
      {help && <div style={{ fontSize: 11, color: "var(--ink-2)", lineHeight: 1.5 }}>{help}</div>}
    </div>
  );
}

/* ---------- Reusable: multi-image uploader (for product galleries) ---------- */
function ImageGalleryUploader({ value = [], onChange, max = 6, prefix = "products" }) {
  const inputRef = useRef(null);
  const [busy, setBusy] = useState(false);
  async function add(e) {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setBusy(true);
    try {
      const uploaded = [];
      for (const f of files) {
        if (value.length + uploaded.length >= max) break;
        const url = await window.kiroStorage.uploadImage(f, prefix, { maxW: 1400, quality: 0.85 });
        uploaded.push(url);
      }
      onChange([...value, ...uploaded]);
    } catch (err) {
      alert("No se pudo subir alguna imagen: " + (err.message || err));
      console.error(err);
    } finally {
      setBusy(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }
  const remove = async (i) => {
    const url = value[i];
    if (url) { try { await window.kiroStorage.deleteImageByUrl(url); } catch (_) {} }
    onChange(value.filter((_, idx) => idx !== i));
  };
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= value.length) return;
    const next = [...value];
    [next[i], next[j]] = [next[j], next[i]];
    onChange(next);
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--burgundy)", fontWeight: 600 }}>
        Galería ({value.length}/{max})
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>
        {value.map((src, i) => (
          <div key={i} style={{ position: "relative", aspectRatio: "1", background: "var(--cream)", border: "1px solid var(--line-2)" }}>
            <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
            <div style={{ position: "absolute", top: 4, left: 4, fontSize: 10,
              background: "rgba(107,31,37,0.85)", color: "var(--pink-50)", padding: "2px 6px", letterSpacing: "0.1em" }}>
              {i + 1}
            </div>
            <div style={{ position: "absolute", bottom: 4, left: 4, right: 4, display: "flex", gap: 4 }}>
              <button type="button" onClick={()=>move(i, -1)} disabled={i===0}
                style={{ flex: 1, background: "rgba(251,244,241,0.9)", border: 0, fontSize: 11, padding: 2, cursor: "pointer" }}>←</button>
              <button type="button" onClick={()=>move(i, 1)} disabled={i===value.length-1}
                style={{ flex: 1, background: "rgba(251,244,241,0.9)", border: 0, fontSize: 11, padding: 2, cursor: "pointer" }}>→</button>
              <button type="button" onClick={()=>remove(i)}
                style={{ flex: 1, background: "rgba(107,31,37,0.85)", color: "var(--pink-50)", border: 0, fontSize: 11, padding: 2, cursor: "pointer" }}>×</button>
            </div>
          </div>
        ))}
        {value.length < max && (
          <button type="button" onClick={()=>inputRef.current?.click()}
            style={{ aspectRatio: "1", background: "var(--cream)", border: "1px dashed var(--line)",
              cursor: "pointer", color: "var(--burgundy)", fontSize: 22 }}>
            {busy ? <span className="spinner"/> : "+"}
          </button>
        )}
      </div>
      <input ref={inputRef} type="file" accept="image/*" multiple onChange={add} style={{ display: "none" }}/>
      <div style={{ fontSize: 11, color: "var(--ink-2)" }}>
        La primera imagen es la principal. Usa ← → para reordenar.
      </div>
    </div>
  );
}

function AdminPage({ store, setStore, navigate, refreshStore }) {
  const [session, setSession] = useState(null);
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    let mounted = true;
    window.kiroAuth.getSession().then(s => {
      if (!mounted) return;
      setSession(s);
      setChecking(false);
    });
    const unsub = window.kiroAuth.onAuthChange((s) => { if (mounted) setSession(s); });
    return () => { mounted = false; unsub && unsub(); };
  }, []);

  if (checking) {
    return (
      <div style={{ minHeight: "calc(100vh - 80px)", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)" }}>
        <span className="spinner" style={{ color: "var(--burgundy)" }}/>
      </div>
    );
  }
  if (!session) return <AdminLogin navigate={navigate}/>;

  return <AdminDashboard store={store} setStore={setStore} navigate={navigate}
    refreshStore={refreshStore}
    session={session}
    onLogout={async () => { await window.kiroAuth.signOut(); }}/>;
}

function AdminLogin({ navigate }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [err, setErr]   = useState("");
  const [busy, setBusy] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setErr("");
    if (!email.trim() || !password) { setErr("Ingresa correo y contraseña."); return; }
    setBusy(true);
    try {
      await window.kiroAuth.signIn(email.trim(), password);
      // AdminPage onAuthChange listener will pick up the new session and re-render.
    } catch (e2) {
      const msg = e2?.message || "";
      if (msg.toLowerCase().includes("invalid")) setErr("Correo o contraseña incorrectos.");
      else setErr(msg || "No se pudo iniciar sesión.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{
      minHeight: "calc(100vh - 80px)",
      display: "grid", gridTemplateColumns: "1fr 1fr",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 48, background: "var(--bg)",
      }}>
        <form onSubmit={submit} style={{
          width: "100%", maxWidth: 380,
          display: "flex", flexDirection: "column", gap: 20,
        }}>
          <div>
            <BrandLogo size={26}/>
          </div>
          <div>
            <div className="eyebrow">Panel privado</div>
            <h1 style={{
              fontFamily: "var(--serif)", fontWeight: 400,
              fontSize: 44, lineHeight: 1.05, letterSpacing: "-0.01em",
              color: "var(--burgundy)", margin: "12px 0 8px",
            }}>Iniciar sesión</h1>
            <p style={{ fontSize: 14, color: "var(--ink-2)" }}>
              Acceso solo para el equipo de KIRO. Edita catálogo, precios y categorías.
            </p>
          </div>

          <div className="field">
            <label htmlFor="email">Correo</label>
            <input id="email" type="email" value={email} onChange={e=>setEmail(e.target.value)}
              autoComplete="email" placeholder="tu@correo.com"/>
          </div>
          <div className="field">
            <label htmlFor="pass">Contraseña</label>
            <input id="pass" type="password" value={password} onChange={e=>setPassword(e.target.value)}
              autoComplete="current-password" placeholder="••••••••"/>
          </div>

          {err && <div style={{ fontSize: 13, color: "var(--burgundy)",
            background: "var(--pink-100)", padding: 10, border: "1px solid var(--line)" }}>{err}</div>}

          <button type="submit" className="btn btn-lg" disabled={busy}>
            {busy ? <><span className="spinner"/> Entrando…</> : "Entrar al panel"}
          </button>

          <a onClick={()=>navigate("/")} style={{
            cursor: "pointer", fontSize: 12, letterSpacing: "0.16em",
            textTransform: "uppercase", color: "var(--ink-2)", textAlign: "center"
          }}>← Volver a la tienda</a>
        </form>
      </div>
      <div style={{
        background: "var(--burgundy)",
        position: "relative", overflow: "hidden",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <div className="img-ph dark" style={{ position: "absolute", inset: 0, border: 0 }}>
          <svg viewBox="0 0 600 800" preserveAspectRatio="xMidYMid slice"
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.5 }}>
            <g stroke="rgba(252,234,231,0.3)" strokeWidth="1" fill="none">
              <circle cx="300" cy="400" r="160"/>
              <circle cx="300" cy="400" r="180"/>
              <path d="M260 200 L300 160 L340 200 L320 240 L280 240 Z"/>
            </g>
          </svg>
        </div>
        <div style={{
          position: "relative", color: "var(--pink-50)",
          padding: 48, maxWidth: 460, textAlign: "center",
        }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 64, fontStyle: "italic",
            fontWeight: 300, lineHeight: 1.1, marginBottom: 16 }}>
            "Hecho a mano, pieza por pieza."
          </div>
          <div className="eyebrow" style={{ color: "var(--pink-200)" }}>
            Estudio KIRO · Lima → Cusco · 2026
          </div>
        </div>
      </div>
    </div>
  );
}

function AdminDashboard({ store, setStore, navigate, refreshStore, session, onLogout }) {
  const [tab, setTab] = useState("products"); // products | categories | overview | content
  const [editingId, setEditingId] = useState(null);
  const [creating, setCreating] = useState(false);
  const [search, setSearch] = useState("");
  const [filterCat, setFilterCat] = useState("all");
  const [busy, setBusy] = useState(false);

  // metrics
  const totalSKUs = store.products.length;
  const inventoryValue = store.products.reduce((s,p)=>s+p.price, 0);
  const avgPrice = Math.round(inventoryValue / Math.max(1, totalSKUs));

  async function withBusy(fn) {
    setBusy(true);
    try { await fn(); }
    catch (err) {
      console.error(err);
      alert("Error: " + (err?.message || err));
    }
    finally { setBusy(false); }
  }

  function deleteProduct(id) {
    if (!confirm("¿Eliminar esta pieza? No se puede deshacer.")) return;
    withBusy(async () => {
      const p = store.products.find(x => x.id === id);
      if (p && Array.isArray(p.images)) {
        for (const url of p.images) {
          try { await window.kiroStorage.deleteImageByUrl(url); } catch (_) {}
        }
      }
      await window.kiroDB.deleteProductById(id);
      await refreshStore();
    });
  }
  function saveProduct(prod) {
    withBusy(async () => {
      await window.kiroDB.upsertProduct(prod);
      await refreshStore();
      setEditingId(null);
      setCreating(false);
    });
  }
  function deleteCategory(id) {
    const usedBy = store.products.filter(p => p.category === id).length;
    if (usedBy > 0) {
      alert(`No se puede eliminar: ${usedBy} producto(s) usan esta categoría.`);
      return;
    }
    if (!confirm("¿Eliminar esta categoría?")) return;
    withBusy(async () => {
      await window.kiroDB.deleteCategoryById(id);
      await refreshStore();
    });
  }
  function saveCategory(cat) {
    withBusy(async () => {
      await window.kiroDB.upsertCategory(cat);
      await refreshStore();
    });
  }
  function resetSeed() {
    if (!confirm("¿Restaurar catálogo a los valores de fábrica? Sobrescribirá productos, categorías y contenido actuales.")) return;
    withBusy(async () => {
      await window.kiroDB.seedCatalog({
        categories: SEED_CATEGORIES, products: SEED_PRODUCTS, content: SEED_CONTENT,
      });
      await refreshStore();
    });
  }

  const visibleProducts = store.products.filter(p => {
    if (filterCat !== "all" && p.category !== filterCat) return false;
    if (search && !p.name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", minHeight: "calc(100vh - 80px)" }}>
      {/* Sidebar */}
      <aside style={{
        background: "var(--burgundy)", color: "var(--pink-100)",
        padding: "32px 24px", display: "flex", flexDirection: "column", gap: 24,
        position: "sticky", top: 0, height: "100vh",
      }}>
        <div onClick={()=>navigate("/")} style={{ cursor: "pointer" }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 26, letterSpacing: "0.16em", color: "var(--pink-50)" }}>KIRO</div>
          <div style={{ fontSize: 10, letterSpacing: "0.3em", color: "var(--pink-200)", marginTop: 2 }}>ADMIN PANEL</div>
        </div>
        <nav style={{ display: "flex", flexDirection: "column", gap: 2, marginTop: 12 }}>
          {[
            { id: "overview",   label: "Resumen",     icon: "chart" },
            { id: "products",   label: "Productos",   icon: "tag" },
            { id: "categories", label: "Categorías",  icon: "box" },
            { id: "content",    label: "Contenido",   icon: "edit" },
          ].map(t => (
            <button key={t.id}
              onClick={()=>{setTab(t.id); setEditingId(null); setCreating(false);}}
              style={{
                background: tab === t.id ? "var(--burgundy-deep)" : "transparent",
                color: tab === t.id ? "var(--pink-50)" : "var(--pink-200)",
                border: 0, padding: "12px 14px", textAlign: "left",
                display: "flex", gap: 12, alignItems: "center",
                fontSize: 13, letterSpacing: "0.08em", fontWeight: 500,
              }}>
              <Icon name={t.icon} size={16}/>
              {t.label}
            </button>
          ))}
        </nav>

        <div style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: 8,
          padding: 16, background: "var(--burgundy-deep)",
          fontSize: 12, color: "var(--pink-200)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%",
              background: "var(--pink-100)", color: "var(--burgundy)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontWeight: 700, fontSize: 13, fontFamily: "var(--serif)" }}>K</div>
            <div style={{ minWidth: 0, overflow: "hidden" }}>
              <div style={{ color: "var(--pink-50)", fontWeight: 600 }}>Admin</div>
              <div style={{ fontSize: 10, letterSpacing: "0.1em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {session?.user?.email || "—"}
              </div>
            </div>
          </div>
          <button onClick={onLogout}
            style={{ background: "transparent", border: "1px solid rgba(252,234,231,0.3)",
              color: "var(--pink-100)", padding: "8px 12px", fontSize: 11,
              letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 600,
              marginTop: 6 }}>
            Cerrar sesión
          </button>
        </div>
      </aside>

      {/* Main */}
      <div style={{ padding: 40, background: "var(--cream)", minHeight: "100vh" }}>
        {tab === "overview" && (
          <>
            <h1 style={{ fontFamily: "var(--serif)", fontSize: 44, fontWeight: 400,
              color: "var(--burgundy)", margin: "0 0 8px" }}>Resumen</h1>
            <p style={{ color: "var(--ink-2)", marginBottom: 32 }}>Vista rápida de tu catálogo.</p>

            {store.products.length === 0 && store.categories.length === 0 && (
              <div style={{ background: "#fff", padding: 24, border: "1px solid var(--burgundy)",
                marginBottom: 24, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 20 }}>
                <div>
                  <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
                    color: "var(--burgundy-soft)", fontWeight: 600 }}>Catálogo vacío</div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--burgundy)", marginTop: 4 }}>
                    Aún no has agregado piezas
                  </div>
                  <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 6 }}>
                    Puedes empezar con un catálogo de muestra (4 categorías, 12 productos, contenido base) y editar desde ahí.
                  </div>
                </div>
                <button className="btn" onClick={resetSeed} disabled={busy}>
                  {busy ? <><span className="spinner"/> Cargando…</> : "Cargar catálogo de muestra"}
                </button>
              </div>
            )}

            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 32 }}>
              <Stat k="Productos" v={totalSKUs} sub="Total en catálogo"/>
              <Stat k="Categorías" v={store.categories.length} sub="Activas"/>
              <Stat k="Precio promedio" v={fmtPrice(avgPrice)} sub="Por pieza"/>
              <Stat k="Valor inventario" v={fmtPrice(inventoryValue)} sub="Suma del catálogo"/>
            </div>

            <div style={{ background: "#fff", padding: 32, border: "1px solid var(--line-2)" }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, color: "var(--burgundy)", margin: "0 0 16px" }}>
                Por categoría
              </h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {store.categories.map(c => {
                  const count = store.products.filter(p => p.category === c.id).length;
                  const pct = (count / Math.max(1,totalSKUs)) * 100;
                  return (
                    <div key={c.id}>
                      <div style={{ display: "flex", justifyContent: "space-between",
                        fontSize: 13, marginBottom: 6 }}>
                        <span style={{ fontWeight: 600 }}>{c.name}</span>
                        <span style={{ color: "var(--ink-2)" }}>{count} piezas</span>
                      </div>
                      <div style={{ background: "var(--pink-100)", height: 6 }}>
                        <div style={{ width: pct+"%", height: "100%", background: "var(--burgundy)" }}/>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

          </>
        )}

        {tab === "products" && !editingId && !creating && (
          <>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32 }}>
              <div>
                <h1 style={{ fontFamily: "var(--serif)", fontSize: 44, fontWeight: 400,
                  color: "var(--burgundy)", margin: "0 0 8px" }}>Productos</h1>
                <p style={{ color: "var(--ink-2)", margin: 0 }}>
                  {store.products.length} piezas en catálogo. Edita, agrega o elimina sin tocar código.
                </p>
              </div>
              <button className="btn" onClick={()=>setCreating(true)}>
                <Icon name="plus" size={14}/> Agregar producto
              </button>
            </div>

            <div style={{ display: "flex", gap: 12, marginBottom: 20 }}>
              <input value={search} onChange={e=>setSearch(e.target.value)}
                placeholder="Buscar por nombre…"
                style={{
                  background: "#fff", border: "1px solid var(--line)",
                  padding: "12px 14px", flex: 1, fontFamily: "var(--sans)",
                  fontSize: 14, outline: "none",
                }}/>
              <select value={filterCat} onChange={e=>setFilterCat(e.target.value)}
                style={{
                  background: "#fff", border: "1px solid var(--line)",
                  padding: "12px 14px", fontFamily: "var(--sans)", fontSize: 14,
                  color: "var(--ink)", outline: "none", minWidth: 180,
                }}>
                <option value="all">Todas las categorías</option>
                {store.categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>

            <div style={{ background: "#fff", border: "1px solid var(--line-2)" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
                <thead>
                  <tr style={{ background: "var(--pink-100)", textAlign: "left" }}>
                    <th style={th}>Producto</th>
                    <th style={th}>Categoría</th>
                    <th style={th}>Material</th>
                    <th style={th}>Tallas</th>
                    <th style={{...th, textAlign: "right"}}>Precio</th>
                    <th style={{...th, textAlign: "right", width: 120}}></th>
                  </tr>
                </thead>
                <tbody>
                  {visibleProducts.map(p => (
                    <tr key={p.id} style={{ borderTop: "1px solid var(--line-2)" }}>
                      <td style={td}>
                        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                          <div style={{ width: 48, height: 48, flexShrink: 0 }}>
                            <ProductImg p={p}/>
                          </div>
                          <div>
                            <div style={{ fontWeight: 600 }}>{p.name}</div>
                            <div style={{ fontSize: 11, color: "var(--ink-2)", letterSpacing: "0.1em" }}>
                              SKU · {p.id.toUpperCase()}
                              {p.tag && <span style={{ marginLeft: 8, color: "var(--burgundy)" }}>· {p.tag}</span>}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td style={td}>{store.categories.find(c=>c.id===p.category)?.name}</td>
                      <td style={{...td, color: "var(--ink-2)", maxWidth: 220}}>
                        <span style={{ display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.material}</span>
                      </td>
                      <td style={{...td, color: "var(--ink-2)" }}>{p.sizes.join(", ")}</td>
                      <td style={{...td, textAlign: "right", fontWeight: 600 }}>{fmtPrice(p.price)}</td>
                      <td style={{...td, textAlign: "right" }}>
                        <button onClick={()=>setEditingId(p.id)} style={iconBtn} aria-label="Editar"><Icon name="edit" size={16}/></button>
                        <button onClick={()=>deleteProduct(p.id)} style={{...iconBtn, color: "var(--burgundy-soft)"}} aria-label="Eliminar"><Icon name="trash" size={16}/></button>
                      </td>
                    </tr>
                  ))}
                  {visibleProducts.length === 0 && (
                    <tr><td style={{...td, textAlign: "center", color: "var(--ink-2)", padding: 40 }} colSpan="6">
                      Sin resultados. Intenta otra búsqueda.
                    </td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "products" && (editingId || creating) && (
          <ProductEditor
            product={editingId ? store.products.find(p=>p.id===editingId) : null}
            categories={store.categories}
            onSave={saveProduct}
            onCancel={()=>{ setEditingId(null); setCreating(false); }}
          />
        )}

        {tab === "categories" && (
          <CategoryManager store={store} onSave={saveCategory} onDelete={deleteCategory}/>
        )}

        {tab === "content" && (
          <ContentEditor
            content={store.content}
            categories={store.categories}
            refreshStore={refreshStore}
            onResetContent={() => {
              if (!confirm("¿Restaurar todos los textos e imágenes al contenido por defecto? Esto no afecta productos ni categorías.")) return;
              withBusy(async () => {
                await window.kiroDB.saveContent(SEED_CONTENT);
                await refreshStore();
              });
            }}
          />
        )}
      </div>
    </div>
  );
}

const th = { padding: "14px 16px", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--burgundy)", fontWeight: 600 };
const td = { padding: "14px 16px", verticalAlign: "middle" };
const iconBtn = { background: "transparent", border: 0, padding: 8, color: "var(--burgundy)", cursor: "pointer" };

function Stat({ k, v, sub }) {
  return (
    <div style={{ background: "#fff", padding: 24, border: "1px solid var(--line-2)" }}>
      <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
        color: "var(--burgundy)", fontWeight: 600 }}>{k}</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 34, fontWeight: 400,
        color: "var(--ink)", margin: "10px 0 4px" }}>{v}</div>
      <div style={{ fontSize: 12, color: "var(--ink-2)" }}>{sub}</div>
    </div>
  );
}

/* ----- Product editor ----- */
function ProductEditor({ product, categories, onSave, onCancel }) {
  const [form, setForm] = useState(() => product || {
    id: "p" + String(Date.now()).slice(-4),
    name: "",
    price: 0,
    category: categories[0]?.id || "anillos",
    material: "",
    sizes: ["Único"],
    description: "",
    tag: "",
    photos: 4,
    images: [],
  });

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }
  function submit(e) {
    e.preventDefault();
    if (!form.name.trim() || !form.material.trim()) {
      alert("Nombre y material son requeridos.");
      return;
    }
    onSave({ ...form, price: Number(form.price) || 0 });
  }

  return (
    <form onSubmit={submit}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
        <div>
          <a onClick={onCancel} style={{ cursor: "pointer", fontSize: 12,
            letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-2)" }}>
            ← Productos
          </a>
          <h1 style={{ fontFamily: "var(--serif)", fontSize: 40, fontWeight: 400,
            color: "var(--burgundy)", margin: "8px 0 0" }}>
            {product ? "Editar pieza" : "Nueva pieza"}
          </h1>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button type="button" onClick={onCancel} className="btn btn-ghost">Cancelar</button>
          <button type="submit" className="btn">
            <Icon name="check" size={14}/> {product ? "Guardar cambios" : "Crear producto"}
          </button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 24 }}>
        <div style={{ background: "#fff", padding: 32, border: "1px solid var(--line-2)",
          display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="field">
            <label>Nombre de la pieza</label>
            <input value={form.name} onChange={e=>set("name", e.target.value)} placeholder="Anillo Lumen"/>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div className="field">
              <label>Precio (PEN)</label>
              <input type="number" value={form.price} onChange={e=>set("price", e.target.value)} placeholder="290"/>
            </div>
            <div className="field">
              <label>Categoría</label>
              <select value={form.category} onChange={e=>set("category", e.target.value)}>
                {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
          </div>
          <div className="field">
            <label>Material</label>
            <input value={form.material} onChange={e=>set("material", e.target.value)} placeholder="Plata 925 con baño de oro 18k"/>
          </div>
          <div className="field">
            <label>Tallas disponibles (separadas por coma)</label>
            <SizesInput value={form.sizes} onChange={(v) => set("sizes", v)} />
          </div>
          <div className="field">
            <label>Descripción</label>
            <textarea value={form.description} onChange={e=>set("description", e.target.value)} rows="4"/>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div className="field">
              <label>Etiqueta (opcional)</label>
              <select value={form.tag || ""} onChange={e=>set("tag", e.target.value)}>
                <option value="">— Ninguna —</option>
                <option value="Nuevo">Nuevo</option>
                <option value="Bestseller">Bestseller</option>
                <option value="Edición">Edición limitada</option>
                <option value="Agotándose">Agotándose</option>
              </select>
            </div>
            <div className="field">
              <label>SKU</label>
              <input value={form.id} onChange={e=>set("id", e.target.value)} disabled={!!product}/>
            </div>
          </div>
        </div>

        <div style={{ background: "#fff", padding: 24, border: "1px solid var(--line-2)",
          display: "flex", flexDirection: "column", gap: 18 }}>
          <ImageGalleryUploader
            value={form.images || []}
            onChange={(imgs) => set("images", imgs)}
            max={6}
          />

          <div style={{ borderTop: "1px solid var(--line-2)", paddingTop: 14 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
              fontWeight: 600, color: "var(--burgundy)", marginBottom: 12 }}>Vista previa</div>
            <div style={{ aspectRatio: "4/5" }}>
              <ProductImg p={{ id: form.id || "preview", category: form.category, images: form.images }}/>
            </div>
            <div style={{ marginTop: 12 }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--ink)" }}>
                {form.name || "Nombre de la pieza"}
              </div>
              <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{fmtPrice(form.price || 0)}</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-2)", borderTop: "1px solid var(--line-2)", paddingTop: 12, marginTop: 12 }}>
              <div><strong style={{ color: "var(--burgundy)" }}>Material:</strong> {form.material || "—"}</div>
              <div style={{ marginTop: 6 }}><strong style={{ color: "var(--burgundy)" }}>Tallas:</strong> {form.sizes.join(", ") || "—"}</div>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}

/* ----- Category manager ----- */
function CategoryManager({ store, onSave, onDelete }) {
  const [editing, setEditing] = useState(null);
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState({ id: "", name: "", tagline: "", image: "" });

  function startEdit(c) {
    setEditing(c.id);
    setCreating(false);
    setForm({ image: "", ...c });
  }
  function startCreate() {
    setCreating(true);
    setEditing(null);
    setForm({ id: "", name: "", tagline: "", image: "" });
  }
  function submit(e) {
    e.preventDefault();
    if (!form.name.trim()) return;
    const id = form.id || form.name.toLowerCase().replace(/[^a-z]/g,'').slice(0,12);
    onSave({ ...form, id });
    setEditing(null);
    setCreating(false);
  }

  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32 }}>
        <div>
          <h1 style={{ fontFamily: "var(--serif)", fontSize: 44, fontWeight: 400,
            color: "var(--burgundy)", margin: "0 0 8px" }}>Categorías</h1>
          <p style={{ color: "var(--ink-2)", margin: 0 }}>
            Familias de productos que se muestran en home y navegación.
          </p>
        </div>
        <button className="btn" onClick={startCreate}>
          <Icon name="plus" size={14}/> Nueva categoría
        </button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {store.categories.map(c => {
            const count = store.products.filter(p=>p.category===c.id).length;
            return (
              <div key={c.id} style={{
                background: editing === c.id ? "var(--pink-100)" : "#fff",
                padding: 20, border: "1px solid var(--line-2)",
                display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16,
              }}>
                <div style={{ display: "flex", gap: 16, alignItems: "center", flex: 1, minWidth: 0 }}>
                  <div style={{
                    width: 64, height: 80, flexShrink: 0,
                    background: "var(--pink-100)", overflow: "hidden",
                    border: "1px solid var(--line-2)",
                  }}>
                    {c.image ? (
                      <img src={c.image} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
                    ) : (
                      <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center",
                        color: "var(--burgundy-soft)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", textAlign: "center", padding: 4 }}>
                        Sin imagen
                      </div>
                    )}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--burgundy)" }}>{c.name}</div>
                    <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 2 }}>
                      /{c.id} · {count} piezas
                    </div>
                    <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 8, fontStyle: "italic" }}>"{c.tagline}"</div>
                  </div>
                </div>
                <div style={{ display: "flex", gap: 4 }}>
                  <button onClick={()=>startEdit(c)} style={iconBtn} aria-label="Editar"><Icon name="edit" size={16}/></button>
                  <button onClick={()=>onDelete(c.id)} style={{...iconBtn, color: "var(--burgundy-soft)"}} aria-label="Eliminar"><Icon name="trash" size={16}/></button>
                </div>
              </div>
            );
          })}
        </div>

        {(editing || creating) && (
          <form onSubmit={submit} style={{
            background: "#fff", padding: 28, border: "1px solid var(--line-2)",
            alignSelf: "start", position: "sticky", top: 24,
            display: "flex", flexDirection: "column", gap: 16,
          }}>
            <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
              fontWeight: 600, color: "var(--burgundy)" }}>
              {creating ? "Nueva categoría" : "Editar categoría"}
            </div>
            <div className="field">
              <label>Nombre</label>
              <input value={form.name} onChange={e=>setForm(f=>({...f, name: e.target.value}))} placeholder="Anillos"/>
            </div>
            <div className="field">
              <label>Slug (URL)</label>
              <input value={form.id} onChange={e=>setForm(f=>({...f, id: e.target.value}))} placeholder="anillos" disabled={editing}/>
            </div>
            <div className="field">
              <label>Tagline</label>
              <textarea value={form.tagline} onChange={e=>setForm(f=>({...f, tagline: e.target.value}))} rows="2" placeholder="Para todos los días, para los días raros."/>
            </div>
            <ImageUploader
              label="Imagen de portada"
              value={form.image}
              onChange={(v)=>setForm(f=>({...f, image: v}))}
              aspect="3/4"
              prefix="categories"
              help="Se muestra en la sección de categorías del home. Recomendado: foto vertical (al menos 800px de ancho)."
            />
            <div style={{ display: "flex", gap: 8 }}>
              <button type="button" className="btn btn-ghost btn-sm" onClick={()=>{setEditing(null); setCreating(false);}}>Cancelar</button>
              <button type="submit" className="btn btn-sm">Guardar</button>
            </div>
          </form>
        )}
      </div>
    </>
  );
}

/* ============================================================
   Content editor — edits all global site copy + images
   ============================================================ */

/* Small chip used in wireframes to point at an editable region. */
function WireLabel({ children, color = "var(--burgundy)" }) {
  return (
    <span style={{
      display: "inline-block", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase",
      fontWeight: 700, color: "var(--pink-50)", background: color, padding: "2px 6px",
      borderRadius: 2, whiteSpace: "nowrap",
    }}>{children}</span>
  );
}

/* Header for each content section. Shows the section name + a small
   description of where in the site this section appears. */
function ContentSection({ kicker, title, where, wireframe, children, defaultOpen = true }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section style={{ background: "#fff", border: "1px solid var(--line-2)", marginBottom: 20 }}>
      <button type="button" onClick={()=>setOpen(o=>!o)}
        style={{ width: "100%", background: "transparent", border: 0, cursor: "pointer",
          padding: "18px 24px", display: "flex", justifyContent: "space-between", alignItems: "center",
          borderBottom: open ? "1px solid var(--line-2)" : "0" }}>
        <div style={{ textAlign: "left" }}>
          <div style={{ fontSize: 10, letterSpacing: "0.3em", textTransform: "uppercase",
            color: "var(--burgundy-soft)", fontWeight: 600 }}>{kicker}</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 24, color: "var(--burgundy)", marginTop: 4 }}>
            {title}
          </div>
          {where && (
            <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4 }}>
              <strong style={{ color: "var(--burgundy)" }}>Dónde aparece:</strong> {where}
            </div>
          )}
        </div>
        <Icon name={open ? "chevD" : "chevR"} size={18}/>
      </button>
      {open && (
        <div style={{ padding: 24, display: "grid", gridTemplateColumns: "minmax(0, 360px) 1fr", gap: 32, alignItems: "start" }}>
          <div style={{ position: "sticky", top: 24 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
              color: "var(--burgundy)", fontWeight: 600, marginBottom: 10 }}>
              ↓ Así se ve en la página
            </div>
            {wireframe}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {children}
          </div>
        </div>
      )}
    </section>
  );
}

/* Small labeled form field for the content editor. */
function ContentField({ label, value, onChange, onBlur, type = "text", rows, placeholder, help }) {
  const common = {
    value: value ?? "",
    onChange: (e) => onChange(e.target.value),
    onBlur,
    placeholder,
    style: {
      background: "var(--cream)", border: "1px solid var(--line)",
      padding: "10px 12px", fontFamily: "var(--sans)", fontSize: 14,
      color: "var(--ink)", outline: "none", width: "100%",
    },
  };
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
        color: "var(--burgundy)", fontWeight: 600 }}>{label}</span>
      {type === "textarea"
        ? <textarea rows={rows || 3} {...common} style={{...common.style, fontFamily: "var(--sans)", resize: "vertical"}}/>
        : <input type={type} {...common}/>}
      {help && <span style={{ fontSize: 11, color: "var(--ink-2)" }}>{help}</span>}
    </label>
  );
}

/* Edit a string[] as a textarea, one item per line.
 * Uses a local text buffer so trailing newlines aren't eaten while typing
 * (same pattern as SizesInput above). */
function LinesField({ label, items, onChange, help }) {
  const [text, setText] = useState(() => (items || []).join("\n"));
  const joined = (items || []).join("|");
  useEffect(() => { setText((items || []).join("\n")); }, [joined]);
  return (
    <ContentField
      label={label}
      type="textarea"
      rows={Math.max(3, text.split("\n").length + 1)}
      value={text}
      onChange={(v) => {
        setText(v);
        onChange(v.split("\n").map(x => x.trim()).filter(Boolean));
      }}
      onBlur={() => setText((items || []).join("\n"))}
      help={help || "Un elemento por línea."}
    />
  );
}

const ICON_OPTIONS = ["leaf", "truck", "shield", "box", "heart", "star", "tag", "chart"];

function IconPickerField({ label, value, onChange }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
        color: "var(--burgundy)", fontWeight: 600 }}>{label}</span>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        {ICON_OPTIONS.map(name => (
          <button key={name} type="button" onClick={()=>onChange(name)}
            title={name}
            style={{
              width: 42, height: 42,
              background: value === name ? "var(--burgundy)" : "var(--cream)",
              color: value === name ? "var(--pink-50)" : "var(--burgundy)",
              border: "1px solid " + (value === name ? "var(--burgundy)" : "var(--line)"),
              cursor: "pointer",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
            <Icon name={name} size={18}/>
          </button>
        ))}
      </div>
    </label>
  );
}

/* ---------- Reusable: drag-to-pick focal point for hero image on mobile ---------- */
function HeroFocalPicker({ image, value, onChange }) {
  const parse = (v) => {
    if (!v) return { x: 100, y: 50 };
    const kx = { left: 0, center: 50, right: 100 };
    const ky = { top: 0, center: 50, bottom: 100 };
    const parts = String(v).trim().split(/\s+/);
    if (parts.length === 2) {
      const px = parts[0].endsWith("%") ? parseFloat(parts[0]) : kx[parts[0]];
      const py = parts[1].endsWith("%") ? parseFloat(parts[1]) : ky[parts[1]];
      if (!isNaN(px) && !isNaN(py)) return { x: px, y: py };
    }
    return { x: 100, y: 50 };
  };

  const ref = useRef(null);
  const [pos, setPos] = useState(() => parse(value));
  const [dragging, setDragging] = useState(false);

  // Re-sync if parent value changes (e.g. reset)
  useEffect(() => { setPos(parse(value)); }, [value]);

  const moveTo = (clientX, clientY) => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
    const y = Math.max(0, Math.min(100, ((clientY - rect.top) / rect.height) * 100));
    const nx = Math.round(x);
    const ny = Math.round(y);
    setPos({ x: nx, y: ny });
    onChange(`${nx}% ${ny}%`);
  };

  if (!image) {
    return (
      <div className="field">
        <label>Punto focal en móvil</label>
        <div style={{
          background: "var(--cream)", padding: "16px 18px", fontSize: 12,
          color: "var(--ink-2)", border: "1px dashed var(--line-2)",
        }}>
          Sube primero una imagen del hero para poder elegir su punto focal.
        </div>
      </div>
    );
  }

  return (
    <div className="field">
      <label>Punto focal en móvil — arrastra el círculo donde quieras</label>
      <div
        ref={ref}
        onMouseDown={(e) => { e.preventDefault(); setDragging(true); moveTo(e.clientX, e.clientY); }}
        onMouseMove={(e) => { if (dragging) moveTo(e.clientX, e.clientY); }}
        onMouseUp={() => setDragging(false)}
        onMouseLeave={() => setDragging(false)}
        onTouchStart={(e) => {
          setDragging(true);
          const t = e.touches[0];
          if (t) moveTo(t.clientX, t.clientY);
        }}
        onTouchMove={(e) => {
          const t = e.touches[0];
          if (t) moveTo(t.clientX, t.clientY);
        }}
        onTouchEnd={() => setDragging(false)}
        style={{
          position: "relative",
          aspectRatio: "16/7",
          background: "var(--cream)",
          border: "1px solid var(--line-2)",
          cursor: dragging ? "grabbing" : "crosshair",
          userSelect: "none",
          touchAction: "none",
          overflow: "hidden",
        }}
      >
        <img src={image} alt=""
          draggable={false}
          style={{
            width: "100%", height: "100%", objectFit: "cover",
            display: "block", pointerEvents: "none",
            opacity: 0.92,
          }}/>
        <div style={{
          position: "absolute",
          left: `${pos.x}%`, top: `${pos.y}%`,
          transform: "translate(-50%, -50%)",
          width: 32, height: 32,
          borderRadius: "50%",
          border: "3px solid #fff",
          background: "rgba(107,31,37,0.85)",
          boxShadow: "0 2px 10px rgba(0,0,0,0.45)",
          pointerEvents: "none",
        }}>
          <div style={{ position: "absolute", inset: 8, borderRadius: "50%", background: "#fff" }}/>
        </div>
      </div>

      <div style={{ display: "flex", gap: 18, marginTop: 12, alignItems: "flex-start" }}>
        <div>
          <div style={{ fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase",
            color: "var(--burgundy)", marginBottom: 6, fontWeight: 600 }}>
            Vista previa móvil
          </div>
          <div style={{
            width: 110, aspectRatio: "9/16", borderRadius: 14,
            border: "2px solid var(--burgundy)", overflow: "hidden",
            background: "var(--cream)",
          }}>
            <img src={image} alt=""
              draggable={false}
              style={{
                width: "100%", height: "100%", objectFit: "cover",
                objectPosition: `${pos.x}% ${pos.y}%`,
                display: "block",
              }}/>
          </div>
        </div>

        <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.7, flex: 1 }}>
          <div style={{ fontFamily: "var(--mono)", marginBottom: 8 }}>
            X: {pos.x}% &nbsp;·&nbsp; Y: {pos.y}%
          </div>
          <div>Arrastra el círculo sobre la imagen para elegir qué parte de la foto debe quedar siempre visible en móvil. El desktop sigue centrado.</div>
          <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
            <button type="button"
              onClick={() => onChange("50% 50%")}
              style={{ background: "transparent", border: "1px solid var(--line-2)",
                padding: "5px 10px", fontSize: 10.5, letterSpacing: "0.12em",
                textTransform: "uppercase", cursor: "pointer", color: "var(--burgundy)" }}>
              Centrar
            </button>
            <button type="button"
              onClick={() => onChange("100% 50%")}
              style={{ background: "transparent", border: "1px solid var(--line-2)",
                padding: "5px 10px", fontSize: 10.5, letterSpacing: "0.12em",
                textTransform: "uppercase", cursor: "pointer", color: "var(--burgundy)" }}>
              Derecha
            </button>
            <button type="button"
              onClick={() => onChange("0% 50%")}
              style={{ background: "transparent", border: "1px solid var(--line-2)",
                padding: "5px 10px", fontSize: 10.5, letterSpacing: "0.12em",
                textTransform: "uppercase", cursor: "pointer", color: "var(--burgundy)" }}>
              Izquierda
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ContentEditor({ content, categories, refreshStore, onResetContent }) {
  const [local, setLocal] = useState(content);
  const [saveStatus, setSaveStatus] = useState("idle"); // idle | saving | saved | error
  const timerRef = useRef(null);
  const pendingRef = useRef(null);

  // When external content changes (e.g. after refreshStore from reset), sync local.
  useEffect(() => { setLocal(content); }, [content]);

  const flush = useCallback(async (next) => {
    setSaveStatus("saving");
    try {
      await window.kiroDB.saveContent(next);
      setSaveStatus("saved");
    } catch (err) {
      console.error(err);
      setSaveStatus("error");
    }
  }, []);

  // On unmount, flush any pending change so it isn't lost.
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        if (pendingRef.current) flush(pendingRef.current);
      }
    };
  }, [flush]);

  const update = useCallback((updater) => {
    setLocal(prev => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      pendingRef.current = next;
      clearTimeout(timerRef.current);
      setSaveStatus("saving");
      timerRef.current = setTimeout(() => flush(next), 700);
      return next;
    });
  }, [flush]);

  const updateHero      = (k, v) => update(c => ({ ...c, hero: { ...c.hero, [k]: v } }));
  const updateFooter    = (k, v) => update(c => ({ ...c, footer: { ...c.footer, [k]: v } }));
  const updateSocial    = (k, v) => update(c => ({ ...c, social: { ...(c.social || {}), [k]: v } }));
  const updateEditorial = (k, v) => update(c => ({
    ...c, editorial: { ...(c.editorial || {}), [k]: v }
  }));
  const updateValue  = (i, k, v) => update(c => {
    const values = c.values.map((it, idx) => idx === i ? { ...it, [k]: v } : it);
    return { ...c, values };
  });
  const setContent = update; // alias so existing handlers keep working

  // Re-bind `content` to the local state for the rest of this component
  content = local;

  const statusLabel = {
    idle:   "",
    saving: "Guardando…",
    saved:  "Guardado",
    error:  "Error al guardar",
  }[saveStatus];
  const statusColor = saveStatus === "error" ? "var(--burgundy)" : "var(--ink-2)";

  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32 }}>
        <div>
          <h1 style={{ fontFamily: "var(--serif)", fontSize: 44, fontWeight: 400,
            color: "var(--burgundy)", margin: "0 0 8px" }}>Contenido del sitio</h1>
          <p style={{ color: "var(--ink-2)", margin: 0, maxWidth: 640 }}>
            Edita todos los textos e imágenes globales. Los cambios se guardan automáticamente en la base de datos.
          </p>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <span style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase",
            fontWeight: 600, color: statusColor, display: "inline-flex", gap: 8, alignItems: "center" }}>
            {saveStatus === "saving" && <span className="spinner"/>}
            {statusLabel}
          </span>
          <button className="btn btn-ghost" onClick={onResetContent}>Restaurar contenido</button>
        </div>
      </div>

      {/* ───── Banda promocional ───── */}
      <ContentSection
        kicker="01 · Banda promocional"
        title="Mensaje de la cinta superior"
        where="Aparece arriba del todo, sobre el logo, en color burdeos."
        wireframe={
          <div>
            <div style={{ background: "var(--burgundy)", color: "var(--pink-50)",
              padding: "8px 10px", fontSize: 10, letterSpacing: "0.18em",
              textTransform: "uppercase", textAlign: "center", position: "relative" }}>
              {content.utilityBar || "—"}
              <div style={{ position: "absolute", right: 4, top: -10 }}>
                <WireLabel>1</WireLabel>
              </div>
            </div>
            <div style={{ background: "var(--bg)", padding: 12, border: "1px solid var(--line-2)",
              borderTop: 0, fontSize: 11, color: "var(--ink-2)", textAlign: "center", letterSpacing: "0.1em" }}>
              KIRO JEWELRY · Header
            </div>
          </div>
        }
      >
        <ContentField
          label="① Texto de la banda"
          value={content.utilityBar}
          onChange={(v) => setContent(c => ({ ...c, utilityBar: v }))}
          help="Separa ideas con el carácter · (Opt+8 en Mac)."
        />
      </ContentSection>

      {/* ───── Header (barra superior) ───── */}
      <ContentSection
        kicker="02 · Header"
        title="Barra superior · enlaces de redes"
        where="El header muestra el logo KIRO al centro, las categorías a la izquierda y los íconos de redes sociales a la derecha. Aquí editas los enlaces de las redes — los mismos íconos aparecen también en el footer."
        wireframe={
          <div style={{ background: "var(--header-bg)", padding: 12, border: "1px solid var(--line-2)" }}>
            <div style={{ background: "var(--burgundy)", color: "var(--pink-50)",
              padding: "5px 8px", fontSize: 8, letterSpacing: "0.18em",
              textTransform: "uppercase", textAlign: "center", marginBottom: 8 }}>
              {(content.utilityBar || "—").slice(0, 60)}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", gap: 12 }}>
              <div style={{ fontSize: 9, color: "var(--burgundy)", letterSpacing: "0.18em" }}>
                {(categories || []).slice(0, 3).map(c => c.name.toUpperCase()).join(" · ") || "Categorías"}
              </div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--burgundy)", letterSpacing: "0.16em" }}>
                KIRO
              </div>
              <div style={{ display: "flex", gap: 10, color: "var(--burgundy)", justifyContent: "flex-end", alignItems: "center", position: "relative" }}>
                <div style={{ position: "absolute", left: -22, top: -10 }}><WireLabel>·</WireLabel></div>
                {content.social?.instagram && <span style={{ fontSize: 11 }}>IG</span>}
                {content.social?.tiktok && <span style={{ fontSize: 11 }}>TT</span>}
                {content.social?.whatsapp && <span style={{ fontSize: 11 }}>WA</span>}
                {!content.social?.instagram && !content.social?.tiktok && !content.social?.whatsapp && (
                  <span style={{ fontSize: 10, color: "var(--ink-2)", fontStyle: "italic" }}>sin redes</span>
                )}
              </div>
            </div>
          </div>
        }
      >
        <div style={{ fontSize: 12.5, lineHeight: 1.6, color: "var(--ink-2)",
          padding: "10px 14px", background: "rgba(107,31,37,0.05)",
          border: "1px dashed var(--line-2)", marginBottom: 4 }}>
          Estos enlaces se usan en <strong>dos lugares</strong>: los íconos a la derecha de la barra superior y la columna 3 del footer. Si dejas un campo vacío, ese ícono no se muestra.
        </div>
        <ContentField label="① Instagram (URL completa)"
          value={content.social?.instagram || ""} onChange={(v)=>updateSocial("instagram", v)}
          placeholder="https://instagram.com/kirojewelry"
          help="Pega el enlace completo a tu perfil. Déjalo vacío si no tienes Instagram."/>
        <ContentField label="② TikTok (URL completa)"
          value={content.social?.tiktok || ""} onChange={(v)=>updateSocial("tiktok", v)}
          placeholder="https://tiktok.com/@kirojewelry"
          help="Pega el enlace completo a tu perfil. Déjalo vacío si no tienes TikTok."/>
        <ContentField label="③ WhatsApp (enlace wa.me)"
          value={content.social?.whatsapp || ""} onChange={(v)=>updateSocial("whatsapp", v)}
          placeholder="https://wa.me/51954796222"
          help="Formato: https://wa.me/ seguido del número con código de país (sin + ni espacios)."/>
      </ContentSection>

      {/* ───── Hero ───── */}
      <ContentSection
        kicker="03 · Hero del Home"
        title="Pantalla principal de inicio"
        where="Es lo primero que se ve al entrar a la tienda."
        wireframe={
          <div style={{ background: "var(--pink-50)", color: "var(--burgundy-deep)",
            padding: 16, position: "relative", minHeight: 280, overflow: "hidden" }}>
            {content.hero.image && (
              <img src={content.hero.image} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.4 }}/>
            )}
            <div style={{ position: "relative" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <WireLabel>1</WireLabel>
                <span style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--burgundy)" }}>
                  {content.hero.eyebrow}
                </span>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 6, marginTop: 10 }}>
                <WireLabel>2</WireLabel>
                <div style={{ fontFamily: "var(--serif)", fontSize: 22, lineHeight: 1, color: "var(--burgundy-deep)" }}>
                  {content.hero.titleLine1}<br/>
                  <span style={{ fontStyle: "italic" }}>{content.hero.titleLine2}</span>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 6, marginTop: 12 }}>
                <WireLabel>3</WireLabel>
                <p style={{ fontSize: 10, color: "var(--ink-2)", margin: 0, lineHeight: 1.5, maxWidth: 200 }}>
                  {content.hero.body}
                </p>
              </div>
              <div style={{ display: "flex", gap: 4, marginTop: 12 }}>
                <div style={{ background: "var(--burgundy)", color: "var(--pink-50)", padding: "4px 8px", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase" }}>
                  <WireLabel color="var(--burgundy-deep)">4</WireLabel> {content.hero.cta1}
                </div>
                <div style={{ border: "1px solid var(--burgundy)", color: "var(--burgundy)", padding: "4px 8px", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase" }}>
                  <WireLabel color="var(--burgundy-deep)">5</WireLabel> {content.hero.cta2}
                </div>
              </div>
            </div>
            <div style={{ position: "absolute", bottom: 8, left: 16, right: 16, display: "flex", justifyContent: "space-between",
              fontSize: 8, color: "var(--burgundy)", letterSpacing: "0.16em", textTransform: "uppercase" }}>
              <span><WireLabel color="var(--burgundy-deep)">7</WireLabel> {content.hero.cornerMeta}</span>
              <span><WireLabel color="var(--burgundy-deep)">8</WireLabel> {content.hero.cornerCredit}</span>
            </div>
            <div style={{ position: "absolute", top: 8, right: 8 }}>
              <WireLabel>6 imagen de fondo</WireLabel>
            </div>
          </div>
        }
      >
        <ContentField label="① Eyebrow (texto pequeño arriba del título)"
          value={content.hero.eyebrow} onChange={(v)=>updateHero("eyebrow", v)} />
        <ContentField label="② Título — primera línea"
          value={content.hero.titleLine1} onChange={(v)=>updateHero("titleLine1", v)} />
        <ContentField label="② Título — segunda línea (en cursiva)"
          value={content.hero.titleLine2} onChange={(v)=>updateHero("titleLine2", v)} />
        <ContentField label="③ Párrafo descriptivo"
          type="textarea" rows={3}
          value={content.hero.body} onChange={(v)=>updateHero("body", v)} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <ContentField label="④ Texto botón principal"
            value={content.hero.cta1} onChange={(v)=>updateHero("cta1", v)} />
          <ContentField label="⑤ Texto botón secundario"
            value={content.hero.cta2} onChange={(v)=>updateHero("cta2", v)} />
        </div>
        <ImageUploader
          label="⑥ Imagen de fondo (opcional)"
          value={content.hero.image}
          onChange={(v) => updateHero("image", v)}
          aspect="16/7"
          prefix="hero"
          help="Recomendado: foto horizontal grande (al menos 1600px de ancho). Sin imagen, se muestra la ilustración decorativa por defecto."
        />
        <HeroFocalPicker
          image={content.hero.image}
          value={content.hero.imagePositionMobile}
          onChange={(v) => updateHero("imagePositionMobile", v)}
        />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <ContentField label="⑦ Texto esquina inferior izquierda"
            value={content.hero.cornerMeta} onChange={(v)=>updateHero("cornerMeta", v)} />
          <ContentField label="⑧ Texto esquina inferior derecha"
            value={content.hero.cornerCredit} onChange={(v)=>updateHero("cornerCredit", v)} />
        </div>
      </ContentSection>

      {/* ───── Valores ───── */}
      <ContentSection
        kicker="04 · Banner de valores"
        title="Materiales / Envíos / Garantía / Empaque"
        where="Banda burdeos al medio del Home, justo abajo de los productos destacados."
        wireframe={
          <div style={{ background: "var(--burgundy)", color: "var(--pink-50)",
            padding: 16, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
            {content.values.map((v, i) => (
              <div key={i} style={{ position: "relative" }}>
                <div style={{ position: "absolute", top: -8, left: -8 }}>
                  <WireLabel color="var(--burgundy-deep)">{i+1}</WireLabel>
                </div>
                <div style={{ color: "var(--pink-100)", marginBottom: 4 }}>
                  <Icon name={v.icon} size={16}/>
                </div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 12, lineHeight: 1.1 }}>{v.title}</div>
                <div style={{ fontSize: 8.5, color: "var(--pink-200)", lineHeight: 1.3, marginTop: 4 }}>
                  {(v.body || "").slice(0, 50)}{v.body && v.body.length > 50 ? "…" : ""}
                </div>
              </div>
            ))}
          </div>
        }
      >
        {content.values.map((v, i) => (
          <div key={i} style={{
            background: "var(--cream)", border: "1px solid var(--line-2)",
            padding: 16, display: "flex", flexDirection: "column", gap: 12,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <WireLabel>{i+1}</WireLabel>
              <span style={{ fontFamily: "var(--serif)", fontSize: 18, color: "var(--burgundy)" }}>
                Bloque {i+1}
              </span>
            </div>
            <IconPickerField label="Icono" value={v.icon} onChange={(name)=>updateValue(i, "icon", name)}/>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
              <ContentField label="Título"
                value={v.title} onChange={(val)=>updateValue(i, "title", val)} />
              <ContentField label="Descripción" type="textarea" rows={2}
                value={v.body} onChange={(val)=>updateValue(i, "body", val)} />
            </div>
          </div>
        ))}
      </ContentSection>

      {/* ───── Editorial band ───── */}
      <ContentSection
        kicker="05 · Sección editorial"
        title="El taller — bloque editorial"
        where="Banda con foto a la izquierda y texto a la derecha, justo arriba del footer."
        wireframe={
          <div style={{ background: "var(--cream)", padding: 14, display: "grid",
            gridTemplateColumns: "1fr 1fr", gap: 12, alignItems: "center" }}>
            <div style={{ aspectRatio: "4/5", background: "var(--pink-100)",
              border: "1px solid var(--line-2)", position: "relative", overflow: "hidden" }}>
              {content.editorial?.image ? (
                <img src={content.editorial.image} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}/>
              ) : (
                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
                  color: "var(--burgundy-soft)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase" }}>
                  <WireLabel color="var(--burgundy-deep)">5</WireLabel>
                </div>
              )}
            </div>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <WireLabel>1</WireLabel>
                <span style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--burgundy-soft)" }}>
                  {content.editorial?.eyebrow}
                </span>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 6, marginTop: 8 }}>
                <WireLabel>2</WireLabel>
                <div style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.1, color: "var(--burgundy)" }}>
                  {content.editorial?.titleStart} <em>{content.editorial?.titleItalic}</em> {content.editorial?.titleEnd}
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 6, marginTop: 10 }}>
                <WireLabel>3</WireLabel>
                <p style={{ fontSize: 9, color: "var(--ink-2)", margin: 0, lineHeight: 1.5 }}>
                  {(content.editorial?.body || "").slice(0, 90)}…
                </p>
              </div>
              <div style={{ display: "inline-flex", marginTop: 10,
                border: "1px solid var(--burgundy)", padding: "4px 8px",
                fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--burgundy)" }}>
                <WireLabel color="var(--burgundy-deep)">4</WireLabel> {content.editorial?.cta}
              </div>
            </div>
          </div>
        }
      >
        <ContentField label="① Eyebrow (texto pequeño arriba del título)"
          value={content.editorial?.eyebrow || ""} onChange={(v)=>updateEditorial("eyebrow", v)} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <ContentField label="② Título — parte 1"
            value={content.editorial?.titleStart || ""} onChange={(v)=>updateEditorial("titleStart", v)} />
          <ContentField label="② Título — cursiva (énfasis)"
            value={content.editorial?.titleItalic || ""} onChange={(v)=>updateEditorial("titleItalic", v)} />
          <ContentField label="② Título — parte 3"
            value={content.editorial?.titleEnd || ""} onChange={(v)=>updateEditorial("titleEnd", v)} />
        </div>
        <ContentField label="③ Párrafo descriptivo"
          type="textarea" rows={4}
          value={content.editorial?.body || ""} onChange={(v)=>updateEditorial("body", v)} />
        <ContentField label="④ Texto del botón (vacío para ocultarlo)"
          value={content.editorial?.cta || ""} onChange={(v)=>updateEditorial("cta", v)} />
        <ImageUploader
          label="⑤ Imagen del bloque"
          value={content.editorial?.image}
          onChange={(v)=>updateEditorial("image", v)}
          aspect="4/5"
          prefix="editorial"
          help="Recomendado: foto vertical de tu taller / artesanos (al menos 800px de ancho). Sin imagen, se muestra la ilustración decorativa por defecto."
        />
      </ContentSection>

      {/* ───── Footer ───── */}
      <ContentSection
        kicker="06 · Footer"
        title="Pie de página"
        where="Aparece al final de cualquier página (excepto Admin)."
        wireframe={
          <div style={{ background: "var(--burgundy)", color: "var(--pink-50)", padding: 16 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr 1fr 1fr", gap: 10,
              paddingBottom: 12, borderBottom: "1px solid rgba(252,234,231,0.2)" }}>
              <div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 14, letterSpacing: "0.18em" }}>KIRO</div>
                <div style={{ position: "relative", marginTop: 8 }}>
                  <div style={{ position: "absolute", left: -8, top: -10 }}><WireLabel color="var(--burgundy-deep)">1</WireLabel></div>
                  <div style={{ fontSize: 9, color: "var(--pink-200)", lineHeight: 1.4 }}>
                    {(content.footer.tagline || "").slice(0, 70)}{content.footer.tagline && content.footer.tagline.length > 70 ? "…" : ""}
                  </div>
                </div>
              </div>
              <div style={{ position: "relative" }}>
                <div style={{ position: "absolute", left: -8, top: -10 }}><WireLabel color="var(--burgundy-deep)">2</WireLabel></div>
                <div style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: 4 }}>{content.footer.col1Title}</div>
                {(categories || []).slice(0, 4).map((c, j) => (
                  <div key={j} style={{ fontSize: 9, color: "var(--pink-200)" }}>{c.name}</div>
                ))}
              </div>
              <div style={{ position: "relative" }}>
                <div style={{ position: "absolute", left: -8, top: -10 }}><WireLabel color="var(--burgundy-deep)">3</WireLabel></div>
                <div style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: 4 }}>{content.footer.col2Title}</div>
                <div style={{ fontSize: 9, color: "var(--pink-200)", lineHeight: 1.4 }}>
                  {(content.footer.col2Body || "").slice(0, 80)}{content.footer.col2Body && content.footer.col2Body.length > 80 ? "…" : ""}
                </div>
              </div>
              <div style={{ position: "relative" }}>
                <div style={{ position: "absolute", left: -8, top: -10 }}><WireLabel color="var(--burgundy-deep)">4</WireLabel></div>
                <div style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", marginBottom: 6 }}>{content.footer.col3Title}</div>
                <div style={{ display: "flex", gap: 6, fontSize: 9, color: "var(--pink-200)" }}>
                  {content.social?.instagram && <span>IG</span>}
                  {content.social?.tiktok && <span>TT</span>}
                  {content.social?.whatsapp && <span>WA</span>}
                </div>
              </div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10,
              fontSize: 9, color: "var(--pink-200)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
              <span><WireLabel color="var(--burgundy-deep)">5</WireLabel> {content.footer.copyrightLeft}</span>
              <span><WireLabel color="var(--burgundy-deep)">6</WireLabel> {content.footer.copyrightRight}</span>
            </div>
          </div>
        }
      >
        <ContentField label="① Tagline (descripción de la marca)"
          type="textarea" rows={3}
          value={content.footer.tagline} onChange={(v)=>updateFooter("tagline", v)} />

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: 14,
            background: "var(--cream)", border: "1px solid var(--line-2)" }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <WireLabel>2</WireLabel>
              <span style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--burgundy)" }}>Columna 1 · Tienda</span>
            </div>
            <ContentField label="Título" value={content.footer.col1Title} onChange={(v)=>updateFooter("col1Title", v)}/>
            <div style={{ fontSize: 12, lineHeight: 1.5, color: "var(--ink-2)",
              padding: "10px 12px", background: "rgba(107,31,37,0.05)",
              border: "1px dashed var(--line-2)" }}>
              Los enlaces de esta columna se generan automáticamente con tus categorías. Edítalas en la pestaña <strong>Categorías</strong>.
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: 14,
            background: "var(--cream)", border: "1px solid var(--line-2)" }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <WireLabel>3</WireLabel>
              <span style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--burgundy)" }}>Columna 2 · Cuidado</span>
            </div>
            <ContentField label="Título" value={content.footer.col2Title} onChange={(v)=>updateFooter("col2Title", v)}/>
            <ContentField label="Texto"
              type="textarea" rows={6}
              value={content.footer.col2Body || ""} onChange={(v)=>updateFooter("col2Body", v)}
              help="Párrafo libre. Útil para mencionar el mantenimiento gratuito u otros servicios."/>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: 14,
            background: "var(--cream)", border: "1px solid var(--line-2)" }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <WireLabel>4</WireLabel>
              <span style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--burgundy)" }}>Columna 3 · Redes</span>
            </div>
            <ContentField label="Título" value={content.footer.col3Title} onChange={(v)=>updateFooter("col3Title", v)}
              help="Sugerencia: 'Síguenos' o 'Redes'."/>
            <div style={{ fontSize: 12, lineHeight: 1.5, color: "var(--ink-2)",
              padding: "10px 12px", background: "rgba(107,31,37,0.05)",
              border: "1px dashed var(--line-2)" }}>
              Esta columna muestra los iconos de Instagram, TikTok y WhatsApp. Configura sus enlaces en la sección <strong>02 · Header</strong>.
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <ContentField label="⑤ Copyright izquierdo"
            value={content.footer.copyrightLeft} onChange={(v)=>updateFooter("copyrightLeft", v)} />
          <ContentField label="⑥ Copyright derecho"
            value={content.footer.copyrightRight} onChange={(v)=>updateFooter("copyrightRight", v)} />
        </div>
      </ContentSection>

      {/* ───── Guía de tallas (modal) ───── */}
      <ContentSection
        kicker="07 · Guía de tallas"
        title="Popup de guía de tallas"
        where="Se abre desde el botón del footer y desde el enlace 'Tabla de tallas' en cada producto."
        wireframe={
          <div style={{ background: "var(--cream)", padding: 16, border: "1px solid var(--line-2)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
              <div>
                <div style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase",
                  color: "var(--burgundy-soft)", marginBottom: 6 }}>KIRO · Guía</div>
                <div style={{ position: "relative", paddingLeft: 4 }}>
                  <div style={{ position: "absolute", left: -16, top: -4 }}><WireLabel>2</WireLabel></div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 18, color: "var(--burgundy)" }}>
                    {content.footer.sizingButtonLabel || "Guía de tallas de anillos"}
                  </div>
                </div>
              </div>
              <div style={{ fontSize: 18, color: "var(--burgundy)" }}>×</div>
            </div>
            <div style={{ position: "relative", paddingLeft: 4 }}>
              <div style={{ position: "absolute", left: -16, top: -4 }}><WireLabel>3</WireLabel></div>
              <div style={{ fontSize: 10.5, color: "var(--ink-2)", lineHeight: 1.5,
                whiteSpace: "pre-wrap", maxHeight: 90, overflow: "hidden" }}>
                {(content.footer.sizingContent || "").slice(0, 260)}
                {content.footer.sizingContent && content.footer.sizingContent.length > 260 ? "…" : ""}
              </div>
            </div>
            <div style={{ marginTop: 12, paddingTop: 10, borderTop: "1px dashed var(--line-2)",
              fontSize: 10, color: "var(--ink-2)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
              <WireLabel color="var(--burgundy-deep)">1</WireLabel> Botón en el footer · {content.footer.sizingTitle || "—"}
            </div>
          </div>
        }
      >
        <ContentField label="① Título del bloque CTA en el footer"
          value={content.footer.sizingTitle || ""} onChange={(v)=>updateFooter("sizingTitle", v)}
          help="Aparece en la cajita del footer, encima del botón."/>
        <ContentField label="② Texto del botón / título del popup"
          value={content.footer.sizingButtonLabel || ""} onChange={(v)=>updateFooter("sizingButtonLabel", v)}
          help="Se usa tanto en el botón del footer como en el título del popup."/>

        <div style={{ fontSize: 12.5, lineHeight: 1.6, color: "var(--ink-2)",
          padding: "10px 14px", background: "rgba(107,31,37,0.05)",
          border: "1px dashed var(--line-2)" }}>
          Puedes mostrar la guía como <strong>imagen</strong> (③) o como <strong>texto</strong> (④). Si subes una imagen, se muestra esa y se ignora el texto. Para volver al texto, elimina la imagen.
        </div>

        <ImageUploader
          label="③ Imagen de la guía (opcional)"
          value={content.footer.sizingImage}
          onChange={(v)=>updateFooter("sizingImage", v)}
          aspect="4/3"
          prefix="sizing"
          help="Recomendado: imagen con tabla de tallas, métodos de medición, etc. Si la subes, reemplaza al texto del popup. Formato PNG o JPG. Si la dejas vacía, se muestra el texto de abajo."
        />

        <ContentField label="④ Contenido completo del popup (texto)"
          type="textarea" rows={16}
          value={content.footer.sizingContent || ""} onChange={(v)=>updateFooter("sizingContent", v)}
          help="Solo se usa si NO subiste una imagen en ③. Los saltos de línea se respetan."/>
      </ContentSection>

    </>
  );
}

window.AdminPage = AdminPage;
