"use client";

import * as React from "react";
import { Label } from "@/components/ui/label";
import type { FacetDef } from "@/lib/search/types";

type Props = {
  facet: FacetDef;
  /** Aktueller URL-Wert als CSV der gewählten `wert`-Codes. */
  value: string | undefined;
  onChange: (value: string | null) => void;
};

/**
 * Enum-Facette als Multi-Select (Checkbox-Liste). Schreibt die gewählten Codes
 * als CSV in die URL; leere Auswahl entfernt den Filter.
 */
export function EnumFacet({ facet, value, onChange }: Props) {
  const optionen = facet.optionen ?? [];
  const selected = React.useMemo(
    () => new Set((value ?? "").split(",").map((s) => s.trim()).filter(Boolean)),
    [value],
  );

  if (optionen.length === 0) return null;

  const toggle = (wert: string) => {
    const next = new Set(selected);
    if (next.has(wert)) next.delete(wert);
    else next.add(wert);
    const csv = [...next].join(",");
    onChange(csv === "" ? null : csv);
  };

  return (
    <fieldset className="flex flex-col gap-1.5">
      <Label className="text-sm font-medium text-anthrazit">{facet.name}</Label>
      <div className="flex flex-col gap-1">
        {optionen.map((opt) => (
          <label
            key={opt.wert}
            className="flex items-center gap-2 text-sm text-anthrazit/90"
          >
            <input
              type="checkbox"
              className="h-4 w-4 rounded border-rand text-navy focus:ring-navy"
              checked={selected.has(opt.wert)}
              onChange={() => toggle(opt.wert)}
            />
            {opt.label}
          </label>
        ))}
      </div>
    </fieldset>
  );
}
