'use client'
import type { ReactNode } from 'react'
import type { QuestionOption } from '@/lib/types'

interface RadioGroupProps {
  name: string
  legend: ReactNode
  options: QuestionOption[]
  value: string | undefined
  required: boolean
  onChange: (value: string) => void
  error?: string
}

export function RadioGroup({
  name,
  legend,
  options,
  value,
  required,
  onChange,
  error,
}: RadioGroupProps) {
  return (
    <fieldset className="question-fieldset">
      <legend className="question-legend">
        {legend}
        {required && <span className="required-mark" aria-hidden="true"> *</span>}
        {required && <span className="sr-only"> (obligatorio)</span>}
      </legend>
      <div className="options-list" role="list">
        {options.map((opt) => {
          const id = `${name}_${opt.value.replace(/\s+/g, '_')}`
          return (
            <div key={opt.value} className="option-item" role="listitem">
              <label className="option-label" htmlFor={id}>
                <input
                  type="radio"
                  id={id}
                  name={name}
                  value={opt.value}
                  checked={value === opt.value}
                  onChange={() => onChange(opt.value)}
                  aria-required={required}
                  className="option-input"
                />
                <span className="option-text">{opt.label}</span>
              </label>
            </div>
          )
        })}
      </div>
      {error && (
        <p role="alert" className="field-error" id={`${name}-error`}>
          {error}
        </p>
      )}
    </fieldset>
  )
}
