// PLP.jsx — Product Listing Page with left filters
const { useState: usePLPState, useMemo: usePLPMemo } = React;

const PLP = ({ params, onNav, onAdd, onFav, favs }) => {
const PLP = ({ params, onNav, onAdd, onFav, favs }) => {
  const [sort, setSort] = usePLPState(params?.sort || "relevance");
  const [activeCat, setActiveCat] = usePLPState(params?.cat || "all");
  const [priceMax, setPriceMax] = usePLPState(8000);
  const [onlyDiscount, setOnlyDiscount] = usePLPState(!!params?.onlyDiscount);
  const [brands, setBrands] = usePLPState(new Set());
  const [q, setQ] = usePLPState(params?.q || "");
  const [filtersOpen, setFiltersOpen] = usePLPState(false);
  const { isMobile, isTablet } = useViewport();

  const filtered = usePLPMemo(() => {
    let r = CATALOG;
    if (activeCat !== "all") r = r.filter(p => p.cat === activeCat);
    if (onlyDiscount) r = r.filter(p => p.discount);
    if (brands.size) r = r.filter(p => brands.has(p.brand));
    r = r.filter(p => p.price <= priceMax);
    if (q.trim()) {
      const needle = q.trim().toLowerCase();
      r = r.filter(p =>
        p.name.toLowerCase().includes(needle) ||
        p.brand.toLowerCase().includes(needle) ||
        (CATEGORIES.find(c => c.id === p.cat)?.label || "").toLowerCase().includes(needle)
      );
    }
    if (sort === "price-asc") r = [...r].sort((a, b) => a.price - b.price);
    if (sort === "price-desc") r = [...r].sort((a, b) => b.price - a.price);
    if (sort === "discount") r = [...r].sort((a, b) => (b.discount || 0) - (a.discount || 0));
    if (sort === "rating") r = [...r].sort((a, b) => b.rating - a.rating);
    return r;
  }, [activeCat, onlyDiscount, brands, priceMax, sort, q]);

  const allBrands = [...new Set(CATALOG.map(p => p.brand))];

  return (
    <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: isMobile ? "0 16px" : "0 32px" }}>
      <Breadcrumb items={["Inicio", "Productos", activeCat === "all" ? "Todos" : CATEGORIES.find(c => c.id === activeCat)?.label || activeCat]} />

      {q.trim() && (
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 20px", background: "var(--primary-soft)", borderRadius: "var(--radius-md)", marginBottom: 16 }}>
          <span className="body" style={{ color: "var(--fg-strong)" }}>
            Resultados para <strong style={{ color: "var(--primary-press)" }}>"{q}"</strong>
          </span>
          <button onClick={() => setQ("")} style={{ background: "transparent", border: 0, color: "var(--primary)", font: "700 13px var(--font-sans)", cursor: "pointer", display: "flex", alignItems: "center", gap: 4 }}>
            Limpiar búsqueda <AllenIcon name="close" size={14} />
          </button>
        </div>
      )}

      {/* Category chip strip */}
      <div style={{ display: "flex", gap: 8, marginBottom: 24, overflowX: "auto", paddingBottom: 4 }}>
        <Chip selected={activeCat === "all"} onClick={() => setActiveCat("all")}>Todo</Chip>
        {CATEGORIES.map(c => (
          <Chip key={c.id} selected={activeCat === c.id} onClick={() => setActiveCat(c.id)}>{c.label}</Chip>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "260px 1fr", gap: isMobile ? 16 : 32, alignItems: "start" }}>
        {/* FILTERS — desktop sidebar / mobile drawer */}
        {!isMobile && (
          <FilterPanel {...{ priceMax, setPriceMax, onlyDiscount, setOnlyDiscount, brands, setBrands }} />
        )}
        {isMobile && (
          <button onClick={() => setFiltersOpen(true)}
            style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, padding: "12px 16px", background: "var(--bg-elev-1)", border: "1px solid var(--border-strong)", borderRadius: "9999px", font: "700 13px var(--font-sans)", color: "var(--fg-strong)", cursor: "pointer" }}>
            <AllenIcon name="tune" size={16} /> Filtros{(brands.size || onlyDiscount || priceMax < 8000) ? ` (${brands.size + (onlyDiscount ? 1 : 0) + (priceMax < 8000 ? 1 : 0)})` : ""}
          </button>
        )}
        {isMobile && filtersOpen && (
          <div onClick={() => setFiltersOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.55)", zIndex: 100 }}>
            <div onClick={e => e.stopPropagation()} style={{ position: "absolute", bottom: 0, left: 0, right: 0, background: "var(--bg-elev-1)", borderRadius: "var(--radius-xl) var(--radius-xl) 0 0", padding: 20, maxHeight: "85vh", overflowY: "auto" }}>
              <div style={{ width: 40, height: 4, borderRadius: 2, background: "var(--border-strong)", margin: "0 auto 16px" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <h3 className="title-lg">Filtros</h3>
                <button onClick={() => setFiltersOpen(false)} style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--fg-strong)" }}><AllenIcon name="close" size={20} /></button>
              </div>
              <FilterPanel {...{ priceMax, setPriceMax, onlyDiscount, setOnlyDiscount, brands, setBrands, allBrands }} embedded />
              <button onClick={() => setFiltersOpen(false)} style={{ width: "100%", marginTop: 16, background: "var(--primary)", color: "#fff", border: 0, padding: "14px 20px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>Ver {filtered.length} resultados</button>
            </div>
          </div>
        )}

        {/* GRID */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, gap: 12, flexWrap: "wrap" }}>
            <span className="body-sm">{filtered.length} resultados</span>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {!isMobile && <span className="body-sm">Ordenar por</span>}
              <select value={sort} onChange={e => setSort(e.target.value)}
                style={{
                  background: "var(--bg-elev-1)", border: "1px solid var(--border-strong)",
                  borderRadius: "var(--radius-input)", padding: "8px 12px",
                  font: "600 13px var(--font-sans)", color: "var(--fg-strong)", cursor: "pointer",
                }}>
                <option value="relevance">Relevancia</option>
                <option value="price-asc">Precio: menor a mayor</option>
                <option value="price-desc">Precio: mayor a menor</option>
                <option value="discount">Mayor descuento</option>
                <option value="rating">Mejor calificación</option>
              </select>
            </div>
          </div>
          {filtered.length === 0 ? (
            <div style={{ padding: 64, textAlign: "center", background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)" }}>
              <AllenIcon name="search_off" size={48} color="var(--fg-hint)" />
              <h3 className="title-lg" style={{ marginTop: 12 }}>No encontramos resultados</h3>
              <p className="body-sm" style={{ marginTop: 6 }}>Cambia los filtros o amplía el rango de precio.</p>
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 1fr" : isTablet ? "repeat(2, 1fr)" : "repeat(3, 1fr)", gap: isMobile ? 12 : 20 }}>
              {filtered.map(p => <ProductCard key={p.id} p={p} onOpen={() => onNav("pdp", { id: p.id })} onAdd={onAdd} onFav={onFav} fav={favs.has(p.id)} />)}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const FilterPanel = ({ priceMax, setPriceMax, onlyDiscount, setOnlyDiscount, brands, setBrands, allBrands, embedded }) => {
  const all = allBrands || [...new Set(CATALOG.map(p => p.brand))];
  const Wrapper = embedded ? React.Fragment : 'aside';
  const wrapperProps = embedded ? {} : {
    style: { position: "sticky", top: 160, background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 20 }
  };
  return (
    <Wrapper {...wrapperProps}>
      {!embedded && <h3 className="title" style={{ marginBottom: 18 }}>Filtros</h3>}

      <FilterBlock title="Precio">
        <div style={{ display: "flex", justifyContent: "space-between", font: "500 13px var(--font-sans)", color: "var(--fg-muted)", marginBottom: 8 }}>
          <span>$0</span><span>${priceMax.toLocaleString("es-MX")}</span>
        </div>
        <input type="range" min={100} max={8000} step={100} value={priceMax} onChange={e => setPriceMax(+e.target.value)}
          style={{ width: "100%", accentColor: "var(--primary)" }} />
      </FilterBlock>

      <FilterBlock title="Promociones">
        <Toggle checked={onlyDiscount} onChange={setOnlyDiscount} label="Solo productos en oferta" />
      </FilterBlock>

      <FilterBlock title="Marca">
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {all.map(b => (
            <Toggle key={b} checked={brands.has(b)} onChange={v => {
              const next = new Set(brands);
              v ? next.add(b) : next.delete(b);
              setBrands(next);
            }} label={b} />
          ))}
        </div>
      </FilterBlock>

      <FilterBlock title="Calificación">
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[4, 3, 2].map(r => (
            <a key={r} style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-muted)", font: "500 13px var(--font-sans)", cursor: "pointer" }}>
              <RatingStars value={r} size={14} /> y más
            </a>
          ))}
        </div>
      </FilterBlock>
    </Wrapper>
  );
};

const Chip = ({ selected, onClick, children }) => (
  <button onClick={onClick}
    style={{
      flexShrink: 0,
      padding: "10px 18px", borderRadius: "9999px",
      background: selected ? "var(--hub-black)" : "var(--bg-elev-1)",
      color: selected ? "#fff" : "var(--fg-strong)",
      border: selected ? "1px solid var(--hub-black)" : "1px solid var(--border)",
      font: selected ? "600 13px var(--font-sans)" : "500 13px var(--font-sans)",
      cursor: "pointer", transition: "all var(--dur-fast)",
    }}>
    {children}
  </button>
);

const FilterBlock = ({ title, children }) => (
  <div style={{ marginBottom: 22, paddingBottom: 22, borderBottom: "1px solid var(--border-soft)" }}>
    <h4 style={{ font: "700 13px var(--font-sans)", color: "var(--fg-strong)", margin: "0 0 12px", textTransform: "uppercase", letterSpacing: ".06em" }}>{title}</h4>
    {children}
  </div>
);

const Toggle = ({ checked, onChange, label }) => (
  <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", font: "500 13px var(--font-sans)", color: "var(--fg-strong)" }}>
    <span style={{
      width: 18, height: 18, borderRadius: 4,
      background: checked ? "var(--primary)" : "transparent",
      border: checked ? "1.5px solid var(--primary)" : "1.5px solid var(--border-input)",
      display: "grid", placeItems: "center", transition: "all var(--dur-fast)", flexShrink: 0,
    }}>
      {checked && <AllenIcon name="check" size={14} color="#fff" weight={700} />}
    </span>
    <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} style={{ display: "none" }} />
    {label}
  </label>
);

window.PLP = PLP;
