// plp.jsx — plp.html (browse / product listing page)

function buildFacets(items) {
  const count = (field) => {
    const c = {};
    items.forEach((i) => {
      const vals = field === "bestFor" ? i[field] : [i[field]];
      vals.forEach((v) => { c[v] = (c[v] || 0) + 1; });
    });
    return c;
  };
  const toOptions = (c) => Object.keys(c).map((value) => ({ value, count: c[value] })).sort((a, b) => b.count - a.count);
  return [
    { id: "category", label: "Category", options: toOptions(count("category")).map((o) => ({ ...o, value: CATEGORIES.find((c) => c.id === o.value)?.label || o.value, key: o.value })) },
    { id: "mode", label: "Mode", options: toOptions(count("mode")).map((o) => ({ ...o, value: MODES[o.value]?.label || o.value, key: o.value })) },
    { id: "bestFor", label: "Best for", options: toOptions(count("bestFor")).map((o) => ({ ...o, key: o.value })) },
  ];
}

function readQuery() {
  const p = new URLSearchParams(location.search);
  const out = { category: [], mode: [], bestFor: [] };
  if (p.get("category")) out.category = [p.get("category")];
  if (p.get("bestFor")) out.bestFor = [p.get("bestFor")];
  return out;
}

function matchItem(item, applied) {
  if (applied.category.length && !applied.category.includes(item.category)) return false;
  if (applied.mode.length && !applied.mode.includes(item.mode)) return false;
  if (applied.bestFor.length && !applied.bestFor.some((t) => item.bestFor.includes(t))) return false;
  return true;
}

function sortItems(items, sort) {
  const arr = [...items];
  if (sort === "price-asc") arr.sort((a, b) => (a.price ?? 9e9) - (b.price ?? 9e9));
  if (sort === "price-desc") arr.sort((a, b) => (b.price ?? -1) - (a.price ?? -1));
  if (sort === "rated") arr.sort((a, b) => b.provider.reputationScore - a.provider.reputationScore);
  return arr;
}

function PlpPage() {
  const [applied, setApplied] = React.useState(() => readQuery());
  const [sort, setSort] = React.useState("featured");

  const toggle = (facetKey, optKey) => {
    setApplied((f) => {
      const map = { category: f.category, mode: f.mode, bestFor: f.bestFor };
      const set = new Set(map[facetKey] || []);
      set.has(optKey) ? set.delete(optKey) : set.add(optKey);
      return { ...f, [facetKey]: [...set] };
    });
  };
  const clearAll = () => setApplied({ category: [], mode: [], bestFor: [] });

  const matched = CATALOG.filter((i) => matchItem(i, applied));
  const sorted = sortItems(matched, sort);

  return (
    <>
      <Section id="plp-hd" className="plp-hd-sec">
        <span className="topic label-overline">Catalog</span>
        <h1 className="h1">Shop the catalog.</h1>
        <FinderPanel defaultOpen={false} />
      </Section>

      <Section id="plp-body">
        <div className="plp-layout">
          <FilterPanel
            facets={buildFacets(CATALOG)}
            applied={{
              category: applied.category.map((id) => CATEGORIES.find((c) => c.id === id)?.label || id),
              mode: applied.mode.map((id) => MODES[id]?.label || id),
              bestFor: applied.bestFor,
            }}
            onToggle={(facetId, displayValue) => {
              if (facetId === "category") {
                const cat = CATEGORIES.find((c) => c.label === displayValue);
                toggle("category", cat ? cat.id : displayValue);
              } else if (facetId === "mode") {
                const m = Object.keys(MODES).find((k) => MODES[k].label === displayValue);
                toggle("mode", m || displayValue);
              } else {
                toggle("bestFor", displayValue);
              }
            }}
            onClearAll={clearAll}
          />
          <div>
            <div className="plp-toolbar">
              <span className="result-count body-sm">{sorted.length} result{sorted.length === 1 ? "" : "s"}</span>
              <select className="sort-select" value={sort} onChange={(e) => setSort(e.target.value)} aria-label="Sort">
                <option value="featured">Sort: Featured</option>
                <option value="price-asc">Price: low to high</option>
                <option value="price-desc">Price: high to low</option>
                <option value="rated">Top rated</option>
              </select>
            </div>
            {sorted.length === 0 ? (
              <EmptyState
                title="Nothing matches those filters."
                message="Clear a filter or two — the catalog has 14 listings across six categories."
                actionLabel="Clear all filters"
                actionHref="plp.html"
              />
            ) : (
              <div className="product-grid">
                {sorted.map((item) => <ProductCard key={item.id} item={item} />)}
              </div>
            )}
          </div>
        </div>
      </Section>
    </>
  );
}

window.__PAGE__ = PlpPage;
