# Calendar

## Introduction

Calendar is a low-level UI component that renders an interactive calendar grid for date selection. It provides the visual foundation for higher-level picker components like DatePicker, DateRangePicker, and MonthPicker. While you will rarely use Calendar directly in forms, it is useful for building custom date selection interfaces or embedded calendar views where you need full control over the calendar behavior.

Calendar accepts `Date` objects (not strings) and uses an array-based value format `[startDate, endDate]` to support both single-date and range selection modes. It supports multiple locales, view modes (day and month), and flexible date restriction options.

> **Note**: Calendar is a **building block component** intended for custom implementations.
>
> - For standard date input, use `DatePicker` instead.
> - For date ranges, use `DateRangePicker` instead.
> - For month selection, use `MonthPicker` or `MonthRangePicker`.

```tsx
<Calendar />
```

| Field  | Description | Default |
| ------ | ----------- | ------- |
| locale | —           | —       |

## Usage

```tsx
import { Calendar } from '@ceed/cds';
import { useState } from 'react';

function DateSelector() {
  const [date, setDate] = useState<Date | null>(null);

  return <Calendar value={date ? [date, undefined] : undefined} onChange={(dates) => setDate(dates[0] || null)} />;
}
```

## Controlled

In controlled mode, the parent component manages the calendar's selected date via the `value` and `onChange` props. This is the recommended approach for most use cases.

```tsx
<Calendar />
```

## Uncontrolled

In uncontrolled mode, Calendar manages its own internal state. Use this when you do not need to programmatically read or set the selected date.

```tsx
<Calendar />
```

## Locale Support

Display month names, day abbreviations, and first-day-of-week according to a specific locale using the `locale` prop.

```tsx
<Calendar locale="de" />
```

## Range Selection

Enable `rangeSelection` to allow users to pick a start and end date. The first click sets the start date and the second click sets the end date. Dates between the two are visually highlighted.

```tsx
<Calendar rangeSelection />
```

## Default Value with Range Selection

Pre-populate a date range when the calendar initially renders by providing a `defaultValue` array alongside `rangeSelection`.

```tsx
<Calendar rangeSelection defaultValue={[new Date(2024, 2, 1), new Date(2024, 2, 20)]} />
```

## View Modes

### Month View Only

Show only the month grid for month-level navigation and selection.

```tsx
<Calendar
  views={['month']}
  defaultValue={[new Date(2024, 2, 1), undefined]}
/>
```

### All Views

Enable both month and day views with navigation between them, giving users the flexibility to zoom in and out of the calendar.

```tsx
<Calendar
    views={["month", "day"]}
    rangeSelection
    defaultValue={[new Date(2024, 2, 1), new Date(2024, 2, 20)]}
  />
```

### Month Selection

Use the calendar exclusively for selecting a month. Combine `view="month"` with the `onMonthChange` callback to capture month-level changes.

```tsx
<Calendar view="month" value={[value, undefined]} onMonthChange={setValue} />
```

## Date Restrictions

### Minimum Date

Restrict selection to dates on or after a specified minimum date using the `minDate` prop.

```tsx
<Calendar minDate={new Date('2024-02-15')} rangeSelection />
```

### Maximum Date

Restrict selection to dates on or before a specified maximum date using the `maxDate` prop.

```tsx
<Calendar maxDate={new Date('2024-02-15')} rangeSelection />
```

### Disable Future Dates

Prevent selection of any date after today with the `disableFuture` prop.

```tsx
<Calendar disableFuture rangeSelection />
```

### Disable Past Dates

Prevent selection of any date before today with the `disablePast` prop.

```tsx
<Calendar disablePast rangeSelection />
```

### Custom Date Disabling

Use the `shouldDisableDate` callback to implement arbitrary disabling logic, such as blocking weekends.

```tsx
<Calendar shouldDisableDate={date => [0, 6].includes(date.getDay())} />
```

### Weekends and Past Dates Disabled

Combine `shouldDisableDate` with `disablePast` to apply multiple restrictions simultaneously.

```tsx
<Calendar shouldDisableDate={(date) => [0, 6].includes(date.getDay())} disablePast />
```

### Complex Date Restrictions

Disable weekends, past dates, and limit selection to one week ahead by combining all restriction options.

```tsx
<Calendar
    shouldDisableDate={(date) =>
      [0, 6].includes(date.getDay()) ||
      date.getTime() >= new Date().getTime() + 7 * 24 * 60 * 60 * 1000
    }
    disablePast
  />
```

## Common Use Cases

### Embedded Calendar Widget

```tsx
import { Calendar } from '@ceed/cds';
import { Box, Typography } from '@ceed/cds';

function CalendarWidget() {
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());

  return (
    <Box sx={{ p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 'md' }}>
      <Typography level="title-md" sx={{ mb: 2 }}>
        Select a Date
      </Typography>
      <Calendar value={[selectedDate, undefined]} onChange={(dates) => dates[0] && setSelectedDate(dates[0])} />
      <Typography level="body-sm" sx={{ mt: 2 }}>
        Selected: {selectedDate.toLocaleDateString()}
      </Typography>
    </Box>
  );
}
```

### Booking Calendar with Disabled Dates

