/* global React, CATALOGO, CAT_LABELS, CAT_TOTALS, PATRONES, detectarPatron, ICONOS_INFO,
   Placeholder, Eyebrow, Arr, HeartIcon, Reveal, useWishlist, useUI, waLink */
const { useState, useMemo, useEffect } = React;

/* Una tarjeta de producto para listados (cat / categoría / modelo). */
function CatProd({ p, onOpen, onModelo }) {
  const wl = useWishlist();
  const isOn = wl.has(p.id);
  return (
    <div className="cat-prod" onClick={() => onOpen(p)}>
      <div className="img">
        {p.foto ? (
          <img src={p.foto} alt={p.nombre} loading="lazy" />
        ) : (
          <Placeholder ratio="auto" tone="bone" label={`/assets/productos/${p.id}.jpg`} fill />
        )}
        <button
          className={`heart ${isOn ? "is-on" : ""}`}
          aria-label={isOn ? "Quitar de mis piezas" : "Guardar"}
          onClick={(e) => { e.stopPropagation(); wl.toggle({ id: p.id, name: p.nombre, family: CAT_LABELS[p.categoria], pattern: detectarPatron(p.variante), price: p.precio.toLocaleString("es-CO") }); }}
        >
          <HeartIcon filled={isOn} size={14} stroke={isOn ? "var(--bone)" : "var(--ink)"} />
        </button>
      </div>
      <div className="head">
        <h4>{p.nombre}</h4>
        <div className="price">$ {p.precio.toLocaleString("es-CO")}</div>
      </div>
      {p.variante ? <div className="variant">{p.variante}</div> : null}
    </div>
  );
}

