"use client";

import { Children, useState, type ReactNode } from "react";
import { cn } from "cn";
import { categories, type Category } from "@/content/catalog";

type FilterGridProps = {
  /** Label of the first chip ("All Projects"). */
  allLabel: string;
  /** Chip label per category. */
  labels: Record<Category, string>;
  /** Accessible name of the chip group. */
  filterLabel: string;
  /** Categories of each child, in the same order as `children`. */
  itemCategories: Category[][];
  /** Classes for the <ul> grid. */
  listClassName?: string;
  /** Classes for every <li>. */
  itemClassName?: string;
  /** One card per item (rendered on the server and passed in). */
  children: ReactNode;
};

/**
 * Filter chips + the cards they filter (Projects / Products pages).
 * Figma: chips 12px apart, the grid 48px under them; the selected chip is filled purple, the others outlined.
 */
export function FilterGrid({ allLabel, labels, filterLabel, itemCategories, listClassName, itemClassName, children }: FilterGridProps) {
  const [selected, setSelected] = useState<Category | "all">("all");
  const items = Children.toArray(children);
  const options: { value: Category | "all"; label: string }[] = [
    { value: "all", label: allLabel },
    ...categories.map((c) => ({ value: c, label: labels[c] })),
  ];

  return (
    <div className="flex flex-col gap-12">
      <div role="group" aria-label={filterLabel} className="flex flex-wrap gap-3">
        {options.map(({ value, label }) => (
          <button
            key={value}
            type="button"
            aria-pressed={selected === value}
            onClick={() => setSelected(value)}
            className={cn(
              "rounded-full border px-3 py-2 text-sm leading-4 font-semibold transition outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
              selected === value ? "border-brand-deep bg-brand-deep text-default" : "border-soft text-soft hover:bg-white/10",
            )}
          >
            {label}
          </button>
        ))}
      </div>

      <ul className={listClassName}>
        {items.map((item, i) =>
          selected === "all" || itemCategories[i]?.includes(selected) ? (
            <li key={i} className={itemClassName}>
              {item}
            </li>
          ) : null,
        )}
      </ul>
    </div>
  );
}
