/* global React, useApp, Foto, SectionHead, ProductCard, PapelPicado, MOTIFS, GlyphDiamond,
   IconFilter, IconChevron, PRODUCTS, CATEGORIES, FILTERS, fmt */
const { createElement: k, useState: useStateCat, useEffect: useEffectCat } = React;

function CheckRow({ active, onClick, children, dot }) {
  return k("button", { onClick, style: { display: "flex", alignItems: "center", gap: 11, background: "none", border: "none", padding: "8px 0", width: "100%", textAlign: "left", color: active ? "var(--vino)" : "var(--ink-soft)", fontFamily: "var(--font-ui)", fontSize: 14, fontWeight: active ? 600 : 400 } },
    k("span", { style: { width: 17, height: 17, borderRadius: 4, border: `1.5px solid ${active ? "var(--vino)" : "var(--amate-line)"}`, background: active ? "var(--vino)" : "rgba(0,0,0,.25)", display: "grid", placeItems: "center", flex: "none" } },
      active && k("span", { style: { width: 7, height: 7, borderRadius: 2, background: "var(--gold-claro)" } })),
    dot && k("span", { style: { width: 14, height: 14, borderRadius: "50%", background: dot, border: "1px solid rgba(0,0,0,.15)", flex: "none" } }),
    k("span", null, children));
}

function FilterGroup({ title, children, open = true }) {
  const [o, setO] = useStateCat(open);
  return k("div", { style: { borderBottom: "1px solid var(--amate-line)", padding: "16px 0" } },
    k("button", { onClick: () => setO(v => !v), style: { display: "flex", justifyContent: "space-between", alignItems: "center", width: "100%", background: "none", border: "none", padding: 0 } },
      k("span", { className: "eyebrow", style: { color: "var(--ink)", fontSize: 12.5 } }, title),
      k(IconChevron, { size: 16, style: { color: "var(--ink-faint)", transform: o ? "none" : "rotate(-90deg)", transition: "transform .2s" } })),
    o && k("div", { style: { marginTop: 10 } }, children));
}

