# Calendar
A month grid for picking a day, several days or a range.
Source page: https://dinachi.dev/docs/components/calendar

## Installation
```bash
npx @dinachi/cli@latest add calendar
```
Adds to your project:
- `components/ui/calendar/calendar.tsx`
- `components/ui/calendar/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `date-fns` ^4.4.0
- `lucide-react` ^0.552.0
- `react-day-picker` ^9.14.0

## Usage
```tsx
import { useState } from "react"
import { Calendar } from "@/components/ui/calendar"

export function DueDate() {
  const [day, setDay] = useState<Date | null>(null)
  return <Calendar aria-label="Due date" value={day} onValueChange={setDay} />
}
```

## Examples

### Default
One day, months scrolling as a column.
```tsx
import { useState } from 'react';
import { Calendar, toISODate } from '@/components/ui/calendar';

export function Example() {
  const [day, setDay] = useState<Date | null>(null);
  return (
    <div className="grid justify-items-center gap-3">
      <Calendar aria-label="Due date" value={day} onValueChange={setDay} className="rounded-lg border" />
      <p className="text-sm text-muted-foreground">{day ? toISODate(day) : "No day picked"}</p>
    </div>
  );
}
```

### Range, paged
Two months side by side, from today on.
```tsx
import { useState } from 'react';
import { Calendar, type DateRange } from '@/components/ui/calendar';

export function Example() {
  const [range, setRange] = useState<DateRange>({ from: null, to: null });
  return (
    <Calendar
      mode="range"
      layout="paged"
      numberOfMonths={2}
      aria-label="Stay"
      value={range}
      onValueChange={setRange}
      min={new Date()}
      className="rounded-lg border p-3"
    />
  );
}
```

### Several days
Weekdays only, with week numbers.
```tsx
import { Calendar } from '@/components/ui/calendar';

export function Example() {
  return (
    <Calendar
      mode="multiple"
      aria-label="Rota days"
      weekNumbers
      isDateDisabled={(d) => d.getDay() === 0 || d.getDay() === 6}
      className="rounded-lg border"
    />
  );
}
```

## Notes

### What a day is
A day is a `Date` at local midnight, so it names the same calendar day wherever it is read. Nothing converts time zones. Forms receive `YYYY-MM-DD`, and `toISODate` gives you the same string.

### Scrolling months
The scroll layout renders a window of months around the value and adds more as you near either end, stopping at `min` and `max`. The Today button appears once today has scrolled out of view. Use `layout="paged"` to embed the calendar where a scroll area doesn't fit.

### Ranges and blocked days
A range can't run across a day that can't be picked. The preview stops short of one, and pressing past it starts a new range with the reason `range-blocked`, which you can cancel or explain. A value set from outside that breaks the rule marks the calendar `data-invalid` and paints the blocked days inside the band.

### Date helpers
`calendar.tsx` also exports the helpers the date components share: `parseDate` reads what people type (today, next fri, in 2 weeks, 21 nov, 3/12, read in the order the page's language writes dates; a two-digit year lands inside `min` and `max`, else up to twenty years ahead), plus `toISODate`, `fromISODate`, `isSameDay`, `addDays`, `daysBetween` and `isoWeek`.

## API reference
Props marked **agent** change what an agent reads or may do.

### Calendar
The weekday header, the months and the Today button.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `"single" \| "multiple" \| "range"` | `"single"` | One day, a set of days, or a from and to. |
| `value` **agent** | `Date \| null \| Date[] \| DateRange` | - | Controlled value. Its type follows `mode`. |
| `defaultValue` | `Date \| null \| Date[] \| DateRange` | - | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs on every pick, for people and agents. `details.cancel()` refuses the change. |
| `layout` | `"scroll" \| "paged"` | `"scroll"` | Scroll months as a column, or page them with arrows. |
| `numberOfMonths` | `number` | `1` | Months side by side in the paged layout. |
| `captionLayout` | `"label" \| "dropdown"` | `"label"` | `dropdown` turns each month heading into month and year selects, for dates years away like a birthday. Years run from `min` to `max`, else a century back and twenty years ahead. |
| `min` **agent** | `Date` | - | The earliest day that can be picked. Agents are refused before it. |
| `max` **agent** | `Date` | - | The latest day that can be picked. Agents are refused after it. |
| `isDateDisabled` **agent** | `(date: Date) => boolean` | - | Blocks single days, such as weekends. A range can't run across one. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `weekNumbers` | `boolean` | `false` | Shows week numbers before each week: ISO 8601 when weeks start on Monday, else the locale's. |
| `locale` | `Locale` | - | A date-fns locale for month and weekday names. |
| `weekStartsOn` | `0 to 6` | `1` | The first day of the week, 0 for Sunday. Defaults to the locale's. |
| `dir` | `"ltr" \| "rtl"` | - | Reading direction. Arrow keys follow it. |
| `today` | `Date` | - | Overrides the current day, for tests and other time zones. |
| `onPreview` | `(range: DateRange \| null) => void` | - | The range under the pointer while it waits for an end. |
| `name` | `string` | - | Submits the value with a form, as `YYYY-MM-DD` or `YYYY-MM-DD/YYYY-MM-DD`. |
| `required` | `boolean` | `false` | A picked day can't be unpicked by pressing it again. The hidden input is not validated; use a picker for a required field. |
| `autoFocus` | `boolean` | `false` | Focuses the picked day, or today, on mount. |
| `allowDisabledEnd` **agent** | `boolean` | `false` | Lets a range end on the first disabled day after its start, as a stay checks out on a booked night. That day still can't start a range. |
| `renderDay` | `(date: Date) => ReactNode` | - | Short content under a day's number, such as a price. |
| `dayClassName` | `(date: Date) => string \| undefined` | - | Classes for a day's button, such as a sold-out style. |
| `describeDay` | `(date: Date) => string \| undefined` | - | Words added to a day's name, such as "sold out", so it is heard as well as seen. |

## Agent
Inside an `AgentProvider`, Calendar appears in `agent.snapshot()` as `date`.
Reads:
- `label`: The calendar's aria-label.
- `value`: YYYY-MM-DD, a list of them in multiple mode, or [from, to] for a range.
- `multiple`: True in multiple and range modes, where the value is a list.
- `disabled`: True when the calendar is blocked.
- `invalid`: True when the value names a day that can't be picked, or a range runs across one.
Actions:
- `setValue("2026-12-24")`: Picks the day and scrolls to it. Phrases work too: next fri, in 2 weeks, 21 nov.
- `setValue(["2026-12-21", "2026-12-24"])`: Sets a range, or the days in multiple mode. Refuses a range that ends before it starts.
- `clear()`: Empties the value.
An agent's change runs through `onValueChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told the app refused. Days outside `min` and `max`, days `isDateDisabled` blocks, and text that isn't a date are refused with the reason.
```ts
await agent.act({
  steps: [{ ref: "Due date", action: "setValue", args: ["next fri"] }],
})
```

