"use client";

import { useRouter, useSearchParams } from "next/navigation";

// Category checkboxes (union — any checked category matches) plus a
// separate "Nur verfügbare Produkte" availability toggle, sharing one
// component since both are simple instant-apply checkboxes writing to the
// same /shop searchParams (no submit button, same as the price slider —
// see PriceRangeFilter.tsx). Categories are derived from the active
// product set by the caller (ProductGrid.tsx), same "distinct values from
// what's actually in use" pattern as the blog's category chips — an
// uncategorized product still matches every category filter (see
// Product.categories' own comment in lib/payload.ts), so this list never
// needs an "Alle" fallback entry.
export function CategoryFilter({ categories }: { categories: string[] }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const activeCategories = (searchParams.get("categories") ?? "").split(",").filter(Boolean);
  const inStockOnly = searchParams.get("inStock") === "1";

  function push(params: URLSearchParams) {
    const qs = params.toString();
    router.push(qs ? `/shop?${qs}` : "/shop");
  }

  function toggleCategory(category: string) {
    const next = activeCategories.includes(category)
      ? activeCategories.filter((c) => c !== category)
      : [...activeCategories, category];
    const params = new URLSearchParams(searchParams.toString());
    if (next.length > 0) params.set("categories", next.join(","));
    else params.delete("categories");
    push(params);
  }

  function toggleInStock() {
    const params = new URLSearchParams(searchParams.toString());
    if (inStockOnly) params.delete("inStock");
    else params.set("inStock", "1");
    push(params);
  }

  return (
    <div className="flex flex-col gap-2 w-full">
      {categories.length > 1 && (
        <div className="flex flex-col gap-2 w-full">
          <p className="font-bold text-body-sm text-text-primary">Kategorie</p>
          {categories.map((category) => (
            <label key={category} className="flex items-center gap-2 text-body-sm text-text-primary cursor-pointer">
              <input
                type="checkbox"
                checked={activeCategories.includes(category)}
                onChange={() => toggleCategory(category)}
                className="h-4 w-4 rounded-sm border-border accent-brand cursor-pointer"
              />
              {category}
            </label>
          ))}
        </div>
      )}
      <label className="flex items-center gap-2 text-body-sm text-text-primary cursor-pointer">
        <input
          type="checkbox"
          checked={inStockOnly}
          onChange={toggleInStock}
          className="h-4 w-4 rounded-sm border-border accent-brand cursor-pointer"
        />
        Nur verfügbare Produkte
      </label>
    </div>
  );
}
