// admin.jsx — acceso a la muestra + panel de administración para la clienta.
// La administradora prende/apaga modelos, diseños, accesorios y ofertas, y edita precios.
// Todo se guarda en localStorage (muestra, sin backend). Al guardar, recarga y los cambios se ven.
// ----------------------------------------------------------------
// CLAVES — cámbialas aquí cuando quieras (texto entre comillas):
const CC_ACCESS_PASS = "coolcase2026";   // clave para ver la muestra
const CC_ADMIN_PASS  = "carcasas2026";   // clave del panel de administradora
// ----------------------------------------------------------------

// ===== Pantalla de clave reutilizable =====
function CCKeyScreen({ title, sub, cta, accent, onOk, pass }) {
  const [val, setVal] = React.useState("");
  const [err, setErr] = React.useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (val.trim() === pass) onOk();
    else { setErr(true); setVal(""); }
  };
  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", padding: 24 }}>
      <form onSubmit={submit} className="glass-strong rise" style={{
        width: "min(420px, 92vw)", padding: "40px 32px", borderRadius: 28, textAlign: "center"
      }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>COOLCASE</div>
        <h1 className="display" style={{ fontSize: 30, marginBottom: 8 }}>{title}</h1>
        <p className="muted" style={{ fontSize: 14, lineHeight: 1.5, marginBottom: 24 }}>{sub}</p>
        <input
          type="password" autoFocus value={val}
          onChange={(e) => { setVal(e.target.value); setErr(false); }}
          placeholder="Clave"
          style={{
            width: "100%", padding: "14px 16px", borderRadius: 14, fontSize: 16,
            background: "rgba(255,255,255,0.06)", color: "var(--ink)",
            border: "1px solid " + (err ? "#ff5470" : "var(--glass-border)"),
            outline: "none", marginBottom: 14, textAlign: "center", letterSpacing: "0.1em"
          }}
        />
        {err && <div style={{ color: "#ff5470", fontSize: 13, marginBottom: 14 }}>Clave incorrecta</div>}
        <button type="submit" className="btn btn-neon" style={{
          width: "100%", justifyContent: "center", padding: "14px 24px",
          background: accent || "var(--grad-neon)"
        }}>{cta}</button>
      </form>
    </div>
  );
}

// ===== Puerta de acceso a la muestra (envuelve toda la app) =====
function AccessGate({ children }) {
  const [ok, setOk] = React.useState(() => sessionStorage.getItem("cc_access_ok") === "1");
  if (ok) return children;
  return (
    <CCKeyScreen
      title="Muestra privada"
      sub="Esta es una vista previa de COOLCASE preparada para tu revisión. Ingresa la clave que te compartimos."
      cta="Entrar a la muestra"
      pass={CC_ACCESS_PASS}
      onOk={() => { sessionStorage.setItem("cc_access_ok", "1"); setOk(true); }}
    />
  );
}