## Accessibility
- Each month is a grid. Every day is a button whose name is the full date.
- Picked days, and every day inside a picked range, carry aria-selected. A previewed range is drawn but not announced.
- Only one day is in the tab order: the picked day, else today. Arrows move from there.
- Today is marked with a dot as well as its name, not colour alone.
- The range band is a primary tint with a 3:1 edge against the surface, in light and dark.
- The paged arrows are plain buttons, Previous month and Next month, not a navigation landmark.
- If scrolling drops the month holding focus, focus moves to the nearest day still shown.
- Reduced motion turns off the smooth scroll to today.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `→` | Moves to the previous or next day |
| `↑` / `↓` | Moves by a week |
| `Page Up` / `Page Down` | Moves by a month, stopping at `min` and `max` and stepping off days that can't be picked |
| `Shift` | Held with Page Up or Page Down, moves by a year |
| `Home` / `End` | Moves to the start or end of the week |
| `Enter` / `Space` | Picks the focused day |

## Source
`components/ui/calendar/calendar.tsx`
```tsx
import * as React from "react";
import { DayPicker, type DayButtonProps, type DayProps, type MonthCaptionProps, type MonthGridProps, type MonthProps, type Matcher, type NavProps } from "react-day-picker";
import { format, type Locale } from "date-fns";
import { Select as SelectPrimitive } from "@base-ui/react/select";
import { Check, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent";

/* ----------------------------------------------------------------------------------------
 * Dates. A day is a Date at local midnight, so it means the same calendar day wherever it
 * is read, and forms carry it as YYYY-MM-DD. Nothing here converts time zones.
 * ------------------------------------------------------------------------------------- */

const DAY_MS = 86_400_000;

function startOfDay(date: Date): Date {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

function addDays(date: Date, days: number): Date {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
}

function addMonths(date: Date, months: number): Date {
  return new Date(date.getFullYear(), date.getMonth() + months, 1);
}

function isSameDay(a: Date | null | undefined, b: Date | null | undefined): boolean {
  return !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

/** Whole days from `a` to `b`, counted on the calendar so daylight saving never shifts it. */
function daysBetween(a: Date, b: Date): number {
  return Math.round((Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / DAY_MS);
}

function monthsBetween(a: Date, b: Date): number {
  return (b.getFullYear() - a.getFullYear()) * 12 + b.getMonth() - a.getMonth();
}

/** The ISO 8601 week number: weeks start on Monday, and week 1 holds the year's first Thursday. */
function isoWeek(date: Date): number {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
  return Math.ceil(((d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 1)) / DAY_MS + 1) / 7);
}

const pad = (n: number) => String(n).padStart(2, "0");

/** `YYYY-MM-DD`, the form a day is submitted and reported in. */
function toISODate(date: Date): string {
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}

/** The day a real calendar date names, or null when the parts don't make one (31 Feb). */
function makeDate(year: number, month: number, day: number): Date | null {
  const d = new Date(year, month, day);
  return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day ? d : null;
}

function fromISODate(text: string): Date | null {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text.trim());
  return m ? makeDate(+m[1], +m[2] - 1, +m[3]) : null;
}

const MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

/** The index of the name `word` spells or shortens to three letters or more, else -1. */
const nameIn = (names: string[], word: string) => (word.length < 3 ? -1 : names.findIndex((n) => n.startsWith(word)));

export interface ParseDateOptions {
  /** The day relative phrases count from. Defaults to today. */
  today?: Date;
  /** How a numeric date such as 3/12 is read. Defaults to the order the browser's language writes dates in. */
  order?: "day-first" | "month-first";
  /** The day a week starts on, which decides what "next fri" means. Defaults to Monday. */
  weekStartsOn?: number;
  /** The earliest day the field takes. A two-digit year lands inside `min` and `max` when it can. */
  min?: Date;
  max?: Date;
}

/** Whether `locale` writes the day before the month, read off how it formats a known date. */
function dayFirst(locale?: Locale): boolean {
  const page = typeof document !== "undefined" ? document.documentElement.lang : "";
  const code = locale?.code ?? (page || (typeof navigator !== "undefined" ? navigator.language : "en-GB"));
  try {
    const parts = new Intl.DateTimeFormat(code, { day: "numeric", month: "numeric" }).formatToParts(new Date(2000, 10, 22));
    return parts.findIndex((p) => p.type === "day") < parts.findIndex((p) => p.type === "month");
  } catch {
    return true;
  }
}

/**
 * A year as typed. Two digits land inside `min` and `max` when one century does, else up to
 * twenty years ahead of `base` or eighty back, so 30 is 2030 and 75 is 1975.
 */
function fullYear(text: string | undefined, base: Date, min?: Date, max?: Date): number {
  if (!text) return base.getFullYear();
  if (text.length === 4) return +text;
  const now = base.getFullYear();
  const century = Math.floor(now / 100) * 100;
  const years = [century - 100, century, century + 100].map((c) => c + +text);
  const inside = years.filter((y) => (!min || y >= min.getFullYear()) && (!max || y <= max.getFullYear()));
  const pool = inside.length ? inside : years;
  return pool.find((y) => y > now - 80 && y <= now + 20) ?? pool.reduce((a, b) => (Math.abs(b - now) < Math.abs(a - now) ? b : a));
}

/**
 * Reads what a person types into a date field: today, tomorrow, yesterday, in 3 days, in
 * 2 weeks, fri, next fri, 21 nov, nov 21, 21/11, 2026-11-21. Returns null when the text
 * isn't a date. English words only; pass your own parser to the pickers for other languages.
 */
function parseDate(input: string, { today = new Date(), order, weekStartsOn = 1, min, max }: ParseDateOptions = {}): Date | null {
  const base = startOfDay(today);
  const s = input
    .trim()
    .toLowerCase()
    .replace(/\s+/g, " ")
    .replace(/(\d)(st|nd|rd|th)\b/, "$1")
    // A weekday before a full date, as in "Fri, 21 Nov 2026", says nothing the date doesn't.
    .replace(/^([a-z]+)\.?,? (?=\d|[a-z]+\.? \d)/, (all, word: string) => (nameIn(WEEKDAYS, word) < 0 ? all : ""));
  if (!s) return null;
  if (s === "today" || s === "now") return base;
  if (s === "tomorrow" || s === "tmr") return addDays(base, 1);
  if (s === "yesterday") return addDays(base, -1);
  let m: RegExpMatchArray | null;
  if ((m = s.match(/^in (\d+) (day|week|month)s?$/))) {
    const n = +m[1];
    if (m[2] === "month") {
      const target = new Date(base.getFullYear(), base.getMonth() + n, 1);
      const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
      return new Date(target.getFullYear(), target.getMonth(), Math.min(base.getDate(), last));
    }
    return addDays(base, m[2] === "week" ? n * 7 : n);
  }
  if ((m = s.match(/^(next |this )?([a-z]+)$/)) && nameIn(WEEKDAYS, m[2]) >= 0) {
    const ahead = (nameIn(WEEKDAYS, m[2]) - base.getDay() + 7) % 7;
    // "this tue" on a Tuesday is today; a bare "tue" is the next one.
    let diff = ahead || (m[1] === "this " ? 0 : 7);
    // "next fri" is the Friday of next week, not the coming one.
    if (m[1] === "next " && diff <= 6 - ((base.getDay() - weekStartsOn + 7) % 7)) diff += 7;
    return addDays(base, diff);
  }
  if ((m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/))) return makeDate(+m[1], +m[2] - 1, +m[3]);
  if ((m = s.match(/^(\d{1,2})[/.\- ](\d{1,2})(?:[/.\- ](\d{2}|\d{4}))?$/))) {
    const [day, month] = (order ?? (dayFirst() ? "day-first" : "month-first")) === "day-first" ? [+m[1], +m[2]] : [+m[2], +m[1]];
    return makeDate(fullYear(m[3], base, min, max), month - 1, day);
  }
  if ((m = s.match(/^(\d{1,2}) ([a-z]+)\.?,?(?: (\d{2}|\d{4}))?$/)) && nameIn(MONTHS, m[2]) >= 0) {
    return makeDate(fullYear(m[3], base, min, max), nameIn(MONTHS, m[2]), +m[1]);
  }
  if ((m = s.match(/^([a-z]+)\.? (\d{1,2}),?(?: (\d{2}|\d{4}))?$/)) && nameIn(MONTHS, m[1]) >= 0) {
    return makeDate(fullYear(m[3], base, min, max), nameIn(MONTHS, m[1]), +m[2]);
  }
  return null;
}

/* ----------------------------------------------------------------------------------------
 * Calendar
 * ------------------------------------------------------------------------------------- */

export interface DateRange {
  from: Date | null;
  to: Date | null;
}

export type CalendarMode = "single" | "multiple" | "range";

/** Base UI's change details shape, so a handler can cancel a change the same way. */
export interface CalendarChangeDetails {
  reason: "day-press" | "imperative-action" | (string & {});
  event: Event | undefined;
  isCanceled: boolean;
  cancel(): void;
}

function changeDetails(reason: string, event?: Event): CalendarChangeDetails {
  const details: CalendarChangeDetails = {
    reason,
    event,
    isCanceled: false,
    cancel() {
      details.isCanceled = true;
    },
  };
  return details;
}

type ValueOf<M extends CalendarMode> = M extends "range" ? DateRange : M extends "multiple" ? Date[] : Date | null;

interface CalendarBaseProps
  extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange" | "dir"> {
  /** `scroll`: months as one column you scroll. `paged`: arrows and months side by side. */
  layout?: "scroll" | "paged";
  /** Months side by side in the paged layout. */
  numberOfMonths?: number;
  /** `dropdown` turns the month heading into month and year selects, for jumping far. */
  captionLayout?: "label" | "dropdown";
  /** The earliest day that can be picked. Scrolling stops at its month. */
  min?: Date;
  /** The latest day that can be picked. */
  max?: Date;
  /** Days that can't be picked, besides those outside `min` and `max`. */
  isDateDisabled?: (date: Date) => boolean;
  disabled?: boolean;
  /** Shows ISO week numbers in a column before each week. */
  weekNumbers?: boolean;
  /** A date-fns locale, for month and weekday names and the first day of the week. */
  locale?: Locale;
  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
  dir?: "ltr" | "rtl";
  /** Defaults to the current day. */
  today?: Date;
  /** Submits the value with a form: a day as YYYY-MM-DD, a range as YYYY-MM-DD/YYYY-MM-DD. */
  name?: string;
  required?: boolean;
  /** The day under the pointer while a range waits for its end, for a live readout. */
  onPreview?: (range: DateRange | null) => void;
  /** Moves focus to the selected day, or today, when the calendar mounts. */
  autoFocus?: boolean;
  /**
   * Lets a range end on the first disabled day after its start, as a stay checks out on a
   * night that is booked. The day still can't start a range.
   */
  allowDisabledEnd?: boolean;
  /** Extra content under a day's number, such as a price. Keep it short: a cell is 2.5rem. */
  renderDay?: (date: Date) => React.ReactNode;
  /** Classes for a day's button. */
  dayClassName?: (date: Date) => string | undefined;
  /** Words added to a day's accessible name, such as "sold out" or "£120". */
  describeDay?: (date: Date) => string | undefined;
}

export type CalendarProps = CalendarBaseProps &
  (
    | {
        mode?: "single";
        value?: Date | null;
        defaultValue?: Date | null;
        onValueChange?: (value: Date | null, details: CalendarChangeDetails) => void;
      }
    | {
        mode: "multiple";
        value?: Date[];
        defaultValue?: Date[];
        onValueChange?: (value: Date[], details: CalendarChangeDetails) => void;
      }
    | {
        mode: "range";
        value?: DateRange;
        defaultValue?: DateRange;
        onValueChange?: (value: DateRange, details: CalendarChangeDetails) => void;
      }
  );

const EMPTY_RANGE: DateRange = { from: null, to: null };

function emptyFor(mode: CalendarMode): ValueOf<CalendarMode> {
  return mode === "range" ? EMPTY_RANGE : mode === "multiple" ? [] : null;
}

/** The day the calendar opens on: the selection, else today, kept inside the bounds. */
function anchorOf(mode: CalendarMode, value: ValueOf<CalendarMode>, today: Date, min?: Date, max?: Date): Date {
  const picked =
    mode === "range" ? (value as DateRange).from : mode === "multiple" ? (value as Date[])[0] : (value as Date | null);
  let day = picked ?? today;
  if (min && day < min) day = min;
  if (max && day > max) day = max;
  return day;
}

/** Months rendered either side of the anchor in the scroll layout, before scrolling adds more. */
const WINDOW = 6;
const GROW = 6;
/** The most months the scroll layout holds; growing one end trims the other past this. */
const MAX_MONTHS = WINDOW * 2 + 1 + GROW;

/** Reads a typed value an agent sent: one day, a list of days, or a from and to. */
function agentValue(
  mode: CalendarMode,
  wanted: unknown,
  parse: ParseDateOptions,
  blocked: (d: Date) => boolean,
  valid: (d: Date, end: boolean) => string | null
): ValueOf<CalendarMode> | string {
  const one = (item: unknown, end = false): Date | string => {
    const d = item instanceof Date ? (isNaN(item.getTime()) ? null : startOfDay(item)) : typeof item === "string" ? parseDate(item, parse) : null;
    if (!d) return `"${String(item)}" is not a date. Send YYYY-MM-DD.`;
    return valid(d, end) ?? d;
  };
  if (mode === "single") return wanted === null || wanted === "" ? null : one(wanted);
  let list: unknown[] = [wanted];
  if (Array.isArray(wanted)) list = wanted;
  else if (typeof wanted === "string") {
    // "/" also separates the parts of 21/11, so it splits only an ISO pair.
    list = /^\s*\d{4}-\d\d-\d\d\s*\/\s*\d{4}-\d\d-\d\d\s*$/.test(wanted) ? wanted.split("/") : wanted.split(/\s*(?:,| to )\s*/);
  }
  const days = list.map((item, i) => one(item, mode === "range" && i === 1));
  const wrong = days.find((d) => typeof d === "string");
  if (wrong) return wrong as string;
  const dates = days as Date[];
  if (mode === "multiple") return dates.sort((a, b) => a.getTime() - b.getTime());
  if (dates.length !== 2) return "Send two dates, from and to.";
  if (dates[1] < dates[0]) return "The range must end on or after its start.";
  for (let d = addDays(dates[0], 1); d < dates[1]; d = addDays(d, 1)) {
    if (blocked(d)) return `The range can't run across ${toISODate(d)}, which can't be picked.`;
  }
  return { from: dates[0], to: dates[1] };
}

function agentReport(mode: CalendarMode, value: ValueOf<CalendarMode>): string | string[] | undefined {
  if (mode === "single") return value ? toISODate(value as Date) : undefined;
  if (mode === "multiple") return (value as Date[]).map(toISODate);
  const { from, to } = value as DateRange;
  return from ? [toISODate(from), ...(to ? [toISODate(to)] : [])] : undefined;
}

/** The cell for `day`, not the hidden copy RDP keeps in the neighbouring month's grid. */
const dayCell = (day: Date) => `[data-day="${toISODate(day)}"]:not([data-outside])`;

const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/** A function whose identity never changes but which always runs the latest render's code. */
function useStable<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
  const latest = React.useRef(fn);
  React.useLayoutEffect(() => {
    latest.current = fn;
  });
  return React.useCallback((...args: A) => latest.current(...args), []);
}

const noop = () => {};

interface DayHooks {
  preview: (day: Date | null) => void;
  /** Moves focus for PageUp and PageDown. True when it handled the key. */
  page: (day: Date, event: React.KeyboardEvent) => boolean;
  renderDay?: (date: Date) => React.ReactNode;
  dayClassName?: (date: Date) => string | undefined;
  describeDay?: (date: Date) => string | undefined;
}

const DayContext = React.createContext<DayHooks>({ preview: () => {}, page: () => false });
const ModeContext = React.createContext<CalendarMode>("single");

/*
 * RDP's parts, replaced so they carry our data-slots and classes. They live outside the
 * component so their identity is stable: a new one each render would remount every day.
 */
function CalendarDayButton({ day, modifiers: m, className: _c, children, ...buttonProps }: DayButtonProps) {
  const { preview, page, renderDay, dayClassName, describeDay } = React.useContext(DayContext);
  const date = day.date;
  const extra = !m.hidden && renderDay?.(date);
  const description = !m.hidden && describeDay?.(date);
  const ref = React.useRef<HTMLButtonElement>(null);
  // RDP moves focus by flagging the day, and its own button focuses itself; so must this one.
  React.useEffect(() => {
    if (m.focused) ref.current?.focus();
  }, [m.focused]);
  return (
    <button
      {...buttonProps}
      aria-label={description ? `${buttonProps["aria-label"]}, ${description}` : buttonProps["aria-label"]}
      onKeyDown={(e) => {
        if (page(date, e)) {
          e.preventDefault();
          e.stopPropagation();
        } else buttonProps.onKeyDown?.(e);
      }}
      ref={ref}
      data-slot="calendar-day"
      data-today={m.today || undefined}
      data-selected={m.selected || undefined}
      data-range={m.band_start ? "start" : m.band_end ? "end" : m.band ? "middle" : undefined}
      className={cn(
        "relative mx-auto flex size-[var(--calendar-cell)] items-center justify-center rounded-[calc(var(--radius)-2px)] text-sm tabular-nums outline-none",
        "transition-colors duration-150 motion-reduce:transition-none",
        "hover:bg-accent hover:text-accent-foreground",
        "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
        m.band && !m.selected && "hover:bg-transparent",
        (m.selected || m.band_start || m.band_end) && "bg-primary font-medium text-primary-foreground hover:bg-primary hover:text-primary-foreground",
        m.today && "after:absolute after:bottom-1 after:left-1/2 after:size-1 after:-translate-x-1/2 after:rounded-full after:bg-current",
        extra != null && extra !== false && "flex-col gap-0 leading-none",
        m.disabled && "pointer-events-none text-muted-foreground opacity-50",
        m.outside && "text-muted-foreground",
        !m.hidden && dayClassName?.(date)
      )}
      onPointerEnter={() => preview(date)}
    >
      {children}
      {extra != null && extra !== false && (
        <span data-slot="calendar-day-content" className="mt-0.5 text-[0.625rem] font-normal leading-none">
          {extra}
        </span>
      )}
    </button>
  );
}

/**
 * Every day of a picked range is selected, not only its ends; a previewed one is not. RDP
 * keeps a hidden copy of each neighbouring month's days, which never take part. The band is
 * a primary tint with a stronger edge, so it reads at 3:1 against the surface in both themes.
 */
function CalendarDay({ day: _d, modifiers: m, className, ...cellProps }: DayProps) {
  const band = m.band && !m.hidden;
  return (
    <td
      {...cellProps}
      data-band={band ? (m.band_start ? "start" : m.band_end ? "end" : m.unavailable ? "blocked" : "middle") : undefined}
      className={cn(
        className,
        band &&
          "bg-[var(--calendar-band)] shadow-[inset_0_1px_0_var(--calendar-band-edge),inset_0_-1px_0_var(--calendar-band-edge)] first-of-type:rounded-s-[calc(var(--radius)-2px)] last-of-type:rounded-e-[calc(var(--radius)-2px)]",
        band && m.band_start && "rounded-s-[calc(var(--radius)-2px)]",
        band && m.band_end && "rounded-e-[calc(var(--radius)-2px)]",
        band && m.unavailable && !m.band_start && !m.band_end && "bg-destructive/15 shadow-none"
      )}
      aria-selected={(!m.hidden && (m.selected || m.chosen)) || undefined}
    />
  );
}

/** RDP is always told `multiple`, so the grid says multiselectable only when it is. */
function CalendarMonthGrid(props: MonthGridProps) {
  const mode = React.useContext(ModeContext);
  return <table {...props} aria-multiselectable={mode !== "single" || undefined} />;
}

function CalendarMonth({ calendarMonth: _m, displayIndex: _i, ...monthProps }: MonthProps) {
  return <div {...monthProps} data-slot="calendar-month" />;
}

/** The paged arrows, as plain buttons: a landmark per calendar would crowd the page's own. */
function CalendarNav({ onPreviousClick, onNextClick, previousMonth, nextMonth, className }: NavProps) {
  const arrow = cn(
    "pointer-events-auto inline-flex size-8 items-center justify-center rounded-md text-muted-foreground outline-none",
    "hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring aria-disabled:pointer-events-none aria-disabled:opacity-40"
  );
  return (
    <div data-slot="calendar-nav" className={className}>
      <button
        type="button"
        data-slot="calendar-previous"
        aria-label="Previous month"
        aria-disabled={!previousMonth || undefined}
        tabIndex={previousMonth ? undefined : -1}
        className={arrow}
        onClick={(e) => previousMonth && onPreviousClick?.(e)}
      >
        <ChevronLeft className="size-4 rtl:rotate-180" />
      </button>
      <button
        type="button"
        data-slot="calendar-next"
        aria-label="Next month"
        aria-disabled={!nextMonth || undefined}
        tabIndex={nextMonth ? undefined : -1}
        className={arrow}
        onClick={(e) => nextMonth && onNextClick?.(e)}
      >
        <ChevronRight className="size-4 rtl:rotate-180" />
      </button>
    </div>
  );
}

type CaptionOption = { value: number; label: string; disabled?: boolean };

// Opens with the current choice in the middle, so the years either side of it both show.
function centreSelected(popup: HTMLDivElement | null) {
  if (!popup) return;
  requestAnimationFrame(() => {
    const item = popup.querySelector<HTMLElement>("[data-selected]");
    if (item) popup.scrollTop = item.offsetTop - popup.clientHeight / 2 + item.offsetHeight / 2;
  });
}

/** Base UI's select rather than ours, so a scroll of captions doesn't register dozens of agent controls. */
function CaptionSelect({
  value,
  options,
  onChange,
  disabled,
  ...props
}: {
  value: number;
  options: CaptionOption[];
  onChange: (value: number) => void;
  disabled?: boolean;
  "aria-label": string;
  "data-slot": string;
}) {
  return (
    <SelectPrimitive.Root<number> value={value} onValueChange={(v) => v != null && onChange(v)} disabled={disabled} modal={false}>
      <SelectPrimitive.Trigger
        {...props}
        className={cn(
          "inline-flex h-8 items-center gap-1 rounded-md pe-1.5 ps-2 text-sm font-semibold text-foreground",
          "hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-[popup-open]:bg-accent",
          "disabled:pointer-events-none disabled:opacity-50"
        )}
      >
        {options.find((o) => o.value === value)?.label ?? value}
        <ChevronDown aria-hidden className="size-3.5 text-muted-foreground" />
      </SelectPrimitive.Trigger>
      <SelectPrimitive.Portal>
        <SelectPrimitive.Positioner sideOffset={4} alignItemWithTrigger={false} className="z-50">
          <SelectPrimitive.Popup
            ref={centreSelected}
            className={cn(
              "max-h-[min(15rem,var(--available-height))] min-w-[max(var(--anchor-width),5rem)] overflow-y-auto overscroll-contain rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-black/5",
              "origin-[var(--transform-origin)] transition-[scale,opacity] duration-150 ease-out motion-reduce:transition-none",
              "data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:scale-95 data-[ending-style]:opacity-0"
            )}
          >
            {options.map((o) => (
              <SelectPrimitive.Item
                key={o.value}
                value={o.value}
                disabled={o.disabled}
                className={cn(
                  "relative flex h-8 cursor-default select-none items-center rounded-md pe-2 ps-7 text-sm tabular-nums outline-none",
                  "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground data-[selected]:font-medium data-[disabled]:opacity-40"
                )}
              >
                <SelectPrimitive.ItemIndicator className="absolute start-2 inline-flex">
                  <Check className="size-3.5" />
                </SelectPrimitive.ItemIndicator>
                <SelectPrimitive.ItemText>{o.label}</SelectPrimitive.ItemText>
              </SelectPrimitive.Item>
            ))}
          </SelectPrimitive.Popup>
        </SelectPrimitive.Positioner>
      </SelectPrimitive.Portal>
    </SelectPrimitive.Root>
  );
}


/**
 * A month grid for picking a day, several days or a range. Months scroll as one column by
 * default, with a Today button that appears once today is out of view.
 */
const Calendar = React.forwardRef<HTMLDivElement, CalendarProps>((props, ref) => {
  const {
    mode = "single",
    value: valueProp,
    defaultValue,
    onValueChange,
    layout = "scroll",
    numberOfMonths = 1,
    captionLayout = "label",
    min: minProp,
    max: maxProp,
    isDateDisabled,
    disabled,
    weekNumbers = false,
    locale,
    weekStartsOn = locale?.options?.weekStartsOn ?? 1,
    dir,
    today: todayProp,
    name,
    required,
    onPreview,
    autoFocus,
    allowDisabledEnd = false,
    renderDay,
    dayClassName,
    describeDay,
    className,
    ...rest
  } = props;

  const today = React.useMemo(() => startOfDay(todayProp ?? new Date()), [todayProp ? toISODate(todayProp) : null]);
  const min = minProp && startOfDay(minProp);
  const max = maxProp && startOfDay(maxProp);
  const [value, change] = useAgentState<ValueOf<CalendarMode>, CalendarChangeDetails>(
    valueProp as ValueOf<CalendarMode> | undefined,
    (defaultValue as ValueOf<CalendarMode> | undefined) ?? emptyFor(mode),
    onValueChange as ((v: ValueOf<CalendarMode>, d: CalendarChangeDetails) => void) | undefined
  );
  const [hover, setHover] = React.useState<Date | null>(null);
  const root = React.useRef<HTMLDivElement>(null);
  const scroller = React.useRef<HTMLDivElement>(null);
  const scroll = layout === "scroll";

  const outside = (d: Date) => (!!min && d < min) || (!!max && d > max);
  /** A day no one can pick, whatever the calendar's own disabled state. */
  const unavailable = (d: Date) => outside(d) || !!isDateDisabled?.(d);
  const blocked = React.useCallback(
    (d: Date) => !!disabled || unavailable(d),
    [disabled, min?.getTime(), max?.getTime(), isDateDisabled]
  );
  /** Whether a range from `from` to `to` runs across a day that can't be picked. */
  const crosses = (from: Date, to: Date) => {
    for (let d = addDays(from, 1); d < to; d = addDays(d, 1)) if (unavailable(d)) return true;
    return false;
  };
  /** A day that can end a range though it can't start one. */
  const endOnly = (d: Date) => allowDisabledEnd && !outside(d) && !!isDateDisabled?.(d);

  /* ---- the months on screen ---- */
  const anchor = anchorOf(mode, value, today, min, max);
  const clampMonth = (m: Date) => {
    if (min && m < addMonths(min, 0)) return addMonths(min, 0);
    if (max && m > addMonths(max, 0)) return addMonths(max, 0);
    return m;
  };
  const [span, setSpan] = React.useState(() => ({
    start: clampMonth(addMonths(anchor, scroll ? -WINDOW : 0)),
    end: clampMonth(addMonths(anchor, scroll ? WINDOW : numberOfMonths - 1)),
  }));
  const count = monthsBetween(span.start, span.end) + 1;

  // Switching layout or month count recentres on the anchor, since a scroll window starts months back.
  const shape = React.useRef({ scroll, numberOfMonths });
  React.useEffect(() => {
    if (shape.current.scroll === scroll && shape.current.numberOfMonths === numberOfMonths) return;
    shape.current = { scroll, numberOfMonths };
    if (scroll) pending.current = anchor;
    setSpan({
      start: clampMonth(addMonths(anchor, scroll ? -WINDOW : 0)),
      end: clampMonth(addMonths(anchor, scroll ? WINDOW : numberOfMonths - 1)),
    });
  }, [scroll, numberOfMonths]);

  // Keeps the reading position when months are added or dropped above it, by pinning a month both renders share.
  const pinned = React.useRef<{ month: Date; top: number } | null>(null);
  const monthTop = (sc: HTMLElement, start: Date, month: Date) =>
    sc.querySelectorAll("[data-slot=calendar-month]")[monthsBetween(start, month)]?.getBoundingClientRect().top;
  React.useLayoutEffect(() => {
    const sc = scroller.current;
    const pin = pinned.current;
    pinned.current = null;
    const top = sc && pin ? monthTop(sc, span.start, pin.month) : undefined;
    if (sc && pin && top !== undefined) {
      const scale = sc.getBoundingClientRect().height / sc.offsetHeight || 1;
      sc.scrollTop += (top - pin.top) / scale;
    }
  }, [span.start.getTime()]);

  // A focused day whose month a trim drops hands focus to the nearest month still shown.
  const refocus = React.useRef<Date | null>(null);
  const grow = React.useCallback(() => {
    const sc = scroller.current;
    if (!sc || !scroll) return;
    const room = sc.clientHeight;
    const pin = (month: Date) => {
      const top = monthTop(sc, span.start, month);
      if (top !== undefined) pinned.current = { month, top };
    };
    const focused = fromISODate(document.activeElement?.closest?.("[data-day]")?.getAttribute("data-day") ?? "");
    const keep = (start: Date, end: Date) => {
      if (!focused || !sc.contains(document.activeElement)) return;
      const month = addMonths(focused, 0);
      if (month < start) refocus.current = start;
      else if (month > end) refocus.current = addMonths(end, 1);
    };
    if (sc.scrollTop < room && (!min || span.start > addMonths(min, 0))) {
      const start = clampMonth(addMonths(span.start, -GROW));
      const end = monthsBetween(start, span.end) >= MAX_MONTHS ? addMonths(start, MAX_MONTHS - 1) : span.end;
      pin(span.start);
      keep(start, end);
      setSpan({ start, end });
    } else if (sc.scrollHeight - sc.scrollTop - room < room && (!max || span.end < addMonths(max, 0))) {
      const end = clampMonth(addMonths(span.end, GROW));
      const start = monthsBetween(span.start, end) >= MAX_MONTHS ? addMonths(end, -(MAX_MONTHS - 1)) : span.start;
      if (start.getTime() !== span.start.getTime()) pin(start);
      keep(start, end);
      setSpan({ start, end });
    }
  }, [scroll, span.start.getTime(), span.end.getTime(), min?.getTime(), max?.getTime()]);

  /** Scrolls `day` into view, keeping its month's heading on top when it fits. */
  const reveal = React.useCallback(
    (day: Date, smooth: boolean) => {
      const sc = scroller.current;
      const cell = sc?.querySelector<HTMLElement>(dayCell(day));
      if (!sc || !cell) return;
      // A popover opens scaled down, and rects carry the scale where scrollTop doesn't.
      const box = sc.getBoundingClientRect();
      const scale = box.height / sc.offsetHeight || 1;
      const offset = (node: Element) => sc.scrollTop + (node.getBoundingClientRect().top - box.top) / scale;
      const month = cell.closest("[data-slot=calendar-month]") ?? cell;
      const top = Math.max(offset(cell) - sc.clientHeight / 2 + cell.offsetHeight / 2, offset(month));
      sc.scrollTo?.({ top, behavior: smooth && !reducedMotion() ? "smooth" : "auto" });
    },
    []
  );

  // A day to scroll to, and one to focus, once the months they need have rendered.
  const pending = React.useRef<Date | null>(null);
  const pendingFocus = React.useRef<Date | null>(null);
  React.useLayoutEffect(() => {
    if (pending.current) reveal(pending.current, false);
    pending.current = null;
    const days = () => [...(root.current?.querySelectorAll<HTMLButtonElement>("td:not([data-outside]) [data-slot=calendar-day]:not(:disabled)") ?? [])];
    if (pendingFocus.current) root.current?.querySelector<HTMLElement>(`${dayCell(pendingFocus.current)} button`)?.focus();
    else if (refocus.current) {
      // Before the first day of the month after the kept span: the last day shown; else the first.
      const edge = refocus.current;
      const list = days();
      const day = edge > span.end ? list[list.length - 1] : list[0];
      day?.focus({ preventScroll: true });
    }
    pendingFocus.current = null;
    refocus.current = null;
  }, [span.start.getTime(), span.end.getTime()]);

  const goTo = React.useCallback(
    (day: Date, smooth: boolean) => {
      const month = addMonths(day, 0);
      if (!scroll) {
        const last = addMonths(span.start, numberOfMonths - 1);
        if (month < span.start || month > last) setSpan({ start: clampMonth(month), end: clampMonth(addMonths(month, numberOfMonths - 1)) });
      } else if (month < span.start || month > span.end) {
        pending.current = day;
        setSpan({ start: clampMonth(addMonths(day, -WINDOW)), end: clampMonth(addMonths(day, WINDOW)) });
      } else reveal(day, smooth);
    },
    [scroll, numberOfMonths, span.start.getTime(), span.end.getTime(), min?.getTime(), max?.getTime(), reveal]
  );

  // A value set from outside, by the app or an agent, brings its day into view.
  const mounted = React.useRef(false);
  React.useEffect(() => {
    if (!mounted.current) return void (mounted.current = true);
    const sc = scroller.current;
    const cell = sc?.querySelector(dayCell(anchor));
    if (scroll && sc && cell) {
      const [a, b] = [sc.getBoundingClientRect(), cell.getBoundingClientRect()];
      if (b.top >= a.top && b.bottom <= a.bottom) return;
    }
    goTo(anchor, true);
  }, [anchor.getTime()]);

  React.useLayoutEffect(() => {
    if (scroll) reveal(anchor, false);
    if (autoFocus) root.current?.querySelector<HTMLElement>("[data-slot=calendar-day][tabindex='0']")?.focus({ preventScroll: true });
  }, []);

  /* ---- Today button: shown while today is out of view ---- */
  const [todayHidden, setTodayHidden] = React.useState(false);
  const todayInRange = (!min || today >= min) && (!max || today <= max);
  React.useEffect(() => {
    const sc = scroller.current;
    const cell = sc?.querySelector(dayCell(today));
    if (!scroll || !sc || typeof IntersectionObserver === "undefined") return;
    if (!cell) {
      setTodayHidden(true);
      return;
    }
    const io = new IntersectionObserver(([entry]) => setTodayHidden(!entry.isIntersecting), { root: sc, threshold: 1 });
    io.observe(cell);
    return () => io.disconnect();
  }, [scroll, today.getTime(), span.start.getTime(), span.end.getTime()]);

  /** Focuses `day`, bringing its month into view first when it isn't rendered. */
  const focusDay = (day: Date) => {
    const button = root.current?.querySelector<HTMLElement>(`${dayCell(day)} button`);
    const month = addMonths(day, 0);
    const visible = scroll || (month >= span.start && month <= addMonths(span.start, numberOfMonths - 1));
    if (button && visible) {
      button.focus();
      if (scroll) reveal(day, false);
      return;
    }
    pendingFocus.current = day;
    goTo(day, false);
  };

  /*
   * PageUp and PageDown move a month, a year with Shift, to the same day or the month's last.
   * Past min or max they stop at it; on a day that can't be picked they step back toward
   * where focus came from, so a key never strands focus at a month's start.
   */
  const page = useStable((day: Date, event: React.KeyboardEvent) => {
    if (event.key !== "PageUp" && event.key !== "PageDown") return false;
    const step = (event.key === "PageUp" ? -1 : 1) * (event.shiftKey ? 12 : 1);
    const month = addMonths(day, step);
    const last = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
    let target = new Date(month.getFullYear(), month.getMonth(), Math.min(day.getDate(), last));
    if (min && target < min) target = min;
    if (max && target > max) target = max;
    const back = step > 0 ? -1 : 1;
    while (blocked(target) && !isSameDay(target, day)) target = addDays(target, back);
    if (!isSameDay(target, day)) focusDay(target);
    return true;
  });

  /* ---- selection ---- */
  const commit = (next: ValueOf<CalendarMode>, details: CalendarChangeDetails) => change(next, details);

  const waiting = mode === "range" && (value as DateRange).from && !(value as DateRange).to ? (value as DateRange).from : null;
  // The day a waiting range may end on though it can't be picked: the first blocked one after its start.
  const checkout = React.useMemo(() => {
    if (!waiting || !allowDisabledEnd || disabled) return null;
    for (let d = addDays(waiting, 1), i = 0; i < 731 && !(max && d > max); d = addDays(d, 1), i++) {
      if (unavailable(d)) return endOnly(d) ? d : null;
    }
    return null;
  }, [waiting?.getTime(), allowDisabledEnd, disabled, min?.getTime(), max?.getTime(), isDateDisabled]);

  const pick = (day: Date, event?: React.SyntheticEvent) => {
    const details = changeDetails("day-press", event?.nativeEvent);
    if (mode === "range" && unavailable(day) && !isSameDay(day, checkout)) return;
    if (mode === "single") return commit(isSameDay(value as Date | null, day) && !required ? null : day, details);
    if (mode === "multiple") {
      const list = value as Date[];
      const has = list.some((d) => isSameDay(d, day));
      return commit(has ? list.filter((d) => !isSameDay(d, day)) : [...list, day].sort((a, b) => a.getTime() - b.getTime()), details);
    }
    const { from, to } = value as DateRange;
    setHover(null);
    onPreview?.(null);
    if (!from || to || day < from) return commit({ from: day, to: null }, details);
    // A range must not run across a day that can't be picked; pressing past one starts afresh.
    if (crosses(from, day)) return commit({ from: day, to: null }, changeDetails("range-blocked", event?.nativeEvent));
    return commit({ from, to: day }, details);
  };

  const preview = useStable((day: Date | null) => {
    if (!waiting) return;
    const reachable = (d: Date) => d >= waiting && (!unavailable(d) || isSameDay(d, checkout)) && !crosses(waiting, d);
    const end = day && reachable(day) ? day : null;
    setHover(end);
    onPreview?.(end ? { from: waiting, to: end } : null);
  });

  /* ---- what RDP is told ---- */
  const range = mode === "range" ? (value as DateRange) : null;
  const shown: DateRange | null = range && (range.to ? range : waiting && hover ? { from: waiting, to: hover } : range.from ? range : null);
  // RDP is told the picked days as a plain list, which drives aria-selected and where Tab
  // lands. A previewed end is drawn as one but not announced as picked.
  const picked: Date[] =
    mode === "single" ? (value ? [value as Date] : []) : mode === "multiple" ? (value as Date[]) : ([range?.from, range?.to].filter(Boolean) as Date[]);
  const modifiers: Record<string, Matcher | Matcher[] | undefined> = {
    band: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? { from: shown.from, to: shown.to } : undefined,
    band_start: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? shown.from : undefined,
    band_end: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? shown.to : undefined,
    chosen: range?.from && range.to ? { from: range.from, to: range.to } : undefined,
    unavailable,
  };
  // A range's end, or the day a waiting one may end on, stays pressable though it is blocked.
  const pressable = (d: Date) => isSameDay(d, checkout) || (!!range?.to && isSameDay(d, range.to) && endOnly(d));
  const disabledDay = (d: Date) => blocked(d) && !(pressable(d) && !disabled);

  /** A value set from outside that names a day that can't be picked, or runs across one. */
  const problem = (() => {
    const say = (d: Date) => `${toISODate(d)} can't be picked.`;
    if (mode === "single") return value && unavailable(value as Date) ? say(value as Date) : null;
    if (mode === "multiple") {
      const bad = (value as Date[]).find(unavailable);
      return bad ? say(bad) : null;
    }
    const { from, to } = value as DateRange;
    if (from && unavailable(from)) return say(from);
    if (to && unavailable(to) && !endOnly(to)) return say(to);
    if (from && to && crosses(from, to)) return "The range runs across a day that can't be picked.";
    return null;
  })();

  /* ---- agent ---- */
  useAgentControl(() => ({
    kind: "date",
    element: root.current,
    value: agentReport(mode, value),
    multiple: mode !== "single",
    disabled,
    required,
    invalid: !!problem || undefined,
    errors: problem ? [problem] : undefined,
    actions: {
      setValue: (wanted: unknown) => {
        const parse = { today, order: dayFirst(locale) ? "day-first" : "month-first", weekStartsOn, min, max } as const;
        const next = agentValue(mode, wanted, parse, blocked, (d, end) =>
          blocked(d) && !(end && endOnly(d) && !disabled) ? `${toISODate(d)} can't be picked${min && d < min ? `: the earliest is ${toISODate(min)}` : max && d > max ? `: the latest is ${toISODate(max)}` : ""}.` : null
        );
        if (typeof next === "string") return next;
        const failed = changeAsAgent(change, next);
        if (!failed) goTo(anchorOf(mode, next, today, min, max), false);
        return failed;
      },
      clear: () => changeAsAgent(change, emptyFor(mode)),
    },
  }));

  /* ---- render ---- */
  // Selects reach from min to max, else a century back and twenty years ahead.
  const years = React.useMemo(() => {
    const from = min?.getFullYear() ?? today.getFullYear() - 100;
    const to = max?.getFullYear() ?? today.getFullYear() + 20;
    return Array.from({ length: to - from + 1 }, (_, i) => from + i);
  }, [min?.getFullYear(), max?.getFullYear(), today.getFullYear()]);
  const monthNames = React.useMemo(
    () => Array.from({ length: 12 }, (_, i) => format(new Date(2000, i, 1), "LLL", { locale })),
    [locale]
  );

  // Through a ref, so the caption keeps its identity and a select keeps focus after a jump.
  const jumpTo = React.useRef((_month: Date, _index: number) => {});
  jumpTo.current = (month, index) => {
    if (scroll) return goTo(clampMonth(month), false);
    let start = addMonths(month, -index);
    if (max && monthsBetween(start, max) < numberOfMonths - 1) start = addMonths(max, -(numberOfMonths - 1));
    start = clampMonth(start);
    setSpan({ start, end: addMonths(start, numberOfMonths - 1) });
  };

  const MonthCaption = React.useCallback(
    ({ calendarMonth, displayIndex, className: _c, ...captionProps }: MonthCaptionProps) => {
      const shown = calendarMonth.date;
      // In the paged layout a month is out when the pages either side of this one would pass min or max.
      const before = scroll ? 0 : displayIndex;
      const after = scroll ? 0 : numberOfMonths - 1 - displayIndex;
      const outside = (m: Date) =>
        (!!min && addMonths(m, -before) < addMonths(min, 0)) || (!!max && addMonths(m, after) > addMonths(max, 0));
      return (
        <div
          {...captionProps}
          data-slot="calendar-caption"
          className={cn(
            "px-1 pb-2 pt-3 text-sm font-semibold",
            scroll && "sticky top-0 z-10 bg-[var(--calendar-bg)]",
            !scroll && "flex h-9 items-center justify-center pt-0",
            captionLayout === "dropdown" && "flex items-center gap-1",
            captionLayout === "dropdown" && scroll && "-ms-1.5"
          )}
        >
          {captionLayout === "dropdown" ? (
            <>
              <CaptionSelect
                data-slot="calendar-month-select"
                aria-label="Month"
                disabled={disabled}
                value={shown.getMonth()}
                options={monthNames.map((label, i) => ({ value: i, label, disabled: outside(new Date(shown.getFullYear(), i, 1)) }))}
                onChange={(m) => jumpTo.current(new Date(shown.getFullYear(), m, 1), displayIndex)}
              />
              <CaptionSelect
                data-slot="calendar-year-select"
                aria-label="Year"
                disabled={disabled}
                value={shown.getFullYear()}
                options={(years.includes(shown.getFullYear()) ? years : [...years, shown.getFullYear()].sort((x, y) => x - y)).map((y) => ({ value: y, label: String(y) }))}
                onChange={(y) => jumpTo.current(new Date(y, shown.getMonth(), 1), displayIndex)}
              />
            </>
          ) : (
            format(shown, "LLLL y", { locale })
          )}
        </div>
      );
    },
    [scroll, numberOfMonths, locale, captionLayout, monthNames, years, disabled, min?.getTime(), max?.getTime()]
  );

  const weekdayNames = React.useMemo(() => {
    const monday = new Date(2024, 0, 1);
    return Array.from({ length: 7 }, (_, i) => addDays(monday, ((weekStartsOn + 6) % 7) + i));
  }, [weekStartsOn]);

  const grid = "grid grid-cols-[repeat(7,var(--calendar-cell))] justify-between";
  const gridWithWeeks = "grid grid-cols-[1.5rem_repeat(7,var(--calendar-cell))] justify-between";

  const values =
    mode === "single"
      ? value ? [toISODate(value as Date)] : []
      : mode === "multiple"
        ? (value as Date[]).map(toISODate)
        : range?.from && range.to ? [`${toISODate(range.from)}/${toISODate(range.to)}`] : [];

  const hooks = React.useMemo<DayHooks>(() => ({ preview, page, renderDay, dayClassName, describeDay }), [renderDay, dayClassName, describeDay]);

  return (
    <ModeContext.Provider value={mode}>
    <DayContext.Provider value={hooks}>
    <div
      ref={useMergedRef(ref, root)}
      data-slot="calendar"
      data-layout={layout}
      data-disabled={disabled || undefined}
      data-invalid={problem ? "" : undefined}
      dir={dir}
      className={cn(
        "relative inline-flex flex-col text-foreground [--calendar-bg:var(--card)] [--calendar-cell:2.5rem]",
        "[--calendar-band:color-mix(in_oklab,var(--primary)_14%,var(--calendar-bg))] [--calendar-band-edge:color-mix(in_oklab,var(--primary)_50%,var(--calendar-bg))]",
        scroll && "w-[calc(var(--calendar-cell)*7+1rem)]",
        scroll && weekNumbers && "w-[calc(var(--calendar-cell)*7+2.75rem)]",
        className
      )}
      role="group"
      {...rest}
      onPointerLeave={(e) => {
        preview(null);
        rest.onPointerLeave?.(e);
      }}
    >
      {scroll && (
        <div
          data-slot="calendar-weekdays"
          aria-hidden
          className={cn(weekNumbers ? gridWithWeeks : grid, "border-b border-border px-2 pb-2 text-center text-xs text-muted-foreground")}
        >
          {weekNumbers && <span />}
          {weekdayNames.map((d) => (
            <span key={d.getDay()}>{format(d, "EEEEEE", { locale })}</span>
          ))}
        </div>
      )}
      <div
        ref={scroller}
        data-slot="calendar-scroller"
        onScroll={grow}
        className={cn(scroll && "h-[var(--calendar-height,22.5rem)] overflow-y-auto overflow-x-hidden overscroll-contain px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden")}
      >
        <DayPicker
          mode="multiple"
          selected={picked}
          // RDP only treats `selected` as controlled when it is given an onSelect.
          onSelect={noop}
          month={span.start}
          onMonthChange={(m) => {
            if (scroll) goTo(m, true);
            else setSpan({ start: m, end: addMonths(m, numberOfMonths - 1) });
          }}
          numberOfMonths={scroll ? count : numberOfMonths}
          startMonth={min}
          endMonth={max}
          hideNavigation={scroll}
          hideWeekdays={scroll}
          showOutsideDays={false}
          showWeekNumber={weekNumbers}
          ISOWeek={weekNumbers && weekStartsOn === 1}
          weekStartsOn={weekStartsOn}
          locale={locale}
          dir={dir}
          today={today}
          disabled={disabledDay}
          modifiers={modifiers}
          onDayClick={(day, m, e) => !m.disabled && pick(day, e)}
          onDayFocus={(day) => preview(day)}
          components={{
            Day: CalendarDay,
            DayButton: CalendarDayButton,
            Month: CalendarMonth,
            MonthCaption,
            MonthGrid: CalendarMonthGrid,
            Nav: CalendarNav,
          }}
          classNames={{
            root: "relative",
            months: cn("flex", scroll ? "flex-col" : "gap-6"),
            // The last month before max fills the scroller, so its heading can reach the top.
            month: cn("flex flex-col", scroll && max && span.end >= addMonths(max, 0) && "last:min-h-[var(--calendar-height,22.5rem)]"),
            month_grid: "w-full border-collapse",
            weekdays: weekNumbers ? gridWithWeeks : grid,
            weekday: "pb-2 text-center text-xs font-normal text-muted-foreground",
            weeks: "flex flex-col gap-0.5 pb-2",
            week: cn(weekNumbers ? gridWithWeeks : grid, "[&>td]:p-0"),
            week_number_header: "w-6",
            week_number: "flex items-center justify-center text-[0.6875rem] tabular-nums text-muted-foreground",
            day: "p-0 text-center",
            nav: "pointer-events-none absolute inset-x-0 top-0 z-10 flex h-9 items-center justify-between",
          }}
        />
      </div>
      {scroll && todayInRange && (
        <button
          type="button"
          data-slot="calendar-today"
          hidden={!todayHidden}
          tabIndex={todayHidden ? 0 : -1}
          onClick={() => goTo(today, true)}
          className={cn(
            "absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full border border-border bg-background px-3 py-1 text-xs font-medium shadow-sm",
            "transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
            "hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          )}
        >
          Today
        </button>
      )}
      {name && (values.length ? values : [""]).map((v, i) => <input key={i} type="hidden" name={name} value={v} required={required} />)}
    </div>
    </DayContext.Provider>
    </ModeContext.Provider>
  );
});
Calendar.displayName = "Calendar";

export {
  Calendar,
  parseDate,
  dayFirst,
  startOfDay,
  addDays,
  addMonths,
  isSameDay,
  daysBetween,
  monthsBetween,
  isoWeek,
  toISODate,
  fromISODate,
};
```
