# RadioTileGroup

## Introduction

RadioTileGroup is a selection component that displays radio options as visually distinct tiles. Unlike a standard radio button list, each option occupies a tile card, making selections more prominent and scannable. This is especially useful for choices that benefit from visual emphasis, such as plan selection, category picking, or preference surveys.

The component supports flexible layouts (horizontal, grid, vertical), icons via `startDecorator`, three sizes, and built-in form integration with `label`, `helperText`, `error`, and `required` props. It works in both controlled and uncontrolled modes.

> **Using built-in props is recommended when building forms**
>
> This component provides built-in form-related props such as `label` and `helperText`.
> When building a form, use the component's built-in props instead of creating separate labels or helper text with Typography.

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
/>
```

| Field        | Description | Default       |
| ------------ | ----------- | ------------- |
| options      | —           | simpleOptions |
| value        | —           | —             |
| defaultValue | —           | —             |
| onChange     | —           | —             |
| name         | —           | —             |
| disabled     | —           | —             |
| className    | —           | —             |
| useIndicator | —           | —             |
| textAlign    | —           | —             |
| size         | —           | —             |
| flex         | —           | —             |
| columns      | —           | —             |
| label        | —           | —             |
| helperText   | —           | —             |
| error        | —           | —             |
| required     | —           | —             |

## Usage

```tsx
import { RadioTileGroup } from '@ceed/cds';

function MyComponent() {
  const [value, setValue] = useState('');

  const options = [
    { value: 'option1', label: 'Option 1' },
    { value: 'option2', label: 'Option 2' },
    { value: 'option3', label: 'Option 3' },
  ];

  return (
    <RadioTileGroup
      label="Choose an option"
      helperText="Select one of the options below"
      options={options}
      value={value}
      onChange={(e) => setValue(e.target.value)}
      useIndicator
    />
  );
}
```

## Label and Helper Text

Use the `label` and `helperText` props to add descriptive text above and below the tile group. The `required` prop appends a required indicator to the label.

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
  label="Select an option"
  helperText="This is helper text for the RadioTileGroup"
/>
```

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
  label="Select an option"
  helperText="This field is required"
  required
/>
```

## Layout Options

### Flex

Enable the `flex` prop to make tiles stretch and fill all available horizontal space equally.

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
  flex
/>
```

### Columns

Use the `columns` prop to arrange tiles in a specific number of columns using a grid layout.

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
  columns={2}
/>
```

### Flex with Columns

Combine `flex` and `columns` to create a grid where each tile stretches to fill its column width evenly.

```tsx
<Box
    sx={{
      width: "100%",
      maxWidth: 700
    }}
  >
    <Typography
      level="body-md"
      sx={{
        mb: 2
      }}
    >
      Flex with Columns
    </Typography>
    <RadioTileGroup
      options={optionsWithIcons}
      onChange={handleChange}
      value={selectedValue}
      flex={true}
      columns={3}
      size="md"
      useIndicator={true}
      label="Flex with Columns Example"
      helperText="Items stretch to fill available space and are arranged in 3 columns"
    />
  </Box>
```

### Vertical Layout

Set `columns={1}` to stack tiles vertically. This layout is well-suited for list-style selections like pricing plans or step-by-step options.

```tsx
<Box
    sx={{
      width: "100%",
      maxWidth: 400
    }}
  >
    <Typography
      level="body-md"
      sx={{
        mb: 2
      }}
    >
      Vertical Layout (columns: 1)
    </Typography>
    <RadioTileGroup
      options={pricingOptions}
      onChange={handleChange}
      value={selectedValue}
      columns={1}
      size="md"
      useIndicator={true}
      label="Subscription Plans"
      helperText="Select your preferred subscription plan"
    />
  </Box>
