"use client";

import type { ProductVariant } from "@/data/types";
import { colorToHex } from "@/lib/color-swatch";
import { cn } from "@/lib/cn";

type Props = {
  variants: ProductVariant[];
  selected: Record<string, string>;
  onChange: (variantId: string, option: string) => void;
};

/** Compact color dots and size squares. */
export function VariantSelector({ variants, selected, onChange }: Props) {
  return (
    <div className="space-y-6">
      {variants.map((variant) => {
        const isColor = variant.id === "color";
        return (
          <div key={variant.id}>
            <p className="mb-2 text-sm font-medium">
              {variant.label}:{" "}
              <span className="font-normal text-muted">
                {selected[variant.id]}
              </span>
            </p>
            <div className="flex flex-wrap gap-2">
              {variant.options.map((option) => {
                const active = selected[variant.id] === option;
                if (isColor) {
                  const hex = colorToHex(option) ?? "#d4d4d4";
                  return (
                    <button
                      key={option}
                      type="button"
                      aria-label={option}
                      onClick={() => onChange(variant.id, option)}
                      className={cn(
                        "h-8 w-8 rounded-full border",
                        active ? "ring-1 ring-foreground ring-offset-2" : "border-black/20",
                      )}
                      style={{ backgroundColor: hex }}
                    />
                  );
                }
                return (
                  <button
                    key={option}
                    type="button"
                    onClick={() => onChange(variant.id, option)}
                    className={cn(
                      "min-w-11 border px-3 py-2 text-sm transition",
                      active
                        ? "border-foreground bg-foreground text-background"
                        : "border-border hover:border-foreground",
                    )}
                  >
                    {option}
                  </button>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}
