"use client";

import type { UseFormRegisterReturn } from "react-hook-form";
import { FieldErrorIcon } from "./Field";

export interface RadioOption {
  value: string;
  label: string;
}

export interface RadioGroupProps {
  /** Base id. The first option gets `${id}-0`, which is what the error summary links to. */
  id: string;
  legend: string;
  options: RadioOption[];
  /** Spread from React Hook Form's `register(name)` — keeps the group uncontrolled. */
  registration: UseFormRegisterReturn;
  required?: boolean;
  error?: string;
  hint?: string;
}

/**
 * Radio group in a `<fieldset>`/`<legend>`, which is what makes the group's
 * question part of each option's accessible name.
 *
 * Deliberately uncontrolled: the native inputs stay the source of truth and
 * the selected pill is drawn with `:has(input:checked)` in CSS, so choosing an
 * option re-renders nothing. That matters here — this sits inside a field array
 * that can hold up to nine passengers.
 */
export default function RadioGroup({
  id,
  legend,
  options,
  registration,
  required,
  error,
  hint,
}: RadioGroupProps) {
  const describedBy = [hint ? `${id}-hint` : null, error ? `${id}-error` : null]
    .filter(Boolean)
    .join(" ");

  return (
    <fieldset
      className={`lf-radiogroup ${error ? "lf-radiogroup--invalid" : ""}`}
      aria-describedby={describedBy || undefined}
      aria-invalid={error ? true : undefined}
      aria-required={required ? true : undefined}
    >
      <legend className="lf-label">
        {legend}
        {required ? (
          <span className="lf-required" aria-hidden="true">
            *
          </span>
        ) : null}
      </legend>

      <div className="lf-radio-row">
        {options.map((option, index) => (
          <label className="lf-radio" key={option.value}>
            <input
              type="radio"
              id={`${id}-${index}`}
              value={option.value}
              {...registration}
            />
            <span className="lf-radio-dot" aria-hidden="true" />
            <span>{option.label}</span>
          </label>
        ))}
      </div>

      {hint ? (
        <p className="lf-hint" id={`${id}-hint`} style={{ marginTop: 6 }}>
          {hint}
        </p>
      ) : null}

      {error ? (
        <p className="lf-error" id={`${id}-error`} style={{ marginTop: 6 }}>
          <FieldErrorIcon />
          <span>{error}</span>
        </p>
      ) : null}
    </fieldset>
  );
}