```

## Text Alignment

The `textAlign` prop controls the alignment of content inside each tile. The default is `center`. Set it to `start` for left-aligned content.

```tsx
<Box
    sx={{
      display: "flex",
      flexDirection: "column",
      gap: 4,
      width: "100%",
      maxWidth: 700
    }}
  >
    <Box>
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Center Alignment (default)
      </Typography>
      <RadioTileGroup options={simpleOptions} textAlign="center" useIndicator={true} />
    </Box>
    <Box>
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Start Alignment
      </Typography>
      <RadioTileGroup options={simpleOptions} textAlign="start" useIndicator={true} />
    </Box>
  </Box>
```

## Sizes

RadioTileGroup supports three sizes: `sm` (default), `md`, and `lg`. Choose the size that best fits the density of your layout.

```tsx
<Box
    sx={{
      display: "flex",
      flexDirection: "column",
      gap: 4,
      width: "100%",
      maxWidth: 700
    }}
  >
    <Box>
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Size: sm (default)
      </Typography>
      <RadioTileGroup options={simpleOptions} size="sm" useIndicator={true} />
    </Box>
    <Box>
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Size: md
      </Typography>
      <RadioTileGroup options={simpleOptions} size="md" useIndicator={true} />
    </Box>
    <Box>
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Size: lg
      </Typography>
      <RadioTileGroup options={simpleOptions} size="lg" useIndicator={true} />
    </Box>
  </Box>
```

## Icons

Add icons to tiles using the `startDecorator` property on each option. Icons help users visually distinguish between choices at a glance.

```tsx
<RadioTileGroup
  options={[{
  value: 'home',
  label: 'Home',
  startDecorator: <HomeIcon fontSize="large" />
}, {
  value: 'office',
  label: 'Office',
  startDecorator: <BusinessIcon fontSize="large" />
}, {
  value: 'shipping',
  label: 'Shipping',
  startDecorator: <LocalShippingIcon fontSize="large" />
}]}
  useIndicator
/>
```

## State Management

### Controlled

Pass `value` and `onChange` to fully control the selected state from the parent component. This is recommended when the selection participates in form state or triggers side effects.

```tsx
<Box
    sx={{
      width: "100%",
      maxWidth: 500
    }}
  >
    <Typography
      level="body-md"
      sx={{
        mb: 1
      }}
    >
      Selected value: {selectedValue}
    </Typography>
    <RadioTileGroup options={simpleOptions} value={selectedValue} onChange={handleChange} />
  </Box>
```

### Uncontrolled

Use `defaultValue` to set an initial selection without managing state externally. The component tracks its own selection internally.

```tsx
<Box
    sx={{
      display: "flex",
      flexDirection: "column",
      gap: 4
    }}
  >
    <Box
      sx={{
        width: "100%",
        maxWidth: 500
      }}
    >
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Uncontrolled Example (with Indicator)
      </Typography>
      <RadioTileGroup
        options={simpleOptions}
        defaultValue="option2"
        useIndicator={true}
        onChange={(event) => console.log(`Selected value: ${event.target.value}`)}
      />
    </Box>
    <Box
      sx={{
        width: "100%",
        maxWidth: 500
      }}
    >
      <Typography
        level="body-md"
        sx={{
          mb: 2
        }}
      >
        Uncontrolled Example (without Indicator)
      </Typography>
      <RadioTileGroup
        options={simpleOptions}
        defaultValue="option3"
        useIndicator={false}
        onChange={(event) => console.log(`Selected value: ${event.target.value}`)}
      />
    </Box>
  </Box>
```

## Disabled State

### Fully Disabled

Set the `disabled` prop on the group to disable all tiles.

```tsx
<RadioTileGroup
  options={simpleOptions}
  disabled
/>
```

### Individual Disabled

Set `disabled: true` on specific option objects to disable only those tiles while keeping the rest interactive.

```tsx
<RadioTileGroup
  options={[{
  value: 'option1',
  label: 'Option 1'
}, {
  value: 'option2',
  label: 'Option 2',
  disabled: true
}, {
  value: 'option3',
  label: 'Option 3'
}]}
/>
```

## Error State

Use the `error` prop to indicate validation errors. Pair it with `helperText` to communicate the issue to the user.

```tsx
<RadioTileGroup
  options={simpleOptions}
  useIndicator
  label="Select an option"
  helperText="Please select a valid option"
  error
