# Date picker

> A field that opens a month calendar to pick one date or a range, with presets, a month and year jump and a footer, in a popover on wide screens and a sheet on phones.

Docs: https://plumbago.ochotzas.com/components/date-picker

## Installation

```sh
npx plumbago add date-picker
```

This copies `components/ui/date-picker.tsx` into your project, along with `blur-swap`, `cn`, `morph`, `button`, `island`, `sheet`, and installs `@base-ui/react`.

## Usage

```tsx
import { DatePicker } from "@/components/ui/date-picker"

<DatePicker placeholder="Pick a date" onValueChange={(date) => console.log(date)} />
```

## Examples

### Preview

```tsx
import { DatePicker } from "@/components/ui/date-picker"

export default function DatePickerDemo() {
  return (
    <div className="w-full max-w-80">
      <DatePicker aria-label="Booking date" placeholder="Book a table for" clearable />
    </div>
  )
}
```

### Calendar

```tsx
import { Calendar } from "@/components/ui/date-picker"
import { Island } from "@/components/ui/island"

export default function DatePickerCalendar() {
  return (
    <Island className="w-full max-w-sm">
      <Calendar aria-label="Reservation date" defaultValue={new Date()} />
    </Island>
  )
}
```

### Range

```tsx
import { DatePicker } from "@/components/ui/date-picker"

export default function DatePickerRange() {
  return (
    <div className="w-full max-w-80">
      <DatePicker
        mode="range"
        aria-label="Holiday closure"
        placeholder="Holiday closure"
        clearable
        rangeSuffix={(nights) => (nights < 1 ? null : `${nights + 1} days closed`)}
      />
    </div>
  )
}
```

### Presets

```tsx
import { DatePicker, type DatePreset } from "@/components/ui/date-picker"

const day = (offset: number) => {
  const date = new Date()
  date.setDate(date.getDate() + offset)
  return date
}

const saturday = () => day((6 - new Date().getDay() + 7) % 7 || 7)

const presets: DatePreset[] = [
  { label: "Today", date: day(0) },
  { label: "Tomorrow", date: day(1) },
  { label: "This weekend", date: saturday() },
  { label: "Next week", date: day(7) },
]

export default function DatePickerPresets() {
  return (
    <div className="w-full max-w-80">
      <DatePicker aria-label="Booking date" placeholder="Book a table for" presets={presets} />
    </div>
  )
}
```

### Unavailable days

```tsx
import { DatePicker } from "@/components/ui/date-picker"

const fullyBooked = new Set([3, 4, 10, 11, 17, 18, 24, 25])

const isFullyBooked = (date: Date) => date.getDay() === 1 || fullyBooked.has(date.getDate())

export default function DatePickerUnavailableDays() {
  return (
    <div className="w-full max-w-80">
      <DatePicker aria-label="Booking date" placeholder="Closed Mondays, some nights full" isDateUnavailable={isFullyBooked} />
    </div>
  )
}
```

### Date and time

```tsx
import { DatePicker } from "@/components/ui/date-picker"
import { FieldLabel, FieldRoot } from "@/components/ui/field"
import { TimePicker } from "@/components/ui/time-picker"
import { useState } from "react"

const inWords = new Intl.DateTimeFormat("en-GB", { weekday: "long", day: "numeric", month: "long" })

export default function DatePickerDateAndTime() {
  const [date, setDate] = useState<Date | null>(null)
  const [time, setTime] = useState<string | null>("19:30")
  const reservation = date && time ? `${inWords.format(date)} at ${time}` : "Choose a date and a time"

  return (
    <div className="flex w-full max-w-80 flex-col gap-4">
      <FieldRoot>
        <FieldLabel id="reservation-date-label" nativeLabel={false} render={<div />}>
          Reservation
        </FieldLabel>
        <div className="grid grid-cols-[minmax(0,1fr)_8.5rem] gap-2">
          <DatePicker aria-labelledby="reservation-date-label" placeholder="Date" value={date} onValueChange={setDate} />
          <TimePicker aria-label="Time" value={time} onValueChange={setTime} minuteStep={15} min="17:00" max="22:30" />
        </div>
      </FieldRoot>
      <p
        key={reservation}
        aria-live="polite"
        className="text-footnote text-ink-2 transition-[opacity,translate,scale,filter] duration-spring ease-spring starting:translate-y-1.5 starting:scale-98 starting:opacity-0 starting:blur-[8px] motion-reduce:starting:translate-y-0 motion-reduce:starting:scale-100 motion-reduce:starting:blur-none"
      >
        {reservation}
      </p>
    </div>
  )
}
```

### With a label

```tsx
import { DatePicker } from "@/components/ui/date-picker"
import { FieldDescription, FieldLabel, FieldRoot } from "@/components/ui/field"

export default function DatePickerWithALabel() {
  return (
    <FieldRoot className="max-w-80">
      <FieldLabel id="tasting-date-label" nativeLabel={false} render={<div />}>
        Tasting menu date
      </FieldLabel>
      <DatePicker name="tasting-date" aria-labelledby="tasting-date-label" aria-describedby="tasting-date-help" placeholder="Choose a date" />
      <FieldDescription id="tasting-date-help">We serve the tasting menu on Fridays and Saturdays.</FieldDescription>
    </FieldRoot>
  )
}
```

## Built on Base UI

Date picker wraps these Base UI parts and keeps their props:

