/* ============ Category page ============ */
function CategoryPage({ store, categoryId, navigate }) {
  const cat = store.categories.find(c => c.id === categoryId) || store.categories[0];
  const all = store.products.filter(p => p.category === cat.id);

  const [sort, setSort]           = useState("featured");
  const [priceMax, setPriceMax]   = useState(2000);
  const [materials, setMaterials] = useState(() => new Set()); // vacío = sin filtro (todos)
  const [size, setSize]           = useState(null);   // null = sin filtro
  // Filters: open by default on desktop, closed on mobile.
  const [filtersOpen, setFiltersOpen] = useState(() =>
    typeof window === "undefined" ? true : window.innerWidth >= 900
  );

  // Lock body scroll when the mobile filter drawer is open
  useEffect(() => {
    if (typeof window === "undefined") return;
    const isMobile = window.innerWidth < 900;
    if (filtersOpen && isMobile) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }
  }, [filtersOpen]);

  // Reset filters when switching to a different category
  useEffect(() => {
    setMaterials(new Set()); setSize(null); setPriceMax(2000); setSort("featured");
  }, [cat.id]);

  function toggleMaterial(m) {
    setMaterials(prev => {
      const next = new Set(prev);
      if (next.has(m)) next.delete(m); else next.add(m);
      return next;
    });
  }

  // Show material options based on what actually exists in this category
  const materialOptions = useMemo(() => {
    const set = new Set();
    all.forEach(p => {
      const m = (p.material || "").toLowerCase();
      if (m.includes("oro"))   set.add("Oro");
      if (m.includes("plata")) set.add("Plata");
    });
    return Array.from(set);
  }, [all]);

  // Show size options that exist in this category
  const sizes = useMemo(() => {
    const set = new Set();
    all.forEach(p => (p.sizes || []).forEach(s => set.add(s)));
    return Array.from(set);
  }, [all]);

  const filtered = useMemo(() => {
    let list = all.filter(p => p.price <= priceMax);
    if (materials.size > 0) {
      list = list.filter(p => {
        const m = (p.material || "").toLowerCase();
        // OR across selected materials
        if (materials.has("Oro")   && m.includes("oro"))   return true;
        if (materials.has("Plata") && m.includes("plata")) return true;
        return false;
      });
    }
    if (size) {
      list = list.filter(p => Array.isArray(p.sizes) && p.sizes.includes(size));
    }
    if (sort === "asc")  list = [...list].sort((a,b)=>a.price-b.price);
    if (sort === "desc") list = [...list].sort((a,b)=>b.price-a.price);
    if (sort === "name") list = [...list].sort((a,b)=>a.name.localeCompare(b.name));
    return list;
  }, [all, sort, priceMax, materials, size]);

  // Always show only products that belong to this category — no padding.
  const showSet = filtered;

  return (
    <main>
      {/* Hero header */}
      <section style={{ borderBottom: "1px solid var(--line-2)" }}>
        <div className="section" style={{ paddingTop: 56, paddingBottom: 48 }}>
          <div style={{ display: "flex", gap: 8, fontSize: 12,
            letterSpacing: "0.16em", textTransform: "uppercase",
            color: "var(--ink-2)" }}>
            <a onClick={()=>navigate("/")} style={{ cursor: "pointer" }}>Inicio</a>
            <span>/</span>
            <span style={{ color: "var(--burgundy)" }}>{cat.name}</span>
          </div>
          <div className="cat-hero" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 56, marginTop: 28, alignItems: "end" }}>
            <h1 style={{
              fontFamily: "var(--serif)", fontWeight: 300,
              fontSize: "clamp(34px, 8vw, 112px)", lineHeight: 1,
              letterSpacing: "-0.015em", color: "var(--burgundy)", margin: 0,
            }}>
              {cat.name}
            </h1>
            {cat.tagline && (
              <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--ink-2)", maxWidth: 460 }}>
                {cat.tagline}
              </p>
            )}
          </div>
        </div>
      </section>

      {/* Toolbar */}
      <div className="cat-toolbar" style={{
        position: "sticky", top: 81, zIndex: 30,
        background: "var(--bg)",
        borderBottom: "1px solid var(--line-2)",
        padding: "14px var(--pad)",
        display: "flex", justifyContent: "space-between", alignItems: "center",
      }}>
        <button onClick={()=>setFiltersOpen(o=>!o)}
                style={{
                  background: "transparent", border: 0, color: "var(--burgundy)",
                  display: "inline-flex", alignItems: "center", gap: 10,
                  fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase",
                  fontWeight: 600, cursor: "pointer",
                }}>
          <span style={{ display: "inline-flex", gap: 4 }}>
            <span style={{ width: 14, height: 2, background: "currentColor", display: "block" }}/>
            <span style={{ width: 14, height: 2, background: "currentColor", display: "block" }}/>
          </span>
          Filtros {filtersOpen ? "(activos)" : ""}
        </button>
        <div style={{ fontSize: 12, color: "var(--ink-2)", letterSpacing: "0.1em" }}>
          {filtered.length} piezas
        </div>
        <label style={{ display: "inline-flex", alignItems: "center", gap: 12,
          fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase",
          fontWeight: 600, color: "var(--burgundy)" }}>
          Ordenar
          <select value={sort} onChange={e=>setSort(e.target.value)}
                  style={{ background: "transparent", border: 0,
                    borderBottom: "1px solid var(--burgundy)",
                    color: "var(--burgundy)", fontSize: 12, letterSpacing: "0.12em",
                    fontWeight: 600, padding: "4px 0", textTransform: "uppercase",
                    fontFamily: "var(--sans)", outline: "none" }}>
            <option value="featured">Destacados</option>
            <option value="asc">Precio: bajo a alto</option>
            <option value="desc">Precio: alto a bajo</option>
            <option value="name">Nombre A–Z</option>
          </select>
        </label>
      </div>

      {/* Body */}
      <div className={`section cat-body ${filtersOpen ? "filters-open" : ""}`} style={{
        display: "grid",
        gridTemplateColumns: filtersOpen ? "240px 1fr" : "1fr",
        gap: 56, paddingTop: 48, alignItems: "start",
      }}>
        {filtersOpen && (
          <div className="cat-filters-backdrop" onClick={()=>setFiltersOpen(false)}/>
        )}
        {filtersOpen && (
          <aside className="cat-filters" style={{ position: "sticky", top: 160, fontSize: 13 }}>
            <div className="cat-filters-header">
              <span>Filtros</span>
              <button type="button" aria-label="Cerrar filtros"
                onClick={()=>setFiltersOpen(false)}
                style={{ background: "transparent", border: 0, color: "var(--burgundy)",
                  fontSize: 22, lineHeight: 1, cursor: "pointer", padding: 4 }}>
                ×
              </button>
            </div>
            <FilterGroup title="Material">
              {materialOptions.length === 0 && (
                <div style={{ fontSize: 12, color: "var(--ink-2)" }}>Sin materiales disponibles.</div>
              )}
              {materialOptions.map(m => (
                <label key={m} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", padding: "6px 0" }}>
                  <input type="checkbox" checked={materials.has(m)} onChange={()=>toggleMaterial(m)}
                         style={{ accentColor: "var(--burgundy)" }} />
                  <span>{m}</span>
                </label>
              ))}
              {materials.size > 0 && (
                <button type="button" onClick={()=>setMaterials(new Set())}
                  style={{ background: "transparent", border: 0, color: "var(--ink-2)",
                    fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase",
                    textDecoration: "underline", cursor: "pointer", padding: "8px 0 0" }}>
                  Limpiar
                </button>
              )}
            </FilterGroup>

            <FilterGroup title="Precio">
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--ink-2)", marginBottom: 8 }}>
                <span>$0</span><span>{fmtPrice(priceMax)}</span>
              </div>
              <input type="range" min="500" max="2000" step="50"
                     value={priceMax} onChange={e=>setPriceMax(+e.target.value)}
                     style={{ width: "100%", accentColor: "var(--burgundy)" }}/>
            </FilterGroup>

            {sizes.length > 0 && (
              <FilterGroup title="Talla" hideBorder>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {sizes.map(s => (
                    <button key={s} type="button" onClick={()=>setSize(size === s ? null : s)}
                      style={{
                        padding: "6px 10px", fontSize: 12, fontWeight: 600,
                        border: "1px solid " + (size === s ? "var(--burgundy)" : "var(--line)"),
                        background: size === s ? "var(--burgundy)" : "var(--cream)",
                        color: size === s ? "var(--pink-50)" : "var(--ink)",
                        cursor: "pointer", fontFamily: "var(--sans)",
                      }}>{s}</button>
                  ))}
                </div>
              </FilterGroup>
            )}
          </aside>
        )}

        {showSet.length > 0 ? (
          <div style={{
            display: "grid",
            gridTemplateColumns: filtersOpen ? "repeat(3, 1fr)" : "repeat(4, 1fr)",
            gap: "40px 24px",
          }} className="prod-grid">
            {showSet.map(p => (
              <ProductCard key={p.id} p={p} onClick={()=>navigate("/p/"+p.id)}/>
            ))}
          </div>
        ) : (
          <div style={{
            padding: "80px 24px", textAlign: "center", color: "var(--ink-2)",
            border: "1px solid var(--line-2)",
          }}>
            <div className="eyebrow">Sin piezas todavía</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 28, color: "var(--burgundy)", marginTop: 8 }}>
              {all.length === 0
                ? "Aún no hay piezas en esta categoría."
                : "Ninguna pieza coincide con los filtros."}
            </div>
            {all.length > 0 && (
              <button onClick={()=>{ setMaterials(new Set()); setSize(null); setPriceMax(2000); }}
                className="btn btn-ghost btn-sm" style={{ marginTop: 20 }}>
                Limpiar filtros
              </button>
            )}
          </div>
        )}
      </div>
    </main>
  );
}

function FilterGroup({ title, children, hideBorder }) {
  const [open, setOpen] = useState(true);
  return (
    <div style={{
      borderBottom: hideBorder ? "none" : "1px solid var(--line-2)",
      paddingBottom: 22, marginBottom: 22,
    }}>
      <button onClick={()=>setOpen(o=>!o)}
              style={{ background: "transparent", border: 0,
                width: "100%", display: "flex", justifyContent: "space-between",
                alignItems: "center", padding: "4px 0", marginBottom: 10,
                fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
                color: "var(--burgundy)", fontWeight: 600, cursor: "pointer" }}>
        {title}
        <Icon name={open ? "chevD" : "chevR"} size={14}/>
      </button>
      {open && <div>{children}</div>}
    </div>
  );
}

window.CategoryPage = CategoryPage;
