// CATALOG — Artesanías Chepe

const PRICE_RANGES = [
  { id: "lt1000",    label: "Menos $1,000",     min: 0,     max: 999 },
  { id: "1k-3k",    label: "$1,000 – $3,000",   min: 1000,  max: 3000 },
  { id: "3k-10k",   label: "$3,000 – $10,000",  min: 3001,  max: 10000 },
  { id: "gt10000",  label: "+ $10,000",          min: 10001, max: Infinity },
];

const Catalog = ({ onNav, onProduct, onAddCart, initialCat }) => {
  const [cat, setCat] = useState(initialCat || "all");
  const [sort, setSort] = useState("destacados");
  const [showFilters, setShowFilters] = useState(false);
  const [filterMaterials, setFilterMaterials] = useState([]);
  const [filterPrice, setFilterPrice] = useState("");

  const allMaterials = useMemo(() => {
    const s = new Set();
    window.PRODUCTS.forEach(p => p.materials.forEach(m => s.add(m)));
    return [...s];
  }, []);

  const activeFilterCount = filterMaterials.length + (filterPrice ? 1 : 0);

  const toggleMaterial = (m) => setFilterMaterials(prev =>
    prev.includes(m) ? prev.filter(x => x !== m) : [...prev, m]
  );

  const clearFilters = () => { setFilterMaterials([]); setFilterPrice(""); };

  const filtered = useMemo(() => {
    let list = cat === "all" ? window.PRODUCTS : window.PRODUCTS.filter(p => p.cat === cat);
    if (filterMaterials.length > 0)
      list = list.filter(p => p.materials.some(m => filterMaterials.includes(m)));
    if (filterPrice) {
      const range = PRICE_RANGES.find(r => r.id === filterPrice);
      if (range) list = list.filter(p => p.price >= range.min && p.price <= range.max);
    }
    if (sort === "menor") list = [...list].sort((a, b) => a.price - b.price);
    if (sort === "mayor") list = [...list].sort((a, b) => b.price - a.price);
    return list;
  }, [cat, sort, filterMaterials, filterPrice]);

  return (
    <div className="page" data-screen-label="02 Catálogo">
      <div style={{ padding: "12px 20px 16px" }}>
        <div className="eyebrow" style={{ marginBottom: 6 }}>Catálogo · {filtered.length} piezas</div>
        <h1 className="display" style={{ fontSize: 52, margin: 0 }}>
          Todo el <span className="italic" style={{ color: "var(--clay)" }}>taller</span>
        </h1>
      </div>

      {/* Categoría chips */}
      <div className="rail" style={{ padding: "8px 20px 12px" }}>
        <button onClick={() => setCat("all")} className={"chip " + (cat === "all" ? "is-active" : "")}>Todo</button>
        {window.CATEGORIES.map(c => (
          <button key={c.id} onClick={() => setCat(c.id)} className={"chip " + (cat === c.id ? "is-active" : "")}>
            {c.name}
          </button>
        ))}
      </div>

      {/* Sort + filter */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 20px 16px", borderBottom: "1px solid var(--hair)" }}>
        <button onClick={() => setShowFilters(true)} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: activeFilterCount > 0 ? "var(--clay)" : "var(--ink-80)" }}>
          <Icon name="filter" size={14} /> Filtros
          {activeFilterCount > 0 && (
            <span style={{
              background: "var(--clay)", color: "var(--bone)",
              minWidth: 18, height: 18, borderRadius: 999,
              display: "grid", placeItems: "center",
              fontSize: 10, fontWeight: 600, padding: "0 5px",
            }}>{activeFilterCount}</span>
          )}
        </button>
        <div style={{ position: "relative" }}>
          <select value={sort} onChange={e => setSort(e.target.value)} style={{
            background: "transparent", border: 0,
            fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-80)",
            paddingRight: 18, cursor: "pointer", appearance: "none",
          }}>
            <option value="destacados">Destacados</option>
            <option value="menor">Precio menor</option>
            <option value="mayor">Precio mayor</option>
          </select>
          <Icon name="arrow" size={12} style={{ position: "absolute", right: 0, top: 1, transform: "rotate(90deg)", pointerEvents: "none" }} />
        </div>
      </div>

      {/* Grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "28px 14px", padding: "24px 20px 40px" }}>
        {filtered.length === 0 && (
          <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: "64px 20px" }}>
            <div className="ph" style={{ width: 80, height: 80, borderRadius: 999, margin: "0 auto 20px" }}></div>
            <h2 className="display italic" style={{ fontSize: 28, margin: "0 0 8px", color: "var(--clay)" }}>
              Sin piezas aquí
            </h2>
            <p style={{ color: "var(--ink-60)", fontSize: 14, lineHeight: 1.5, marginBottom: 24 }}>
              No encontramos nada en esta categoría.<br />Prueba con otra o explora todo el taller.
            </p>
            <button className="btn btn-ghost" onClick={() => setCat("all")}>
              Ver todo el taller <Icon name="arrow" size={16} />
            </button>
          </div>
        )}
        {filtered.map((p, i) => (
          <div key={p.id} style={{ animationDelay: (i * 40) + "ms" }} className="fade-up">
            <ProductCard product={p} onClick={onProduct} onAdd={onAddCart} />
          </div>
        ))}
      </div>

      <Footer onNav={onNav} />

      {/* Filters drawer */}
      {showFilters && (
        <React.Fragment>
          <div onClick={() => setShowFilters(false)} style={{ position: "fixed", inset: 0, background: "color-mix(in srgb, var(--ink) 50%, transparent)", zIndex: 80, animation: "fadeIn .2s ease" }} />
          <div style={{
            position: "fixed", bottom: 0, left: "50%", transform: "translateX(-50%)",
            width: "100%", maxWidth: 480, background: "var(--bone)",
            borderRadius: "18px 18px 0 0", zIndex: 90, padding: 22,
            animation: "slideUp .35s cubic-bezier(.2,.7,.2,1)",
          }}>
            <style>{`@keyframes slideUp { from { transform: translate(-50%, 100%); } to { transform: translate(-50%, 0); } }`}</style>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
              <h3 className="serif" style={{ fontSize: 24, margin: 0 }}>Filtrar</h3>
              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                {activeFilterCount > 0 && (
                  <button onClick={clearFilters} style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--clay)" }}>
                    Limpiar
                  </button>
                )}
                <button onClick={() => setShowFilters(false)} aria-label="Cerrar filtros"><Icon name="close" size={20} /></button>
              </div>
            </div>
            <div className="stack-6">
              <div>
                <div className="eyebrow" style={{ marginBottom: 10 }}>Material</div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {allMaterials.map(m => (
                    <button key={m} onClick={() => toggleMaterial(m)}
                      className={"chip " + (filterMaterials.includes(m) ? "is-active" : "")}>{m}</button>
                  ))}
                </div>
              </div>
              <div>
                <div className="eyebrow" style={{ marginBottom: 10 }}>Precio</div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {PRICE_RANGES.map(r => (
                    <button key={r.id} onClick={() => setFilterPrice(filterPrice === r.id ? "" : r.id)}
                      className={"chip " + (filterPrice === r.id ? "is-active" : "")}>{r.label}</button>
                  ))}
                </div>
              </div>
              <button className="btn btn-primary btn-block" onClick={() => setShowFilters(false)}>
                Ver {filtered.length} {filtered.length === 1 ? "pieza" : "piezas"}
              </button>
            </div>
          </div>
        </React.Fragment>
      )}
    </div>
  );
};

window.Catalog = Catalog;