- [Popover](https://base-ui.com/react/components/popover)

## Source

```tsx
import { Popover } from "@base-ui/react/popover"
import { BlurSwap } from "@/lib/blur-swap"
import { cn } from "@/lib/cn"
import { morphColor, morphFromTrigger, morphPanel } from "@/lib/morph"
import { Button } from "@/components/ui/button"
import { Island } from "@/components/ui/island"
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"
import { type KeyboardEvent, type ReactNode, useEffect, useId, useRef, useState, useSyncExternalStore } from "react"

export type DateRange = { start: Date | null; end: Date | null }

export type DatePreset = { label: string; date?: Date; range?: { start: Date; end: Date } }

type SingleSelection = {
  mode?: "single"
  value?: Date | null
  defaultValue?: Date | null
  onValueChange?: (value: Date | null) => void
}

type RangeSelection = {
  mode: "range"
  value?: DateRange
  defaultValue?: DateRange
  onValueChange?: (value: DateRange) => void
}

type Selection = DateRange

type DateOptions = {
  locale?: string
  min?: Date
  max?: Date
  isDateUnavailable?: (date: Date) => boolean
  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6
}

type DisplayOptions = {
  showOutsideDays?: boolean
  rangeSuffix?: (nights: number) => string | null
}

const emptySelection: Selection = { start: null, end: null }
const gridCellCount = 42
const slotNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
const monthNumbers = slotNumbers
const millisecondsPerDay = 86_400_000

const startOfDay = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate())
const startOfMonth = (date: Date) => new Date(date.getFullYear(), date.getMonth(), 1)
const addDays = (date: Date, amount: number) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount)
const daysInMonth = (date: Date) => new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
const isSameDay = (a: Date | null, b: Date | null) => a !== null && b !== null && a.getTime() === b.getTime()
const monthIndex = (date: Date) => date.getFullYear() * 12 + date.getMonth()
const monthFromIndex = (index: number) => new Date(Math.floor(index / 12), index % 12, 1)
const pad = (value: number) => String(value).padStart(2, "0")
const toIso = (date: Date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
const nightsBetween = (start: Date, end: Date) => Math.round((end.getTime() - start.getTime()) / millisecondsPerDay)

function addMonths(date: Date, amount: number) {
  const target = new Date(date.getFullYear(), date.getMonth() + amount, 1)
  target.setDate(Math.min(date.getDate(), daysInMonth(target)))
  return target
}

function toSelection(value: Date | DateRange | null | undefined): Selection {
  if (value === null || value === undefined) return emptySelection
  if (value instanceof Date) return { start: startOfDay(value), end: null }
  return { start: value.start && startOfDay(value.start), end: value.end && startOfDay(value.end) }
}

function useSelectionState(props: SingleSelection | RangeSelection) {
  const [internal, setInternal] = useState(() => toSelection(props.defaultValue))
  const controlled = props.value !== undefined
  const selection = controlled ? toSelection(props.value) : internal
  const mode = props.mode === "range" ? "range" : "single"

  const set = (next: Selection) => {
    if (!controlled) setInternal(next)
    if (props.mode === "range") props.onValueChange?.(next)
    else props.onValueChange?.(next.start)
  }

  const pick = (date: Date) => {
    let next: Selection
    if (mode === "single") next = { start: date, end: null }
    else if (selection.start && !selection.end && date.getTime() >= selection.start.getTime()) next = { start: selection.start, end: date }
    else next = { start: date, end: null }
    set(next)
    return next
  }

  return { mode, selection, pick, set } as const
}

function weekStartOf(locale: string | undefined, override: number | undefined) {
  if (override !== undefined) return override
  try {
    const resolved = new Intl.Locale(locale ?? (typeof navigator === "undefined" ? "en" : navigator.language)) as unknown as {
      getWeekInfo?: () => { firstDay: number }
      weekInfo?: { firstDay: number }
    }
    const firstDay = (resolved.getWeekInfo?.() ?? resolved.weekInfo)?.firstDay
    return firstDay === undefined ? 1 : firstDay % 7
  } catch {
    return 1
  }
}

function useCalendarFormat(locale: string | undefined) {
  const format = (options: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, options)
  return {
    monthTitle: format({ month: "long", year: "numeric" }),
    fullDate: format({ dateStyle: "full" }),
    shortWeekday: format({ weekday: "short" }),
    longWeekday: format({ weekday: "long" }),
    inWords: format({ weekday: "long", day: "numeric", month: "long" }),
    inWordsShort: format({ weekday: "short", day: "numeric", month: "long" }),
    rangeWords: format({ day: "numeric", month: "long" }),
    shortMonth: format({ month: "short" }),
    longMonth: format({ month: "long" }),
  }
}

function defaultRangeSuffix(nights: number) {
  if (nights < 1) return null
  return nights === 1 ? "1 night" : `${nights} nights`
}

function availability({ min, max, isDateUnavailable }: Pick<DateOptions, "min" | "max" | "isDateUnavailable">) {
  const minDay = min && startOfDay(min)
  const maxDay = max && startOfDay(max)
  const unavailable = (date: Date) => (minDay !== undefined && date < minDay) || (maxDay !== undefined && date > maxDay) || (isDateUnavailable?.(date) ?? false)
  const clamp = (date: Date) => (minDay !== undefined && date < minDay ? minDay : maxDay !== undefined && date > maxDay ? maxDay : date)
  return { minDay, maxDay, unavailable, clamp }
}

type CalendarBaseProps = DateOptions &
  DisplayOptions & {
    mode: "single" | "range"
    selection: Selection
    onPick: (date: Date) => void
    numberOfMonths: number
    showFooter: boolean
    defaultMonth?: Date
    autoFocus?: boolean
    className?: string
    "aria-label"?: string
  }

type View = { month: Date; focus: Date; direction?: "next" | "prev" }
type PickerState = { open: boolean; year: number; direction?: "next" | "prev" }

function CalendarBase({
  mode,
  selection,
  onPick,
  numberOfMonths,
  showFooter,
  showOutsideDays = true,
  rangeSuffix = defaultRangeSuffix,
  defaultMonth,
  autoFocus,
  locale,
  min,
  max,
  isDateUnavailable,
  weekStartsOn,
  className,
  "aria-label": ariaLabel,
}: CalendarBaseProps) {
  const format = useCalendarFormat(locale)
  const weekStart = weekStartOf(locale, weekStartsOn)
  const baseId = useId()
  const sectionRef = useRef<HTMLElement | null>(null)
  const focusRequested = useRef(autoFocus ?? false)
  const captionFocusRequested = useRef(false)
  const pickerFocusRequested = useRef(false)
  const [hovered, setHovered] = useState<Date | null>(null)
  const [view, setView] = useState<View>(() => {
    const anchor = selection.start ?? defaultMonth ?? startOfDay(new Date())
    return { month: startOfMonth(anchor), focus: anchor }
  })
  const [picker, setPicker] = useState<PickerState>({ open: false, year: view.month.getFullYear() })
  const [seenAnchor, setSeenAnchor] = useState(selection.start?.getTime() ?? null)

  const today = startOfDay(new Date())
  const { minDay, maxDay, unavailable, clamp } = availability({ min, max, isDateUnavailable })
  const firstIndex = monthIndex(view.month)

  const showDate = (date: Date, focus: boolean) => {
    const target = clamp(date)
    const targetIndex = monthIndex(target)
    if (focus) focusRequested.current = true
    setView((current) => {
      const currentFirst = monthIndex(current.month)
      const currentLast = currentFirst + numberOfMonths - 1
      if (targetIndex >= currentFirst && targetIndex <= currentLast) return { ...current, focus: target }
      return {
        month: monthFromIndex(targetIndex < currentFirst ? targetIndex : targetIndex - numberOfMonths + 1),
        focus: target,
        direction: targetIndex > currentLast ? "next" : "prev",
      }
    })
  }

  const anchorTime = selection.start?.getTime() ?? null
  if (anchorTime !== seenAnchor) {
    setSeenAnchor(anchorTime)
    if (selection.start) showDate(selection.start, false)
  }

  useEffect(() => {
    if (focusRequested.current) {
      focusRequested.current = false
      sectionRef.current?.querySelector<HTMLElement>(`[data-slot="calendar-day"][data-date="${toIso(view.focus)}"]`)?.focus({ preventScroll: true })
    }
    if (captionFocusRequested.current) {
      captionFocusRequested.current = false
      sectionRef.current?.querySelector<HTMLElement>('[data-slot="calendar-caption"]')?.focus({ preventScroll: true })
    }
    if (pickerFocusRequested.current) {
      pickerFocusRequested.current = false
      sectionRef.current?.querySelector<HTMLElement>('[data-slot="calendar-month-option"][aria-current="true"]')?.focus({ preventScroll: true })
    }
  })

  const shiftMonths = (amount: number) => {
    const nextFocus = clamp(addMonths(view.focus, amount))
    setView({ month: addMonths(view.month, amount), focus: nextFocus, direction: amount > 0 ? "next" : "prev" })
  }

  const jumpToMonth = (target: Date) => {
    const day = Math.min(view.focus.getDate(), daysInMonth(target))
    const nextFocus = clamp(new Date(target.getFullYear(), target.getMonth(), day))
    const nextIndex = monthIndex(nextFocus)
    setView((current) => ({
      month: monthFromIndex(nextIndex),
      focus: nextFocus,
      direction: nextIndex === monthIndex(current.month) ? current.direction : nextIndex > monthIndex(current.month) ? "next" : "prev",
    }))
  }

  const canGoBack = minDay === undefined || addDays(view.month, -1) >= minDay
  const canGoForward = maxDay === undefined || new Date(view.month.getFullYear(), view.month.getMonth() + numberOfMonths, 1) <= maxDay

  const openPicker = () => {
    pickerFocusRequested.current = true
    setPicker({ open: true, year: view.month.getFullYear() })
  }

  const closePicker = () => {
    captionFocusRequested.current = true
    setPicker((current) => ({ ...current, open: false }))
  }

  const changePickerYear = (amount: number) => setPicker((current) => ({ ...current, year: current.year + amount, direction: amount > 0 ? "next" : "prev" }))

  const chooseMonth = (month: number) => {
    jumpToMonth(new Date(picker.year, month, 1))
    closePicker()
  }

  const monthOptionDisabled = (month: number) => {
    const index = picker.year * 12 + month
    return (minDay !== undefined && index < monthIndex(minDay)) || (maxDay !== undefined && index > monthIndex(maxDay))
  }

  const canGoPreviousYear = minDay === undefined || picker.year > minDay.getFullYear()
  const canGoNextYear = maxDay === undefined || picker.year < maxDay.getFullYear()

  const onPickerKeyDown = (event: KeyboardEvent<HTMLElement>) => {
    if (event.key === "Escape") {
      event.preventDefault()
      event.stopPropagation()
      closePicker()
      return
    }
    const moves: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -3, ArrowDown: 3 }
    const step = moves[event.key]
    const current = Number((event.target as HTMLElement).dataset.month)
    if (step === undefined || Number.isNaN(current)) return
    event.preventDefault()
    let next = current + step
    while (next >= 0 && next < 12 && monthOptionDisabled(next)) next += step
    if (next < 0 || next > 11) return
    sectionRef.current?.querySelector<HTMLElement>(`[data-slot="calendar-month-option"][data-month="${next}"]`)?.focus()
  }

  const weekdayOffsets = Array.from({ length: 7 }, (_, index) => (weekStart + index) % 7)
  const weekdayDate = (weekday: number) => new Date(2023, 0, 1 + weekday)

  const previewEnd = mode === "range" && selection.start && !selection.end && hovered && hovered > selection.start ? hovered : null
  const rangeStart = mode === "range" ? selection.start : null
  const rangeEnd = mode === "range" ? (selection.end ?? previewEnd) : null
  const hasBand = rangeStart !== null && rangeEnd !== null && rangeEnd > rangeStart

  const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
    const weekdayIndex = (view.focus.getDay() - weekStart + 7) % 7
    const moves: Record<string, Date> = {
      ArrowLeft: addDays(view.focus, -1),
      ArrowRight: addDays(view.focus, 1),
      ArrowUp: addDays(view.focus, -7),
      ArrowDown: addDays(view.focus, 7),
      PageUp: addMonths(view.focus, event.shiftKey ? -12 : -1),
      PageDown: addMonths(view.focus, event.shiftKey ? 12 : 1),
      Home: addDays(view.focus, -weekdayIndex),
      End: addDays(view.focus, 6 - weekdayIndex),
    }
    const target = moves[event.key]
    if (!target) return
    event.preventDefault()
    showDate(target, true)
  }

  const pickDate = (date: Date, outside: boolean) => {
    if (unavailable(date)) return
    if (outside) showDate(date, true)
    else setView((current) => ({ ...current, focus: date }))
    onPick(date)
  }

  const summary = describeSelection({ mode, selection, format, rangeSuffix })
  const todayUnavailable = unavailable(today)
  const goToToday = () => (mode === "single" ? pickDate(today, false) : showDate(today, true))
  const multiple = numberOfMonths > 1
  const headingId = (slot: number) => `${baseId}-title-${slot}`

  return (
    <section
      ref={sectionRef}
      data-slot="calendar"
      aria-label={ariaLabel}
      aria-labelledby={ariaLabel ? undefined : headingId(0)}
      className={cn("flex min-w-0 flex-col gap-3", multiple ? "w-fit max-w-full" : "w-full max-w-88", className)}
    >
      <div data-slot="calendar-body" className="relative">
        <div
          data-slot="calendar-months"
          data-hidden={picker.open ? "" : undefined}
          inert={picker.open ? true : undefined}
          className={cn(
            "flex gap-6 transition-[opacity,translate,scale,filter] duration-spring ease-spring",
            "delay-100 data-hidden:pointer-events-none data-hidden:scale-98 data-hidden:opacity-0 data-hidden:delay-0 data-hidden:duration-fast data-hidden:ease-in motion-safe:data-hidden:blur-[8px] motion-safe:data-hidden:-translate-y-1",
          )}
        >
          {slotNumbers.slice(0, numberOfMonths).map((slot) => {
            const month = monthFromIndex(firstIndex + slot)
            const leadingBlanks = (month.getDay() - weekStart + 7) % 7
            const first = slot === 0
            const last = slot === numberOfMonths - 1
            const cells = Array.from({ length: gridCellCount }, (_, index) => {
              const date = new Date(month.getFullYear(), month.getMonth(), index - leadingBlanks + 1)
              const outside = date.getMonth() !== month.getMonth()
              const before = date < month
              const visible = !outside || (showOutsideDays && ((before && first) || (!before && last)))
              return { index, date, outside, visible }
            })
            const rows = Array.from({ length: gridCellCount / 7 }, (_, row) => cells.slice(row * 7, row * 7 + 7))
            return (
              <div key={slot} data-slot="calendar-month" className={cn("flex min-w-0 flex-col gap-3", multiple ? "w-70 shrink-0" : "w-full")}>
                <div data-slot="calendar-header" className={cn("flex items-center gap-1", !multiple && "pl-1")}>
                  {multiple &&
                    (first ? (
                      <NavButton label="Previous month" disabled={!canGoBack} onClick={() => shiftMonths(-1)}>
                        <path d="m15 5-7 7 7 7" />
                      </NavButton>
                    ) : (
                      <span className="size-9 shrink-0" />
                    ))}
                  <button
                    type="button"
                    data-slot="calendar-caption"
                    aria-expanded={picker.open}
                    aria-haspopup="dialog"
                    aria-label={`${format.monthTitle.format(month)}, choose month and year`}
                    onClick={openPicker}
                    className={cn(
                      "relative flex h-9 min-w-0 cursor-pointer items-center gap-1 rounded-full px-3 text-headline font-semibold text-ink outline-none",
                      "transition-[background-color,scale] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press [-webkit-tap-highlight-color:transparent]",
                      multiple ? "mx-auto" : "-ml-3 mr-auto",
                    )}
                  >
                    <BlurSwap id={headingId(slot)} text={format.monthTitle.format(month)} live className="min-w-0" />
                    <svg
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                      className="size-4 shrink-0 fill-none stroke-ink-3"
                      strokeWidth="1.75"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <path d="m7 10 5 5 5-5" />
                    </svg>
                  </button>
                  {!multiple && (
                    <NavButton label="Previous month" disabled={!canGoBack} onClick={() => shiftMonths(-1)}>
                      <path d="m15 5-7 7 7 7" />
                    </NavButton>
                  )}
                  {(!multiple || last) && (
                    <NavButton label="Next month" disabled={!canGoForward} onClick={() => shiftMonths(1)}>
                      <path d="m9 5 7 7-7 7" />
                    </NavButton>
                  )}
                  {multiple && !last && <span className="size-9 shrink-0" />}
                </div>
                <table aria-labelledby={headingId(slot)} onKeyDown={onKeyDown} onPointerLeave={() => setHovered(null)} className="block w-full">
                  <thead className="block pb-1">
                    <tr className="grid grid-cols-[repeat(7,minmax(0,1fr))]">
                      {weekdayOffsets.map((weekday) => (
                        <th
                          key={weekday}
                          scope="col"
                          aria-label={format.longWeekday.format(weekdayDate(weekday))}
                          className="grid h-8 place-items-center text-caption font-semibold text-ink-2"
                        >
                          {format.shortWeekday.format(weekdayDate(weekday)).slice(0, 2)}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody
                    key={monthIndex(month)}
                    data-slot="calendar-grid"
                    data-direction={view.direction}
                    className={cn(
                      "flex flex-col gap-1 transition-[opacity,translate,filter] duration-spring ease-spring starting:data-direction:opacity-0 motion-safe:starting:data-direction:blur-[8px]",
                      "starting:data-[direction=next]:translate-x-[18px] starting:data-[direction=prev]:-translate-x-[18px]",
                      "motion-reduce:starting:data-[direction=next]:translate-x-0 motion-reduce:starting:data-[direction=prev]:translate-x-0",
                    )}
                  >
                    {rows.map((row) => (
                      <tr key={row[0]?.index} className="grid grid-cols-[repeat(7,minmax(0,1fr))]">
                        {row.map(({ index, date, outside, visible }, column) => {
                          if (!visible) return <td key={index} aria-hidden="true" className="aspect-square max-h-11" />
                          const isStart = isSameDay(date, rangeStart)
                          const isEnd = isSameDay(date, rangeEnd)
                          const isSelected = mode === "single" ? isSameDay(date, selection.start) : isStart || isSameDay(date, selection.end)
                          const inBand = hasBand && rangeStart !== null && rangeEnd !== null && date >= rangeStart && date <= rangeEnd
                          const previous = row[column - 1]
                          const following = row[column + 1]
                          return (
                            <DayCell
                              key={index}
                              date={date}
                              label={format.fullDate.format(date)}
                              outside={outside}
                              selected={isSelected}
                              today={isSameDay(date, today)}
                              unavailable={unavailable(date)}
                              booked={isDateUnavailable?.(date) ?? false}
                              tabStop={isSameDay(date, view.focus)}
                              bandBefore={inBand && !(isStart && hasBand)}
                              bandAfter={inBand && !(isEnd && hasBand)}
                              roundBefore={column === 0 || !previous?.visible}
                              roundAfter={column === 6 || !following?.visible}
                              onPick={() => pickDate(date, outside)}
                              onHover={() => setHovered(date)}
                              onFocusDay={() => {
                                setHovered(date)
                                setView((current) => (isSameDay(current.focus, date) ? current : { ...current, focus: date }))
                              }}
                            />
                          )
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )
          })}
        </div>
        <div
          data-slot="calendar-picker"
          role="dialog"
          aria-label="Choose month and year"
          data-hidden={picker.open ? undefined : ""}
          inert={picker.open ? undefined : true}
          onKeyDown={onPickerKeyDown}
          className={cn(
            "absolute inset-0 flex justify-center transition-[opacity,translate,scale,filter] duration-spring ease-spring",
            "delay-100 data-hidden:pointer-events-none data-hidden:translate-y-1.5 data-hidden:scale-98 data-hidden:opacity-0 data-hidden:delay-0 data-hidden:duration-fast data-hidden:ease-in motion-safe:data-hidden:blur-[8px]",
          )}
        >
          <div className="flex h-full w-full max-w-88 flex-col gap-3">
            <div data-slot="calendar-header" className="flex items-center gap-1 pl-1">
              <button
                type="button"
                data-slot="calendar-caption"
                aria-label={`${picker.year}, back to days`}
                onClick={closePicker}
                className={cn(
                  "relative -ml-3 mr-auto flex h-9 min-w-0 cursor-pointer items-center gap-1 rounded-full px-3 text-headline font-semibold text-ink outline-none",
                  "transition-[background-color,scale] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press [-webkit-tap-highlight-color:transparent]",
                )}
              >
                <BlurSwap text={String(picker.year)} className="min-w-0 tabular-nums" />
                <svg
                  viewBox="0 0 24 24"
                  aria-hidden="true"
                  className="size-4 shrink-0 rotate-180 fill-none stroke-ink-3"
                  strokeWidth="1.75"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="m7 10 5 5 5-5" />
                </svg>
              </button>
              <NavButton label="Previous year" disabled={!canGoPreviousYear} onClick={() => changePickerYear(-1)}>
                <path d="m15 5-7 7 7 7" />
              </NavButton>
              <NavButton label="Next year" disabled={!canGoNextYear} onClick={() => changePickerYear(1)}>
                <path d="m9 5 7 7-7 7" />
              </NavButton>
            </div>
            <div
              key={picker.year}
              data-slot="calendar-months-grid"
              data-direction={picker.direction}
              className={cn(
                "grid flex-1 grid-cols-3 grid-rows-4 gap-1 transition-[opacity,translate,filter] duration-spring ease-spring starting:data-direction:opacity-0 motion-safe:starting:data-direction:blur-[8px]",
                "starting:data-[direction=next]:translate-x-[18px] starting:data-[direction=prev]:-translate-x-[18px]",
                "motion-reduce:starting:data-[direction=next]:translate-x-0 motion-reduce:starting:data-[direction=prev]:translate-x-0",
              )}
            >
              {monthNumbers.map((month) => {
                const date = new Date(picker.year, month, 1)
                const isCurrent = picker.year === view.month.getFullYear() && month === view.month.getMonth()
                const isThisMonth = picker.year === today.getFullYear() && month === today.getMonth()
                return (
                  <button
                    key={month}
                    type="button"
                    data-slot="calendar-month-option"
                    data-month={month}
                    data-selected={isCurrent ? "" : undefined}
                    data-today={isThisMonth && !isCurrent ? "" : undefined}
                    aria-current={isCurrent ? "true" : undefined}
                    aria-label={`${format.longMonth.format(date)} ${picker.year}`}
                    aria-disabled={monthOptionDisabled(month) || undefined}
                    tabIndex={isCurrent ? 0 : -1}
                    onClick={() => !monthOptionDisabled(month) && chooseMonth(month)}
                    className={cn(
                      "relative grid cursor-pointer place-items-center rounded-md text-body text-ink outline-none select-none",
                      "transition-[background-color,color,scale] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press [-webkit-tap-highlight-color:transparent]",
                      "data-today:font-semibold data-today:text-accent data-selected:bg-ink data-selected:font-medium data-selected:text-on-ink data-selected:hover:bg-ink",
                      "aria-disabled:cursor-default aria-disabled:text-ink-3 aria-disabled:hover:bg-transparent aria-disabled:active:scale-100",
                    )}
                  >
                    {format.shortMonth.format(date)}
                  </button>
                )
              })}
            </div>
          </div>
        </div>
      </div>
      {showFooter && (
        <div data-slot="calendar-footer" className="-mb-1 flex items-center justify-between gap-3 border-t border-line pt-3">
          <BlurSwap text={summary} live className="min-w-0 flex-1 text-footnote text-ink-2" />
          <Button variant="plain" size="sm" disabled={todayUnavailable} onClick={goToToday} className="-mr-2 shrink-0 px-3 text-accent">
            Today
          </Button>
        </div>
      )}
    </section>
  )
}

type DayCellProps = {
  date: Date
  label: string
  outside: boolean
  selected: boolean
  today: boolean
  unavailable: boolean
  booked: boolean
  tabStop: boolean
  bandBefore: boolean
  bandAfter: boolean
  roundBefore: boolean
  roundAfter: boolean
  onPick: () => void
  onHover: () => void
  onFocusDay: () => void
}

const bandHalf =
  "pointer-events-none absolute inset-y-0 w-1/2 scale-x-50 bg-track opacity-0 transition-[opacity,scale] duration-base ease-in data-band:scale-x-100 data-band:opacity-100 data-band:duration-spring data-band:ease-spring"

function DayCell({
  date,
  label,
  outside,
  selected,
  today,
  unavailable,
  booked,
  tabStop,
  bandBefore,
  bandAfter,
  roundBefore,
  roundAfter,
  onPick,
  onHover,
  onFocusDay,
}: DayCellProps) {
  return (
    <td data-slot="calendar-cell" className="relative aspect-square max-h-11">
      <span
        aria-hidden="true"
        data-band={bandBefore ? "" : undefined}
        className={cn(bandHalf, "origin-right", roundBefore ? "left-0 rounded-l-full" : "-left-px w-[calc(50%+1px)]")}
      />
      <span
        aria-hidden="true"
        data-band={bandAfter ? "" : undefined}
        className={cn(bandHalf, "origin-left", roundAfter ? "right-0 rounded-r-full" : "-right-px w-[calc(50%+1px)]")}
      />
      <button
        type="button"
        data-slot="calendar-day"
        data-date={toIso(date)}
        data-selected={selected ? "" : undefined}
        data-today={today && !selected ? "" : undefined}
        data-outside={outside ? "" : undefined}
        aria-label={label}
        aria-pressed={selected}
        aria-current={today ? "date" : undefined}
        data-booked={booked ? "" : undefined}
        aria-disabled={unavailable || undefined}
        tabIndex={tabStop ? 0 : -1}
        onClick={onPick}
        onFocus={onFocusDay}
        onPointerEnter={onHover}
        className={cn(
          "group relative mx-auto grid aspect-square h-full max-h-11 w-auto max-w-full cursor-pointer place-items-center rounded-full text-body tabular-nums outline-none select-none",
          "transition-[background-color,color,scale] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press [-webkit-tap-highlight-color:transparent]",
          outside ? "text-ink-3" : "text-ink",
          "data-today:font-semibold data-today:text-accent",
          "data-selected:font-medium data-selected:text-on-ink data-selected:hover:bg-transparent",
          "aria-disabled:cursor-default aria-disabled:text-ink-3 data-booked:line-through aria-disabled:hover:bg-transparent aria-disabled:active:scale-100",
        )}
      >
        <span
          aria-hidden="true"
          data-slot="calendar-day-fill"
          className={cn(
            "absolute inset-0 scale-80 rounded-full bg-ink opacity-0 transition-[opacity,scale,filter] duration-base ease-in motion-safe:blur-[2px]",
            "group-data-selected:scale-100 group-data-selected:opacity-100 group-data-selected:blur-none group-data-selected:duration-spring group-data-selected:ease-spring",
          )}
        />
        <span className="relative">{date.getDate()}</span>
      </button>
    </td>
  )
}

function describeSelection({
  mode,
  selection,
  format,
  rangeSuffix,
}: {
  mode: "single" | "range"
  selection: Selection
  format: ReturnType<typeof useCalendarFormat>
  rangeSuffix: (nights: number) => string | null
}) {
  const { start, end } = selection
  if (!start) return mode === "range" ? "No dates chosen" : "No date chosen"
  if (mode === "single") return format.inWords.format(start)
  if (!end) return `${format.inWordsShort.format(start)} · pick the last day`
  if (isSameDay(start, end)) return format.inWords.format(start)
  const suffix = rangeSuffix(nightsBetween(start, end))
  const words = format.rangeWords.formatRange(start, end)
  return suffix ? `${words} · ${suffix}` : words
}

function NavButton({ label, disabled, onClick, children }: { label: string; disabled: boolean; onClick: () => void; children: ReactNode }) {
  return (
    <button
      type="button"
      data-slot="calendar-nav"
      aria-label={label}
      disabled={disabled}
      onClick={onClick}
      className={cn(
        "relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full text-ink-2 outline-none after:absolute after:-inset-1",
        "transition-[background-color,scale,opacity] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press",
        "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent disabled:active:scale-100 [-webkit-tap-highlight-color:transparent]",
      )}
    >
      <svg viewBox="0 0 24 24" aria-hidden="true" className="size-5 fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        {children}
      </svg>
    </button>
  )
}

export type CalendarProps = (SingleSelection | RangeSelection) &
  DateOptions &
  DisplayOptions & {
    defaultMonth?: Date
    numberOfMonths?: number
    showFooter?: boolean
    className?: string
    "aria-label"?: string
  }

export function Calendar(props: CalendarProps) {
  const { mode, selection, pick } = useSelectionState(props)
  const { locale, min, max, isDateUnavailable, weekStartsOn, defaultMonth, className, showOutsideDays, rangeSuffix } = props
  return (
    <CalendarBase
      mode={mode}
      selection={selection}
      onPick={pick}
      numberOfMonths={Math.max(1, props.numberOfMonths ?? 1)}
      showFooter={props.showFooter ?? true}
      showOutsideDays={showOutsideDays}
      rangeSuffix={rangeSuffix}
      locale={locale}
      min={min}
      max={max}
      isDateUnavailable={isDateUnavailable}
      weekStartsOn={weekStartsOn}
      defaultMonth={defaultMonth}
      className={className}
      aria-label={props["aria-label"]}
    />
  )
}

const wideQuery = "(min-width: 640px)"

function useIsWide() {
  return useSyncExternalStore(
    (notify) => {
      const query = window.matchMedia(wideQuery)
      query.addEventListener("change", notify)
      return () => query.removeEventListener("change", notify)
    },
    () => window.matchMedia(wideQuery).matches,
    () => true,
  )
}

export type DatePickerProps = (SingleSelection | RangeSelection) &
  DateOptions &
  DisplayOptions & {
    placeholder?: string
    title?: string
    name?: string
    disabled?: boolean
    clearable?: boolean
    numberOfMonths?: number
    presets?: DatePreset[]
    open?: boolean
    defaultOpen?: boolean
    onOpenChange?: (open: boolean) => void
    id?: string
    "aria-label"?: string
    "aria-labelledby"?: string
    "aria-describedby"?: string
    className?: string
  }

function presetSelection(preset: DatePreset, mode: "single" | "range"): Selection {
  const start = startOfDay(preset.range?.start ?? preset.date ?? new Date())
  if (mode === "single") return { start, end: null }
  if (preset.range) return { start, end: startOfDay(preset.range.end) }
  return { start, end: start }
}

export function DatePicker(props: DatePickerProps) {
  const { mode, selection, pick, set } = useSelectionState(props)
  const { locale, min, max, isDateUnavailable, weekStartsOn, showOutsideDays, rangeSuffix, name, disabled, id, presets, className } = props
  const placeholder = props.placeholder ?? (mode === "range" ? "Pick dates" : "Pick a date")
  const [ownOpen, setOwnOpen] = useState(props.defaultOpen ?? false)
  const open = props.open ?? ownOpen
  const wide = useIsWide()
  const panelRef = useRef<HTMLDivElement | null>(null)
  const months = wide ? Math.max(1, props.numberOfMonths ?? (mode === "range" ? 2 : 1)) : 1

  const setOpen = (next: boolean) => {
    setOwnOpen(next)
    props.onOpenChange?.(next)
  }

  const medium = new Intl.DateTimeFormat(locale, { dateStyle: "medium" })
  const { start, end } = selection
  const valueText = start ? (end && !isSameDay(start, end) ? medium.formatRange(start, end) : medium.format(start)) : null
  const { unavailable } = availability({ min, max, isDateUnavailable })

  const handlePick = (date: Date) => {
    const next = pick(date)
    if (mode === "single" || next.end) setOpen(false)
  }

  const handlePreset = (preset: DatePreset) => {
    const next = presetSelection(preset, mode)
    set(next)
    if (mode === "single" || next.end) setOpen(false)
  }

  const focusDay = () => panelRef.current?.querySelector<HTMLElement>('[data-slot="calendar-day"][tabindex="0"]') ?? true

  const panel = (
    <div ref={panelRef} data-slot="date-picker-panel" className={cn("flex gap-4", wide ? "flex-row" : "flex-col")}>
      {presets && presets.length > 0 && (
        <div
          data-slot="date-picker-presets"
          className={cn("flex shrink-0 gap-0.5", wide ? "w-36 flex-col border-r border-line pr-4" : "grid grid-cols-2 border-b border-line pb-3")}
        >
          {presets.map((preset) => {
            const target = presetSelection(preset, mode)
            const active = isSameDay(selection.start, target.start) && isSameDay(selection.end, target.end)
            return (
              <button
                key={preset.label}
                type="button"
                data-slot="date-picker-preset"
                data-active={active ? "" : undefined}
                aria-disabled={(target.start !== null && unavailable(target.start)) || undefined}
                onClick={() => !(target.start !== null && unavailable(target.start)) && handlePreset(preset)}
                className={cn(
                  "relative flex h-11 cursor-pointer items-center rounded-sm px-3 text-left text-body text-ink outline-none select-none sm:h-10",
                  "transition-[background-color,scale] duration-fast ease-out hover:bg-press focus-visible:ring-2 focus-visible:ring-accent active:scale-press [-webkit-tap-highlight-color:transparent]",
                  "data-active:bg-press data-active:font-medium aria-disabled:cursor-default aria-disabled:text-ink-3 aria-disabled:hover:bg-transparent aria-disabled:active:scale-100",
                )}
              >
                {preset.label}
              </button>
            )
          })}
        </div>
      )}
      <CalendarBase
        mode={mode}
        selection={selection}
        onPick={handlePick}
        numberOfMonths={months}
        showFooter
        showOutsideDays={showOutsideDays}
        rangeSuffix={rangeSuffix}
        locale={locale}
        min={min}
        max={max}
        isDateUnavailable={isDateUnavailable}
        weekStartsOn={weekStartsOn}
        className={wide && months === 1 ? "w-77" : undefined}
        aria-label={props.title ?? "Choose a date"}
      />
    </div>
  )

  const triggerClassName = cn(
    "flex h-11 w-full cursor-pointer items-center justify-between gap-2 rounded-md bg-fill-field pr-3 pl-4 text-left text-body text-ink select-none [-webkit-tap-highlight-color:transparent]",
    "transition-shadow duration-fast ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent data-popup-open:ring-2 data-popup-open:ring-accent",
    "data-disabled:cursor-default data-disabled:opacity-40",
  )

  const triggerChildren = (
    <>
      <BlurSwap
        text={valueText ?? placeholder}
        muted={valueText === null}
        className={cn("min-w-0 flex-1 tabular-nums", props.clearable && start && !disabled && "mr-8")}
      />
      <CalendarIcon />
    </>
  )

  const triggerProps = {
    id,
    disabled,
    "data-slot": "date-picker-trigger",
    "aria-label": props["aria-label"],
    "aria-labelledby": props["aria-labelledby"],
    "aria-describedby": props["aria-describedby"],
    className: triggerClassName,
  }

  const hiddenInputs = name && (
    <>
      <input type="hidden" name={mode === "range" ? `${name}-start` : name} value={start ? toIso(start) : ""} />
      {mode === "range" && <input type="hidden" name={`${name}-end`} value={end ? toIso(end) : ""} />}
    </>
  )

  const clearButton = props.clearable && (
    <button
      type="button"
      data-slot="date-picker-clear"
      data-visible={start && !disabled ? "" : undefined}
      aria-label="Clear date"
      aria-hidden={start ? undefined : true}
      tabIndex={start && !disabled ? 0 : -1}
      onClick={() => set(emptySelection)}
      className={cn(
        "absolute top-1/2 right-11 grid size-6 -translate-y-1/2 scale-80 cursor-pointer place-items-center rounded-full bg-press text-ink-2 opacity-0 outline-none after:absolute after:-inset-2.5",
        "pointer-events-none transition-[opacity,scale,filter,background-color] duration-base ease-in motion-safe:blur-[2px] focus-visible:ring-2 focus-visible:ring-accent [-webkit-tap-highlight-color:transparent]",
        "data-visible:pointer-events-auto data-visible:scale-100 data-visible:opacity-100 data-visible:blur-none data-visible:duration-spring data-visible:ease-spring data-visible:active:scale-press",
      )}
    >
      <svg viewBox="0 0 24 24" aria-hidden="true" className="size-3.5 fill-none stroke-current" strokeWidth="2" strokeLinecap="round">
        <path d="m7 7 10 10M17 7 7 17" />
      </svg>
    </button>
  )

  if (!wide) {
    return (
      <div data-slot="date-picker" className={cn("relative w-full", className)}>
        <Sheet open={open} onOpenChange={setOpen}>
          <SheetTrigger {...triggerProps}>{triggerChildren}</SheetTrigger>
          <SheetContent title={props.title ?? "Choose a date"} initialFocus={focusDay}>
            <Island className="p-4">{panel}</Island>
          </SheetContent>
        </Sheet>
        {clearButton}
        {hiddenInputs}
      </div>
    )
  }

  return (
    <div data-slot="date-picker" className={cn("relative w-full", className)}>
      <Popover.Root open={open} onOpenChange={setOpen}>
        <Popover.Trigger {...triggerProps}>{triggerChildren}</Popover.Trigger>
        <Popover.Portal>
          <Popover.Positioner
            ref={morphColor}
            data-slot="date-picker-positioner"
            side="bottom"
            align="start"
            sideOffset={6}
            collisionPadding={8}
            className={cn(
              morphFromTrigger,
              "z-50 outline-none [--morph-radius-start:var(--pb-radius-md)] [--morph-radius-end:var(--pb-radius-lg)] [--morph-shape-start:squircle]",
            )}
          >
            <Popover.Popup
              data-slot="date-picker-popup"
              initialFocus={focusDay}
              className={cn("on-surface w-fit max-w-(--available-width) overflow-auto overscroll-contain rounded-lg p-4 text-ink outline-none", morphPanel)}
            >
              {panel}
            </Popover.Popup>
          </Popover.Positioner>
        </Popover.Portal>
      </Popover.Root>
      {clearButton}
      {hiddenInputs}
    </div>
  )
}

function CalendarIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className="size-5 shrink-0 fill-none stroke-ink-3"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect x="4" y="5.5" width="16" height="14.5" rx="3.5" />
      <path d="M4 10h16M8.5 3.5v4M15.5 3.5v4" />
    </svg>
  )
}
```