/>
```

### Form Validation Example

Combine `required`, `error`, and `helperText` to build a complete form validation flow. The example below validates that the user has made a selection before submitting.

```tsx
<Stack
    spacing={2}
    sx={{
      width: "100%",
      maxWidth: 500
    }}
  >
    <RadioTileGroup
      options={simpleOptions}
      value={selectedValue}
      onChange={handleChange}
      label="Choose your preferred option"
      helperText={error ? "Please select an option" : "This selection is required"}
      error={error}
      useIndicator={true}
      required={true}
    />
    <Box
      sx={{
        display: "flex",
        justifyContent: "flex-end"
      }}
    >
      <Button onClick={handleSubmit}>Submit</Button>
    </Box>
  </Stack>
```

## Common Use Cases

### Shipping Method Selection

Display delivery options with icons so users can choose intuitively.

```tsx
import { RadioTileGroup } from '@ceed/cds';
import HomeIcon from '@mui/icons-material/Home';
import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import BusinessIcon from '@mui/icons-material/Business';

<RadioTileGroup
  label="Shipping Method"
  helperText="Delivery fees may vary by method."
  options={[
    { value: 'standard', label: 'Standard', startDecorator: <HomeIcon /> },
    { value: 'express', label: 'Express', startDecorator: <LocalShippingIcon /> },
    { value: 'business', label: 'Business', startDecorator: <BusinessIcon /> },
  ]}
  value={selected}
  onChange={(e) => setSelected(e.target.value)}
  size="md"
  useIndicator
/>;
```

```tsx
<Box
    sx={{
      width: "100%",
      maxWidth: 700
    }}
  >
    <RadioTileGroup
      label="배송 방법 선택"
      helperText="배송 방법에 따라 배송비가 달라질 수 있습니다."
      options={[
        {
          value: "standard",
          label: "일반 배송",
          startDecorator: <HomeIcon />
        },
        {
          value: "express",
          label: "빠른 배송",
          startDecorator: <LocalShippingIcon />
        },
        {
          value: "business",
          label: "기업 배송",
          startDecorator: <BusinessIcon />
        }
      ]}
      onChange={handleChange}
      value={selectedValue}
      size="md"
      useIndicator={true}
    />
  </Box>
```

### Survey / Preference Selection

Present survey options with icons in a multi-column grid for a clear, scannable layout.

```tsx
<RadioTileGroup
  label="What type of exercise do you prefer?"
  options={[
    { value: 'cardio', label: 'Cardio', startDecorator: <DirectionsRunIcon /> },
    { value: 'strength', label: 'Strength', startDecorator: <FitnessCenterIcon /> },
    { value: 'flexibility', label: 'Flexibility', startDecorator: <SelfImprovementIcon /> },
    { value: 'balance', label: 'Balance', startDecorator: <BalanceIcon /> },
  ]}
  columns={2}
  size="md"
  value={selected}
  onChange={(e) => setSelected(e.target.value)}
/>
```

```tsx
<Box
    sx={{
      width: "100%",
      maxWidth: 700
    }}
  >
    <RadioTileGroup
      label="선호하는 운동 유형을 선택해주세요"
      options={[
        {
          value: "cardio",
          label: "유산소 운동",
          startDecorator: <DirectionsRunIcon />
        },
        {
          value: "strength",
          label: "근력 운동",
          startDecorator: <FitnessCenterIcon />
        },
        {
          value: "flexibility",
          label: "유연성 운동",
          startDecorator: <SelfImprovementIcon />
        },
        {
          value: "balance",
          label: "균형 운동",
          startDecorator: <BalanceIcon />
        }
      ]}
      onChange={handleChange}
      value={selectedValue}
      columns={2}
      size="md"
    />
  </Box>