// ===== Fila genérica activo/oculto + precio =====
function CCRow({ thumb, title, meta, isOff, onToggle, price, onPrice }) {
  return (
    <div className="glass" style={{
      display: "flex", alignItems: "center", gap: 14, padding: "12px 14px",
      borderRadius: 16, opacity: isOff ? 0.5 : 1, transition: "opacity .2s"
    }}>
      {thumb !== undefined && (
        <div style={{
          width: 44, height: 44, borderRadius: 11, flexShrink: 0,
          background: thumb ? `#0d0a22 url(${thumb}) center/cover` : "rgba(255,255,255,0.06)",
          border: "1px solid var(--glass-border)"
        }} />
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</div>
        {meta && <div className="muted" style={{ fontSize: 12.5 }}>{meta}</div>}
      </div>
      {onPrice && (
        <div className="row" style={{ gap: 4, flexShrink: 0 }}>
          <span className="muted" style={{ fontSize: 13 }}>$</span>
          <input
            type="number" value={price} onChange={(e) => onPrice(e.target.value)}
            style={{
              width: 84, padding: "8px 10px", borderRadius: 10, fontSize: 14,
              background: "rgba(255,255,255,0.06)", color: "var(--ink)",
              border: "1px solid var(--glass-border)", outline: "none", textAlign: "right"
            }}
          />
        </div>
      )}
      <button onClick={onToggle} className="btn" style={{
        flexShrink: 0, padding: "8px 14px", fontSize: 13, fontWeight: 600, borderRadius: 999,
        border: "1px solid " + (isOff ? "var(--glass-border)" : "rgba(61,255,168,0.4)"),
        background: isOff ? "rgba(255,255,255,0.04)" : "rgba(61,255,168,0.14)",
        color: isOff ? "var(--ink-50)" : "#3dffa8"
      }}>{isOff ? "Oculto" : "Activo"}</button>
    </div>
  );
}

// ===== Panel de administración =====
function AdminPanel() {
  const FULL = window.CC_FULL || window.CC;
  const [draft, setDraft] = React.useState(() => {
    const d = window.ccLoadAdmin();
    return { off: d.off || {}, price: d.price || {}, offers: d.offers || {} };
  });
  const [tab, setTab] = React.useState("designs");
  const [mQuery, setMQuery] = React.useState("");
  const [mBrand, setMBrand] = React.useState("Todas");
  const [saved, setSaved] = React.useState(false);

  // helpers
  const isOff = (g, id) => !!(draft.off[g] && draft.off[g][id]);
  const toggle = (g, id) => setDraft((d) => {
    const off = { ...d.off }, grp = { ...(off[g] || {}) };
    if (grp[id]) delete grp[id]; else grp[id] = true;
    off[g] = grp; setSaved(false); return { ...d, off };
  });
  const priceOf = (g, id, fb) => {
    const v = draft.price[g] && draft.price[g][id];
    return (v === undefined || v === null) ? fb : v;
  };
  const setPrice = (g, id, val) => setDraft((d) => {
    const price = { ...d.price }, grp = { ...(price[g] || {}) };
    grp[id] = val; price[g] = grp; setSaved(false); return { ...d, price };
  });
  const offerOf = (id, f, fb) => {
    const v = draft.offers[id] && draft.offers[id][f];
    return (v === undefined || v === null) ? fb : v;
  };
  const setOffer = (id, f, val) => setDraft((d) => {
    const offers = { ...d.offers }, o = { ...(offers[id] || {}) };
    o[f] = val; offers[id] = o; setSaved(false); return { ...d, offers };
  });

  const save = () => { window.ccSaveAdmin(draft); setSaved(true); };
  const saveAndView = () => { window.ccSaveAdmin(draft); window.location.hash = ""; window.location.reload(); };
  const resetAll = () => {
    if (!window.confirm("Esto borra todos tus cambios y vuelve al catálogo original. ¿Seguro?")) return;
    window.ccResetAdmin(); window.location.reload();
  };

  // count changes
  const countOff = Object.values(draft.off).reduce((s, g) => s + Object.keys(g || {}).length, 0);

  const brands = ["Todas", ...Array.from(new Set(FULL.models.map((m) => m.brand)))];
  const modelsView = FULL.models.filter((m) =>
    (mBrand === "Todas" || m.brand === mBrand) &&
    (!mQuery || m.name.toLowerCase().includes(mQuery.toLowerCase()))
  );

  const TABS = [
    { id: "designs", label: "Diseños" },
    { id: "offers", label: "Ofertas" },
    { id: "models", label: "Modelos" },
    { id: "accessories", label: "Accesorios" },
  ];

  return (
    <div style={{ minHeight: "100vh", paddingBottom: 120 }}>
      {/* header */}
      <div className="glass-strong" style={{
        position: "sticky", top: 0, zIndex: 10, padding: "16px 0",
        borderRadius: 0, borderLeft: "none", borderRight: "none", borderTop: "none"
      }}>
        <div className="page row" style={{ justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 2 }}>PANEL DE ADMINISTRACIÓN</div>
            <h1 className="display" style={{ fontSize: 24 }}>COOLCASE <span className="grad-text">admin</span></h1>
          </div>
          <div className="row gap-12" style={{ flexWrap: "wrap" }}>
            {countOff > 0 && <span className="muted" style={{ fontSize: 13, alignSelf: "center" }}>{countOff} oculto{countOff !== 1 ? "s" : ""}</span>}
            <button onClick={resetAll} className="btn btn-ghost" style={{ padding: "10px 16px", fontSize: 13 }}>Restablecer</button>
            <button onClick={save} className="btn btn-ghost" style={{ padding: "10px 16px", fontSize: 13 }}>{saved ? "✓ Guardado" : "Guardar"}</button>
            <button onClick={saveAndView} className="btn btn-neon" style={{ padding: "10px 18px", fontSize: 14 }}>Guardar y ver tienda</button>
          </div>
        </div>
      </div>

      <div className="page" style={{ paddingTop: 24 }}>
        {/* tabs */}
        <div className="row gap-8" style={{ marginBottom: 20, flexWrap: "wrap" }}>
          {TABS.map((t) => (
            <button key={t.id} onClick={() => setTab(t.id)} className="btn" style={{
              padding: "9px 18px", fontSize: 14, borderRadius: 999,
              background: tab === t.id ? "var(--grad-neon)" : "var(--glass-bg)",
              color: "#fff", border: "1px solid " + (tab === t.id ? "transparent" : "var(--glass-border)")
            }}>{t.label}</button>
          ))}
        </div>

        <p className="muted" style={{ fontSize: 13.5, marginBottom: 18, maxWidth: 640 }}>
          Marca como <b style={{ color: "#3dffa8" }}>Activo</b> u <b>Oculto</b> lo que quieras mostrar en la tienda, y ajusta los precios.
          Cuando termines, toca <b>Guardar y ver tienda</b> para ver el resultado.
        </p>

        {/* DISEÑOS */}
        {tab === "designs" && (
          <div className="col gap-8">
            {FULL.designs.map((d) => (
              <CCRow key={d.id} thumb={d.img} title={d.name} meta={d.cat + " · " + d.author}
                isOff={isOff("designs", d.id)} onToggle={() => toggle("designs", d.id)}
                price={priceOf("designs", d.id, d.price)} onPrice={(v) => setPrice("designs", d.id, v)} />
            ))}
          </div>
        )}

        {/* OFERTAS */}
        {tab === "offers" && (
          <div className="col gap-12">
            {FULL.offers.map((o) => (
              <div key={o.id} className="glass" style={{ padding: 16, borderRadius: 16, opacity: isOff("offers", o.id) ? 0.5 : 1 }}>
                <div className="row" style={{ justifyContent: "space-between", marginBottom: 12, gap: 12 }}>
                  <input value={offerOf(o.id, "tag", o.tag)} onChange={(e) => setOffer(o.id, "tag", e.target.value)}
                    style={{ width: 90, padding: "8px 10px", borderRadius: 10, fontSize: 13, fontWeight: 700, textAlign: "center",
                      background: "rgba(255,255,255,0.06)", color: "var(--ink)", border: "1px solid var(--glass-border)", outline: "none" }} />
                  <button onClick={() => toggle("offers", o.id)} className="btn" style={{
                    padding: "8px 14px", fontSize: 13, fontWeight: 600, borderRadius: 999,
                    border: "1px solid " + (isOff("offers", o.id) ? "var(--glass-border)" : "rgba(61,255,168,0.4)"),
                    background: isOff("offers", o.id) ? "rgba(255,255,255,0.04)" : "rgba(61,255,168,0.14)",
                    color: isOff("offers", o.id) ? "var(--ink-50)" : "#3dffa8"
                  }}>{isOff("offers", o.id) ? "Oculta" : "Activa"}</button>
                </div>
                <input value={offerOf(o.id, "title", o.title)} onChange={(e) => setOffer(o.id, "title", e.target.value)}
                  placeholder="Título"
                  style={{ width: "100%", padding: "10px 12px", borderRadius: 10, fontSize: 15, fontWeight: 600, marginBottom: 8,
                    background: "rgba(255,255,255,0.06)", color: "var(--ink)", border: "1px solid var(--glass-border)", outline: "none" }} />
                <input value={offerOf(o.id, "desc", o.desc)} onChange={(e) => setOffer(o.id, "desc", e.target.value)}
                  placeholder="Descripción"
                  style={{ width: "100%", padding: "10px 12px", borderRadius: 10, fontSize: 14, marginBottom: 8,
                    background: "rgba(255,255,255,0.06)", color: "var(--ink)", border: "1px solid var(--glass-border)", outline: "none" }} />
                <input value={offerOf(o.id, "until", o.until)} onChange={(e) => setOffer(o.id, "until", e.target.value)}
                  placeholder="Vigencia (ej: Válido hasta 30 jun)"
                  style={{ width: "100%", padding: "10px 12px", borderRadius: 10, fontSize: 13,
                    background: "rgba(255,255,255,0.06)", color: "var(--ink-70)", border: "1px solid var(--glass-border)", outline: "none" }} />
              </div>
            ))}
          </div>
        )}

        {/* MODELOS */}
        {tab === "models" && (
          <div className="col gap-12">
            <div className="row gap-8" style={{ flexWrap: "wrap" }}>
              <select value={mBrand} onChange={(e) => setMBrand(e.target.value)}
                style={{ padding: "10px 12px", borderRadius: 10, fontSize: 14, background: "rgba(255,255,255,0.06)",
                  color: "var(--ink)", border: "1px solid var(--glass-border)", outline: "none" }}>
                {brands.map((b) => <option key={b} value={b} style={{ background: "#1a1336" }}>{b}</option>)}
              </select>
              <input value={mQuery} onChange={(e) => setMQuery(e.target.value)} placeholder="Buscar modelo…"
                style={{ flex: 1, minWidth: 160, padding: "10px 14px", borderRadius: 10, fontSize: 14,
                  background: "rgba(255,255,255,0.06)", color: "var(--ink)", border: "1px solid var(--glass-border)", outline: "none" }} />
            </div>
            <div className="muted" style={{ fontSize: 12.5 }}>{modelsView.length} de {FULL.models.length} modelos</div>
            <div className="col gap-8">
              {modelsView.slice(0, 80).map((m) => (
                <CCRow key={m.id} title={m.name} meta={m.brand}
                  isOff={isOff("models", m.id)} onToggle={() => toggle("models", m.id)}
                  price={priceOf("models", m.id, m.price)} onPrice={(v) => setPrice("models", m.id, v)} />
              ))}
              {modelsView.length > 80 && <div className="muted" style={{ fontSize: 13, padding: "8px 4px" }}>Mostrando 80 — afina la búsqueda para ver el resto.</div>}
            </div>
          </div>
        )}

        {/* ACCESORIOS */}
        {tab === "accessories" && (
          <div className="col gap-8">
            {FULL.accessories.map((a) => (
              <CCRow key={a.id} title={a.name} meta={a.desc}
                isOff={isOff("accessories", a.id)} onToggle={() => toggle("accessories", a.id)}
                price={priceOf("accessories", a.id, a.price)} onPrice={(v) => setPrice("accessories", a.id, v)} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ===== Ruta admin: login + panel =====
function AdminApp() {
  const [ok, setOk] = React.useState(() => sessionStorage.getItem("cc_admin_ok") === "1");
  if (!ok) return (
    <CCKeyScreen
      title="Panel de administración"
      sub="Ingresa tu clave de administradora para gestionar diseños, modelos, ofertas y precios."
      cta="Entrar al panel"
      accent="linear-gradient(110deg,#3dffa8,#2de2ff)"
      pass={CC_ADMIN_PASS}
      onOk={() => { sessionStorage.setItem("cc_admin_ok", "1"); setOk(true); }}
    />
  );
  return <AdminPanel />;
}
