"use client";

import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { cn } from "@/lib/utils";

export interface RadioOption {
  value: string;
  label: React.ReactNode;
}

export interface RadioGroupProps
  extends React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root> {
  options: RadioOption[];
  legend: string;
}

/** Accessible radio group — announces as a fieldset/legend for screen readers. */
export function RadioGroup({ options, legend, className, ...props }: RadioGroupProps) {
  return (
    <fieldset className="flex flex-col gap-2.5">
      <legend className="text-label mb-1 font-medium uppercase text-ink-soft">{legend}</legend>
      <RadioGroupPrimitive.Root className={cn("flex flex-col gap-2.5", className)} {...props}>
        {options.map((opt) => {
          const id = `radio-${opt.value}`;
          return (
            <div key={opt.value} className="flex items-center gap-2.5">
              <RadioGroupPrimitive.Item
                id={id}
                value={opt.value}
                className={cn(
                  "flex size-5 shrink-0 items-center justify-center rounded-full border border-line bg-paper",
                  "transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",
                  "data-[state=checked]:border-primary"
                )}
              >
                <RadioGroupPrimitive.Indicator className="size-2.5 rounded-full bg-primary" />
              </RadioGroupPrimitive.Item>
              <label htmlFor={id} className="text-body-sm text-ink-soft">
                {opt.label}
              </label>
            </div>
          );
        })}
      </RadioGroupPrimitive.Root>
    </fieldset>
  );
}