```

### Pricing Plan Picker

Use a vertical layout with `columns={1}` for plan or tier selection.

```tsx
<RadioTileGroup
  label="Subscription Plan"
  helperText="Select your preferred plan"
  options={[
    { value: 'basic', label: 'Basic Plan', startDecorator: <AttachMoneyIcon /> },
    { value: 'pro', label: 'Pro Plan', startDecorator: <AttachMoneyIcon /> },
    { value: 'premium', label: 'Premium Plan', startDecorator: <StarIcon /> },
  ]}
  columns={1}
  size="md"
  useIndicator
  value={selected}
  onChange={(e) => setSelected(e.target.value)}
/>
```

## Best Practices

1. **Use built-in form props instead of external labels.** The component's `label`, `helperText`, `required`, and `error` props ensure consistent layout and accessibility. Avoid wrapping with separate Typography elements.

```tsx
// ✅ Recommended
<RadioTileGroup label="Select option" helperText="Required field" required />

// ❌ Avoid
<Typography>Select option</Typography>
<RadioTileGroup options={options} />
<Typography color="danger">Required field</Typography>
```

2. **Choose the right layout for the number of options.** Use the default horizontal flow for 2-4 options. Use `columns` for 5+ options. Use `columns={1}` when each option has long labels or descriptions.

3. **Prefer controlled mode in forms.** When RadioTileGroup is part of a form with validation or submission logic, use `value` and `onChange` for predictable state management.

4. **Add icons only when they aid comprehension.** Icons via `startDecorator` are helpful for visually distinct categories (e.g., shipping methods). Avoid decorating every option if icons do not add meaning.

5. **Always provide an error message.** When `error` is true, update `helperText` to explain the validation issue so users know how to fix it.

## Props and Customization

### Key Props

| Prop           | Type                                             | Default    | Description                                |
| -------------- | ------------------------------------------------ | ---------- | ------------------------------------------ |
| `options`      | `RadioTileOption[]`                              | (required) | Array of radio tile options                |
| `value`        | `T`                                              | -          | Selected value (controlled mode)           |
| `defaultValue` | `T`                                              | -          | Initial selected value (uncontrolled mode) |
| `onChange`     | `(event: ChangeEvent<HTMLInputElement>) => void` | -          | Callback when selection changes            |
| `name`         | `string`                                         | -          | Groups radios together for form submission |
| `label`        | `ReactNode`                                      | -          | Group label displayed above the tiles      |
| `helperText`   | `ReactNode`                                      | -          | Helper text displayed below the tiles      |
| `error`        | `boolean`                                        | `false`    | Applies error styling                      |
| `required`     | `boolean`                                        | `false`    | Marks the field as required                |
| `disabled`     | `boolean`                                        | `false`    | Disables all radio tiles                   |
| `size`         | `'sm' \| 'md' \| 'lg'`                           | `'sm'`     | Tile size                                  |
| `flex`         | `boolean`                                        | `false`    | Tiles stretch to fill available width      |
| `columns`      | `number`                                         | -          | Fixed number of columns in grid layout     |
| `textAlign`    | `'start' \| 'center'`                            | `'center'` | Text alignment within tiles                |
| `useIndicator` | `boolean`                                        | `false`    | Shows a radio indicator on each tile       |
| `sx`           | `SxProps`                                        | -          | Custom styles using the MUI system         |

### RadioTileOption

```tsx
interface RadioTileOption<T = string> {
  value: T;
  label: ReactNode;
  disabled?: boolean;
  startDecorator?: ReactNode;
}
```

## Accessibility

- RadioTileGroup renders a `<fieldset>` with a `<legend>` derived from the `label` prop, providing proper grouping for screen readers.
- Each tile is backed by a native `<input type="radio">`, ensuring full keyboard navigation (arrow keys to move between options, Space/Enter to select).
- The `disabled` prop correctly applies `aria-disabled` semantics to prevent interaction while keeping elements discoverable by assistive technologies.
- When `error` is set, pair it with descriptive `helperText` so that screen readers can announce the validation message via `aria-describedby`.