```tsx
function BookingCalendar({ blockedDates }) {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  const blockedSet = useMemo(() => new Set(blockedDates.map((d) => d.toDateString())), [blockedDates]);

  return (
    <Calendar
      value={selectedDate ? [selectedDate, undefined] : undefined}
      onChange={(dates) => setSelectedDate(dates[0] || null)}
      disablePast
      shouldDisableDate={(date) => [0, 6].includes(date.getDay()) || blockedSet.has(date.toDateString())}
    />
  );
}
```

### Date Range Selector with Summary

```tsx
function DateRangeSelector({ onRangeSelect }) {
  const [range, setRange] = useState<[Date | undefined, Date | undefined]>([undefined, undefined]);

  const dayCount = useMemo(() => {
    if (!range[0] || !range[1]) return 0;
    const diff = range[1].getTime() - range[0].getTime();
    return Math.ceil(diff / (1000 * 60 * 60 * 24)) + 1;
  }, [range]);

  return (
    <Stack gap={2}>
      <Calendar
        rangeSelection
        value={range}
        onChange={(dates) => {
          setRange(dates);
          if (dates[0] && dates[1]) onRangeSelect(dates);
        }}
        disablePast
      />
      {range[0] && range[1] && (
        <Typography level="body-sm">
          {range[0].toLocaleDateString()} - {range[1].toLocaleDateString()} ({dayCount} days)
        </Typography>
      )}
    </Stack>
  );
}
```

## Best Practices

1. **Prefer higher-level picker components for form fields.** Use DatePicker or DateRangePicker unless you need a custom embedded calendar UI.

```tsx
// ✅ Use DatePicker for standard form input
<DatePicker label="Birth Date" value={date} onChange={handleChange} />

// ❌ Using Calendar directly in a form without context
<form>
  <Calendar onChange={handleChange} />
</form>
```

2. **Handle the array value format correctly.** Calendar always uses `[start, end]` format, even for single date selection.

```tsx
// ✅ Proper single-date handling
<Calendar
  value={date ? [date, undefined] : undefined}
  onChange={(dates) => setDate(dates[0] || null)}
/>

// ❌ Treating value as a single Date
<Calendar value={date} onChange={(d) => setDate(d)} />
```

3. **Memoize `shouldDisableDate` for performance.** Complex date validation logic runs on every date cell render, so use `useCallback` or `useMemo` to prevent unnecessary recalculations.

```tsx
// ✅ Memoized disable function
const shouldDisableDate = useCallback(
  (date: Date) => {
    return [0, 6].includes(date.getDay()) || holidays.has(date.toDateString());
  },
  [holidays],
);

// ❌ Inline function recreated every render
<Calendar shouldDisableDate={(date) => expensiveCheck(date)} />;
```

4. **Always use Date objects, not strings.** Calendar expects native `Date` objects for `value`, `defaultValue`, `minDate`, and `maxDate`.

```tsx
// ✅ Using Date objects
<Calendar value={[new Date('2024-04-15'), undefined]} />

// ❌ Using string values
<Calendar value={['2024-04-15', undefined]} />
```

5. **Provide surrounding context when using Calendar directly.** Add a heading or label to explain the calendar's purpose, since Calendar itself has no built-in label.

## Props and Customization

### Key Props

| Prop                | Type                                         | Default            | Description                                                            |
| ------------------- | -------------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
| `value`             | `[Date, Date \| undefined]`                  | -                  | Selected date(s) for controlled mode. Single date: `[date, undefined]` |
| `defaultValue`      | `[Date, Date \| undefined]`                  | -                  | Initial date(s) for uncontrolled mode                                  |
| `onChange`          | `(date: [Date, Date \| undefined]) => void`  | -                  | Callback when date selection changes                                   |
| `view`              | `'month' \| 'day'`                           | `'day'`            | Active calendar view                                                   |
| `views`             | `('month' \| 'day')[]`                       | `['month', 'day']` | Available views for navigation                                         |
| `onViewChange`      | `(view: 'month' \| 'day') => void`           | -                  | Callback when view changes                                             |
| `onMonthChange`     | `(newMonth: Date) => void`                   | -                  | Callback when the displayed month changes                              |
| `rangeSelection`    | `boolean`                                    | `false`            | Enable date range selection (two dates)                                |
| `locale`            | `string`                                     | `'default'`        | Locale for month/day names (BCP 47 format)                             |
| `minDate`           | `Date`                                       | -                  | Minimum selectable date                                                |
| `maxDate`           | `Date`                                       | -                  | Maximum selectable date                                                |
| `disableFuture`     | `boolean`                                    | `false`            | Disable all future dates                                               |
| `disablePast`       | `boolean`                                    | `false`            | Disable all past dates                                                 |
| `shouldDisableDate` | `(date: Date) => boolean`                    | -                  | Custom function to disable specific dates                              |
| `slots`             | `Partial<Record<CalendarSlot, ElementType>>` | -                  | Not implemented. The prop is accepted but no slot is overridable yet   |

## Accessibility

- **Keyboard navigation**: Arrow keys navigate between days, Page Up/Down switches months, Home/End jumps to start/end of the week, and Enter/Space selects the focused date.
- **ARIA attributes**: Days are announced with full date context. Selected dates use `aria-selected` and disabled dates are marked with `aria-disabled`.
- **Focus management**: Focus remains within the calendar during navigation. Disabled dates are skipped during keyboard traversal.
- **Screen reader support**: Month navigation buttons include descriptive labels (e.g., "Previous Month", "Next Month"), and each day cell is announced with its full date.
