"use client";

import { useRouter } from "next/navigation";

import { hexForColor } from "@/lib/colors";
import { cn } from "@/lib/utils";
import { buildItemSearchUrl, type ItemSearchParams } from "@/lib/item-search-params";
import type { FacetCount } from "./types";

export function ColorFacet({ facets, params }: { facets: FacetCount[]; params: ItemSearchParams }) {
  const router = useRouter();

  function toggle(value: string) {
    const next = params.colors.includes(value)
      ? params.colors.filter((c) => c !== value)
      : [...params.colors, value];
    router.push(buildItemSearchUrl(params, { colors: next }));
  }

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold text-slate-900">Color</h3>
      <div className="flex flex-wrap gap-2">
        {facets.map((f) => {
          const selected = params.colors.includes(f.value);
          return (
            <button
              key={f.value}
              type="button"
              onClick={() => toggle(f.value)}
              title={`${f.value} (${f.count})`}
              className={cn(
                "h-8 w-8 rounded-sm border-2 transition-all",
                selected ? "border-forest-600 ring-2 ring-forest-200" : "border-slate-200 hover:border-slate-400",
              )}
              style={{ background: hexForColor(f.value) }}
              aria-label={`${f.value}, ${f.count} items`}
            />
          );
        })}
      </div>
    </div>
  );
}