function CatalogPage() {
  const { route, isFav } = useApp();
  const initCat = route.params && route.params.cat;
  const favView = !!(route.params && route.params.favs);
  const newView = !!(route.params && route.params.nuevo);
  const isNew = (p) => p.nuevo === true || (p.badge && p.badge.toLowerCase().indexOf("nuevo") >= 0);
  const [cats, setCats] = useStateCat(initCat ? [initCat] : []);
  const [sizes, setSizes] = useStateCat([]);
  const [colors, setColors] = useStateCat([]);
  const [maxPrice, setMaxPrice] = useStateCat(2500);
  const [sort, setSort] = useStateCat("destacados");
  const [filtersOpen, setFiltersOpen] = useStateCat(false);

  useEffectCat(() => { setCats(initCat ? [initCat] : []); }, [initCat]);

  const toggle = (arr, setArr, v) => setArr(arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v]);

  let list = PRODUCTS.filter(p =>
    (favView ? isFav(p.id) : true) &&
    (newView ? isNew(p) : true) &&
    (cats.length === 0 || cats.includes(p.cat)) &&
    (sizes.length === 0 || p.sizes.some(s => sizes.includes(s))) &&
    (colors.length === 0 || p.colors.some(cl => colors.some(sel => cl.toLowerCase().includes(sel.toLowerCase())))) &&
    p.price <= maxPrice
  );
  if (sort === "menor") list = [...list].sort((a, b) => a.price - b.price);
  if (sort === "mayor") list = [...list].sort((a, b) => b.price - a.price);
  if (sort === "rating") list = [...list].sort((a, b) => b.rating - a.rating);

  const activeCount = cats.length + sizes.length + colors.length + (maxPrice < 2500 ? 1 : 0);

  return k("div", { style: { background: "var(--bone)" } },
    /* encabezado */
    k("div", { style: { background: "radial-gradient(ellipse at 50% 0%, var(--obsidian-3), var(--obsidian))", color: "var(--bone)", padding: "48px 0 44px", textAlign: "center" } },
      k("div", { className: "wrap" },
        k("div", { style: { display: "flex", justifyContent: "center", marginBottom: 16 } }, k(MOTIFS.calavera, { size: 44, style: { color: "var(--marigold)" } })),
        k("h1", { className: "display", style: { fontSize: "clamp(32px,4vw,50px)", margin: "0 0 12px", textTransform: "uppercase", letterSpacing: ".05em" } }, newView ? "Lo Nuevo" : favView ? "Tus favoritos" : "La Tienda"),
        k("p", { className: "serif", style: { fontSize: 19, opacity: .82, margin: 0 } }, newView ? "Lo más reciente que llegó al inframundo" : favView ? "Las piezas que has guardado" : ["Todo lo que el inframundo tiene para ti — ", PRODUCTS.length, " piezas"])
      )
    ),
    k(PapelPicado, { height: 26, count: 24 }),
    k("div", { className: "wrap catalog-grid", style: { display: "grid", gridTemplateColumns: "248px 1fr", gap: 38, paddingTop: 40, paddingBottom: 70, alignItems: "start" } },
      /* sidebar / drawer móvil */
      filtersOpen && k("div", { className: "catalog-aside-backdrop", onClick: () => setFiltersOpen(false) }),
      k("aside", { className: "catalog-aside" + (filtersOpen ? " open" : ""), style: { position: "sticky", top: 160 } },
        filtersOpen && k("button", { className: "btn btn-ghost btn-full", onClick: () => setFiltersOpen(false), style: { marginBottom: 16 } }, "✕  Cerrar filtros"),
        k("div", { style: { display: "flex", alignItems: "center", gap: 10, marginBottom: 6 } },
          k(IconFilter, { size: 18, style: { color: "var(--vino)" } }),
          k("span", { className: "display", style: { fontSize: 19, textTransform: "uppercase", letterSpacing: ".06em" } }, "Filtrar"),
          activeCount > 0 && k("button", { onClick: () => { setCats([]); setSizes([]); setColors([]); setMaxPrice(2500); }, style: { marginLeft: "auto", background: "none", border: "none", color: "var(--ink-faint)", fontSize: 12, textDecoration: "underline", cursor: "pointer" } }, "Limpiar")
        ),
        k(FilterGroup, { title: "Categoría" },
          CATEGORIES.map(cat => k(CheckRow, { key: cat.id, active: cats.includes(cat.id), onClick: () => toggle(cats, setCats, cat.id) }, cat.name))),
        k(FilterGroup, { title: "Talla" },
          k("div", { style: { display: "flex", flexWrap: "wrap", gap: 8 } },
            FILTERS.sizes.map(s => k("button", { key: s, onClick: () => toggle(sizes, setSizes, s), className: "chip", style: sizes.includes(s) ? { background: "var(--ink)", color: "var(--bone)", borderColor: "var(--ink)", padding: "7px 14px" } : { padding: "7px 14px" } }, s)))),
        k(FilterGroup, { title: "Color" },
          FILTERS.colors.map(cl => k(CheckRow, { key: cl.name, active: colors.includes(cl.name), onClick: () => toggle(colors, setColors, cl.name), dot: cl.dot }, cl.name))),
        k(FilterGroup, { title: "Precio máximo" },
          k("div", { style: { padding: "6px 2px" } },
            k("input", { type: "range", min: 199, max: 2500, step: 50, value: maxPrice, onChange: e => setMaxPrice(+e.target.value), style: { width: "100%", accentColor: "var(--vino)" } }),
            k("div", { style: { display: "flex", justifyContent: "space-between", fontSize: 13, color: "var(--ink-soft)", marginTop: 6, fontFamily: "var(--font-serif)" } },
              k("span", null, "$199"), k("span", { style: { color: "var(--vino)", fontWeight: 600 } }, fmt(maxPrice))))),
        filtersOpen && k("button", { className: "btn btn-gold btn-full", onClick: () => setFiltersOpen(false), style: { marginTop: 18 } }, "Ver " + list.length + " resultado" + (list.length !== 1 ? "s" : ""))
      ),
      /* grid */
      k("div", null,
        k("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22, flexWrap: "wrap", gap: 12 } },
          k("button", { className: "catalog-filter-btn", onClick: () => setFiltersOpen(true) },
            k(IconFilter, { size: 16 }), "Filtrar", activeCount > 0 && k("span", { style: { background: "var(--gold-claro)", color: "var(--bg)", borderRadius: 999, fontSize: 11, fontWeight: 700, minWidth: 18, height: 18, display: "inline-grid", placeItems: "center", padding: "0 5px" } }, activeCount)),
          k("span", { style: { color: "var(--ink-soft)", fontSize: 14, fontFamily: "var(--font-serif)", fontStyle: "italic" } }, list.length, " resultado", list.length !== 1 ? "s" : ""),
          k("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
            k("span", { className: "eyebrow", style: { fontSize: 11, color: "var(--ink-faint)" } }, "Ordenar"),
            k("select", { value: sort, onChange: e => setSort(e.target.value), className: "field", style: { width: "auto", padding: "9px 12px", fontWeight: 600 } },
              k("option", { value: "destacados" }, "Destacados"),
              k("option", { value: "menor" }, "Precio: menor a mayor"),
              k("option", { value: "mayor" }, "Precio: mayor a menor"),
              k("option", { value: "rating" }, "Mejor valorados")))
        ),
        list.length === 0
          ? k("div", { style: { textAlign: "center", padding: "80px 0", color: "var(--ink-faint)" } },
              k(MOTIFS.hueso, { size: 60, style: { margin: "0 auto 20px", color: "var(--amate-line)" } }),
              k("p", { className: "serif", style: { fontSize: 20 } }, newView ? "Aún no hay productos nuevos. Vuelve pronto." : favView ? "Aún no has guardado favoritos. Toca el corazón en cualquier pieza." : "Ningún alma encontró estas piezas. Ajusta los filtros."))
          : k("div", { className: "products-grid", style: { display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 22 } },
              list.map(p => k(ProductCard, { key: p.id, p, height: 280 })))
      )
    )
  );
}

Object.assign(window, { CatalogPage });