function Catalog({ initialFilter, setPage, openModelo, openFicha }) {
  const initial = { cat: "all", modelo: "all", patron: "all", q: "", sort: "destacado", ...(initialFilter || {}) };
  const [f, setF] = useState(initial);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const set = (k, v) => setF((x) => ({ ...x, [k]: v }));

  // Bloqueo scroll cuando drawer abierto
  useEffect(() => {
    document.body.style.overflow = drawerOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [drawerOpen]);

  useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [initialFilter?.cat]);

  // Modelos derivados del catálogo
  const modelos = useMemo(() => {
    const counts = {};
    CATALOGO.forEach((p) => { counts[p.nombre] = (counts[p.nombre] || 0) + 1; });
    return Object.entries(counts).sort((a, b) => b[1] - a[1]).map(([name, n]) => ({ name, n }));
  }, []);

  // Filtrado
  const filtered = useMemo(() => {
    let out = CATALOGO.slice();
    if (f.cat !== "all") out = out.filter((p) => p.categoria === f.cat);
    if (f.modelo !== "all") out = out.filter((p) => p.nombre === f.modelo);
    if (f.patron !== "all") out = out.filter((p) => detectarPatron(p.variante) === f.patron);
    if (f.q) {
      const q = f.q.toLowerCase();
      out = out.filter((p) =>
        p.nombre.toLowerCase().includes(q) ||
        (p.variante || "").toLowerCase().includes(q) ||
        p.id.toLowerCase().includes(q)
      );
    }
    if (f.sort === "destacado") out.sort((a, b) => (b.destacado - a.destacado));
    if (f.sort === "precio-asc") out.sort((a, b) => a.precio - b.precio);
    if (f.sort === "precio-desc") out.sort((a, b) => b.precio - a.precio);
    if (f.sort === "nombre") out.sort((a, b) => a.nombre.localeCompare(b.nombre));
    return out;
  }, [f]);

  const activeChips = [];
  if (f.cat !== "all") activeChips.push({ key: "cat", label: CAT_LABELS[f.cat], kind: "Categoría" });
  if (f.modelo !== "all") activeChips.push({ key: "modelo", label: f.modelo, kind: "Modelo" });
  if (f.patron !== "all") activeChips.push({ key: "patron", label: f.patron, kind: "Patrón" });
  if (f.q) activeChips.push({ key: "q", label: `"${f.q}"`, kind: "Buscar" });

  const clearAll = () => setF({ cat: "all", modelo: "all", patron: "all", q: "", sort: "destacado" });

  return (
    <div className="cat-page">
      <section className="cat-hero">
        <div className="crumb">Inicio  ·  Catálogo</div>
        <div className="top">
          <h1>
            {filtered.length}<br />
            <em>piezas</em>.
          </h1>
          <div className="lead">
            <Eyebrow>Tejido a mano · entrega en 15 días</Eyebrow>
            <p style={{ marginTop: 14 }}>
              Filtra por categoría, modelo o patrón. Toca cualquier pieza para verla en grande
              y pedirla por WhatsApp.
            </p>
          </div>
        </div>

        <div className="chips-row">
          <span className="chip-label">Filtros activos:</span>
          {activeChips.length === 0 ? (
            <span style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.14em", color: "var(--ink-mute)" }}>— ninguno · mostrando todo el catálogo</span>
          ) : (
            <>
              {activeChips.map((c) => (
                <button
                  key={c.key}
                  className="chip is-on"
                  onClick={() => set(c.key, c.key === "q" ? "" : "all")}
                >
                  <span className="kind">{c.kind} ·</span> {c.label} <span className="x">×</span>
                </button>
              ))}
              <button className="chip-clear" onClick={clearAll}>Limpiar todo</button>
            </>
          )}
        </div>
      </section>

      <div className="cat-layout">
        <aside className="cat-side">
          <input
            type="search"
            className="search"
            placeholder="Buscar nombre, código…"
            value={f.q}
            onChange={(e) => set("q", e.target.value)}
          />
          <h4>Categoría</h4>
          <div className="opt" onClick={() => set("cat", "all")} data-on={f.cat === "all"}>
            <span>Todas</span>
            <span className="n">{CATALOGO.length}</span>
          </div>
          {Object.entries(CAT_LABELS).map(([k, label]) => {
            const n = CATALOGO.filter((p) => p.categoria === k).length;
            return (
              <div key={k} className={`opt ${f.cat === k ? "is-on" : ""}`} onClick={() => set("cat", k)}>
                <span>{label}</span>
                <span className="n">{n}</span>
              </div>
            );
          })}

          <h4>Modelo</h4>
          <div className={`opt ${f.modelo === "all" ? "is-on" : ""}`} onClick={() => set("modelo", "all")}>
            <span>Todos</span>
            <span className="n">{modelos.length}</span>
          </div>
          {modelos.slice(0, 14).map((m) => (
            <div key={m.name} className={`opt ${f.modelo === m.name ? "is-on" : ""}`} onClick={() => set("modelo", m.name)}>
              <span>{m.name}</span>
              <span className="n">{m.n}</span>
            </div>
          ))}

          <h4>Patrón</h4>
          <div className={`opt ${f.patron === "all" ? "is-on" : ""}`} onClick={() => set("patron", "all")}>
            <span>Todos</span>
            <span className="n">—</span>
          </div>
          {PATRONES.map((p) => {
            const n = CATALOGO.filter((x) => detectarPatron(x.variante) === p).length;
            if (n === 0) return null;
            return (
              <div key={p} className={`opt ${f.patron === p ? "is-on" : ""}`} onClick={() => set("patron", p)}>
                <span>{p}</span>
                <span className="n">{n}</span>
              </div>
            );
          })}
        </aside>

        <div>
          <div className="cat-toolbar">
            <span>{filtered.length} resultados</span>
            <span>
              Ordenar
              <select value={f.sort} onChange={(e) => set("sort", e.target.value)} style={{ marginLeft: 10 }}>
                <option value="destacado">Destacados</option>
                <option value="precio-asc">Precio · menor</option>
                <option value="precio-desc">Precio · mayor</option>
                <option value="nombre">Nombre A — Z</option>
              </select>
            </span>
          </div>

          {filtered.length === 0 ? (
            <div className="cat-empty">— Sin resultados con esos filtros.</div>
          ) : (
            <div className="cat-grid">
              {filtered.map((p) => (
                <CatProd key={p.id} p={p} onOpen={openFicha} onModelo={openModelo} />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* MOBILE: FAB de filtros */}
      <button className="mobile-filter-fab" onClick={() => setDrawerOpen(true)}>
        <span>Filtros</span>
        {activeChips.length > 0 ? <span className="badge">{activeChips.length}</span> : null}
        <span className="arrow">↑</span>
      </button>

      {/* MOBILE: drawer de filtros */}
      <div className={`mobile-filter-drawer-back ${drawerOpen ? "is-open" : ""}`} onClick={() => setDrawerOpen(false)} />
      <aside className={`mobile-filter-drawer ${drawerOpen ? "is-open" : ""}`}>
        <div className="mobile-filter-drawer-handle" />
        <div className="mobile-filter-drawer-top">
          <h3>Filtros</h3>
          {activeChips.length > 0 ? (
            <button className="clear" onClick={clearAll}>Limpiar todo</button>
          ) : null}
        </div>
        <div className="mobile-filter-drawer-body">
          <div className="mobile-filter-section">
            <h4>¿Qué buscas?</h4>
            <div className="mobile-filter-chips">
              <button className={`mobile-filter-chip ${f.cat === "all" ? "is-on" : ""}`} onClick={() => set("cat", "all")}>
                Todas <span className="n">{CATALOGO.length}</span>
              </button>
              {Object.entries(CAT_LABELS).map(([k, label]) => {
                const n = CATALOGO.filter((p) => p.categoria === k).length;
                if (n === 0) return null;
                return (
                  <button key={k} className={`mobile-filter-chip ${f.cat === k ? "is-on" : ""}`} onClick={() => set("cat", k)}>
                    {label} <span className="n">{n}</span>
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        <div className="mobile-filter-drawer-foot">
          <button className="mobile-filter-apply" onClick={() => setDrawerOpen(false)}>
            Ver {filtered.length} {filtered.length === 1 ? "resultado" : "resultados"} →
          </button>
        </div>
      </aside>
    </div>
  );
}

window.Catalog = Catalog;
window.CatProd = CatProd;
