import React from 'react';

/**
 * Radio button with label; group by `name`.
 */
export interface RadioProps {
  label?: React.ReactNode;
  checked?: boolean;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  name?: string;
  value?: string;
  disabled?: boolean;
  style?: React.CSSProperties;
}

const CSS = `
.ct-radio { display: inline-flex; align-items: center; gap: 9px; cursor: pointer; font: var(--text-body); color: var(--ink-1); }
.ct-radio--disabled { opacity: 0.5; cursor: not-allowed; }
.ct-radio__input { position: absolute; opacity: 0; width: 0; height: 0; }
.ct-radio__dot {
  width: 16px; height: 16px; flex-shrink: 0;
  border: 1px solid var(--line-2);
  border-radius: 50%;
  background: var(--surface-card);
  display: inline-flex; align-items: center; justify-content: center;
  transition: border-color var(--duration-fast) var(--ease-out);
}
.ct-radio__dot::after {
  content: '';
  width: 8px; height: 8px; border-radius: 50%;
  background: transparent;
  transition: background var(--duration-fast) var(--ease-out);
}
.ct-radio:hover:not(.ct-radio--disabled) .ct-radio__dot { border-color: var(--border-strong); }
.ct-radio__input:checked + .ct-radio__dot { border-color: var(--accent); }
.ct-radio__input:checked + .ct-radio__dot::after { background: var(--accent); }
.ct-radio__input:focus-visible + .ct-radio__dot { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
`;
(function inject() {
  if (typeof document !== 'undefined' && !document.getElementById('ct-radio-css')) {
    const s = document.createElement('style'); s.id = 'ct-radio-css'; s.textContent = CSS;
    document.head.appendChild(s);
  }
})();

export function Radio({ label, checked, onChange, name, value, disabled = false, style, ...rest }: RadioProps) {
  return (
    <label className={`ct-radio${disabled ? ' ct-radio--disabled' : ''}`} style={style}>
      <input
        type="radio"
        className="ct-radio__input"
        checked={checked}
        onChange={onChange}
        name={name}
        value={value}
        disabled={disabled}
        {...rest}
      />
      <span className="ct-radio__dot"></span>
      {label ? <span>{label}</span> : null}
    </label>
  );
}
