{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-grid",
  "type": "registry:ui",
  "title": "Calendar Grid",
  "description": "Calendar Grid is a composed month-view calendar with single-date or range selection and grid keyboard navigation.",
  "author": "Skrewww",
  "dependencies": [
    "@phosphor-icons/react"
  ],
  "registryDependencies": [
    "@skrewww/calendar-day",
    "@skrewww/foundation"
  ],
  "docs": "Host requirements (assumed already present, not installed by this command): react, react-dom.",
  "files": [
    {
      "path": "components/ui/CalendarGrid.tsx",
      "content": "/** @skrewww-component calendar-grid */\n\"use client\";\n\nimport { CaretLeft, CaretRight } from \"@phosphor-icons/react\";\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type RefObject,\n} from \"react\";\nimport { CalendarDay } from \"@/components/ui/CalendarDay\";\nimport { CalendarMonthCell } from \"@/components/ui/CalendarMonthCell\";\nimport { assignRef } from \"@/components/ui/internal/assign-ref\";\nimport { CalendarYearCell } from \"@/components/ui/CalendarYearCell\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  CALENDAR_DEFAULT_LOCALE,\n  CALENDAR_DEFAULT_WEEK_STARTS_ON,\n  addDays,\n  addMonths,\n  compareCalendarDates,\n  formatAccessibleDateLabel,\n  formatMonthLabel,\n  formatMonthNameLabel,\n  formatWeekdayLabel,\n  getCalendarDateParts,\n  getMonthFromDate,\n  getTodayCalendarDate,\n  isDateWithinRange,\n  isSameCalendarMonth,\n  parseCalendarDate,\n  warnIfFormatterPairIncomplete,\n  type CalendarDateRange,\n  type CalendarDateString,\n  type CalendarFormatterOverrides,\n  type CalendarMonthParts,\n} from \"@/components/ui/internal/calendar-date\";\nimport {\n  PERIOD_GRID_COLUMNS,\n  YEAR_GRID_PAGE_SIZE,\n  generateMonthGrid,\n  getYearPageStart,\n  isMonthFullyDisabled,\n  isYearFullyDisabled,\n  pageHasSelectableYear,\n  resolveNearestEnabledIndex,\n} from \"@/components/ui/internal/calendar-math\";\nimport { useCalendarKeyboard } from \"@/components/ui/internal/useCalendarKeyboard\";\nimport { useCalendarCellGridKeyboard } from \"@/components/ui/internal/useCalendarCellGridKeyboard\";\nimport { useControllableState } from \"@/lib/use-controllable\";\nimport styles from \"@/components/ui/calendar-grid.module.css\";\n\nexport type CalendarGridProps = {\n  /** \"single\" (default) selects one date via value/defaultValue/onValueChange, untouched by range mode.\n   *  \"range\" selects a start/end pair via rangeValue/defaultRangeValue/onRangeValueChange instead. */\n  mode?: \"single\" | \"range\";\n  value?: CalendarDateString;\n  defaultValue?: CalendarDateString;\n  onValueChange?: (value: CalendarDateString) => void;\n  /** Range mode only. Ignored when mode is \"single\". */\n  rangeValue?: CalendarDateRange;\n  /** Range mode only. Ignored when mode is \"single\". */\n  defaultRangeValue?: CalendarDateRange;\n  /** Range mode only. Ignored when mode is \"single\". */\n  onRangeValueChange?: (range: CalendarDateRange) => void;\n  visibleMonth?: CalendarMonthParts;\n  defaultVisibleMonth?: CalendarMonthParts;\n  onVisibleMonthChange?: (month: CalendarMonthParts) => void;\n  weekStartsOn?: 0 | 1;\n  locale?: string;\n  initialFocusDate?: CalendarDateString;\n  /** Earliest selectable date, inclusive. Dates before this are disabled. */\n  minDate?: CalendarDateString;\n  /** Latest selectable date, inclusive. Dates after this are disabled. */\n  maxDate?: CalendarDateString;\n  /** Arbitrary additional disabled-date predicate, combined with minDate/maxDate. */\n  isDateDisabled?: (date: CalendarDateString) => boolean;\n  dayButtonRef?: RefObject<HTMLButtonElement | null>;\n  className?: string;\n  \"aria-label\"?: string;\n} & CalendarFormatterOverrides;\n\n/** Which drill level of the calendar is currently showing. Internal UI state only. */\ntype CalendarSubview = \"day\" | \"month\" | \"year\";\n\nfunction monthKey(month: CalendarMonthParts): string {\n  return `${month.year}-${month.month}`;\n}\n\nfunction chunkIntoRows<T>(items: T[], columns: number): T[][] {\n  const rows: T[][] = [];\n  for (let index = 0; index < items.length; index += columns) {\n    rows.push(items.slice(index, index + columns));\n  }\n  return rows;\n}\n\nfunction resolveInitialFocusDate(\n  value: CalendarDateString | undefined,\n  visibleMonth: CalendarMonthParts,\n  initialFocusDate: CalendarDateString | undefined,\n  isDisabled: (date: CalendarDateString) => boolean,\n): CalendarDateString {\n  const candidates: CalendarDateString[] = [];\n  if (\n    initialFocusDate &&\n    parseCalendarDate(initialFocusDate) &&\n    isSameCalendarMonth(initialFocusDate, visibleMonth)\n  ) {\n    candidates.push(initialFocusDate);\n  }\n  // Only treat the selected value as a focus candidate when it actually falls\n  // within the month we're now showing — otherwise a selection made in a\n  // different month would steal focus away from the month just navigated to.\n  if (value && parseCalendarDate(value) && isSameCalendarMonth(value, visibleMonth)) {\n    candidates.push(value);\n  }\n  const today = getTodayCalendarDate();\n  if (today.startsWith(`${visibleMonth.year}-${String(visibleMonth.month).padStart(2, \"0\")}`)) {\n    candidates.push(today);\n  }\n  candidates.push(`${visibleMonth.year}-${String(visibleMonth.month).padStart(2, \"0\")}-01`);\n\n  const firstEnabled = candidates.find((c) => !isDisabled(c));\n  if (firstEnabled) return firstEnabled;\n\n  // Every preferred candidate is disabled — search forward from the 1st of the\n  // visible month for the nearest enabled day, so focus never silently lands\n  // on a date the user can't actually select.\n  let probe = `${visibleMonth.year}-${String(visibleMonth.month).padStart(2, \"0\")}-01`;\n  for (let step = 0; step < 42; step += 1) {\n    if (!isDisabled(probe)) return probe;\n    probe = addDays(probe, 1);\n  }\n  return candidates[0] ?? probe;\n}\n\nexport function CalendarGrid(props: CalendarGridProps) {\n  const valueProvided = \"value\" in props;\n  const rangeValueProvided = \"rangeValue\" in props;\n  const {\n    mode = \"single\",\n    value,\n    defaultValue,\n    onValueChange,\n    rangeValue: rangeValueProp,\n    defaultRangeValue,\n    onRangeValueChange,\n    visibleMonth,\n    defaultVisibleMonth,\n    onVisibleMonthChange,\n    weekStartsOn = CALENDAR_DEFAULT_WEEK_STARTS_ON,\n    locale = CALENDAR_DEFAULT_LOCALE,\n    initialFocusDate,\n    minDate,\n    maxDate,\n    isDateDisabled,\n    dayButtonRef,\n    className,\n    formatMonth,\n    formatWeekday,\n    formatDate,\n    parseDate,\n    \"aria-label\": ariaLabel,\n  } = props;\n  useEffect(() => {\n    warnIfFormatterPairIncomplete({ formatMonth, formatWeekday, formatDate, parseDate });\n  }, [formatDate, formatMonth, formatWeekday, parseDate]);\n\n  const labelId = useId();\n  const gridRef = useRef<HTMLDivElement | null>(null);\n  const dayRefs = useRef<Map<string, HTMLButtonElement>>(new Map());\n  const monthRefs = useRef<Map<number, HTMLButtonElement>>(new Map());\n  const yearRefs = useRef<Map<number, HTMLButtonElement>>(new Map());\n\n  const [selectedValue, setSelectedValue] = useControllableState<CalendarDateString | undefined>({\n    value,\n    defaultValue,\n    onChange: (next) => {\n      if (next) onValueChange?.(next);\n    },\n    valueProvided,\n  });\n\n  const initialSelectedValue = value ?? defaultValue;\n  const [currentMonth, setCurrentMonth] = useControllableState<CalendarMonthParts>({\n    value: visibleMonth,\n    defaultValue:\n      defaultVisibleMonth ??\n      (initialSelectedValue\n        ? getMonthFromDate(initialSelectedValue)\n        : getMonthFromDate(getTodayCalendarDate())),\n    onChange: onVisibleMonthChange,\n  });\n\n  const isDisabled = useCallback(\n    (date: CalendarDateString) =>\n      !isDateWithinRange(date, minDate, maxDate) || (isDateDisabled?.(date) ?? false),\n    [minDate, maxDate, isDateDisabled],\n  );\n\n  const [rangeValue, setRangeValue] = useControllableState<CalendarDateRange>({\n    value: rangeValueProp,\n    defaultValue: defaultRangeValue ?? { start: undefined, end: undefined },\n    onChange: onRangeValueChange,\n    valueProvided: rangeValueProvided,\n  });\n\n  // Mouse-hover tracking for the live range preview (range mode only). Cleared\n  // whenever real DOM focus moves, so keyboard arrow-key navigation always\n  // takes over as the preview anchor instead of a stale hover position.\n  const [hoveredDate, setHoveredDate] = useState<CalendarDateString | undefined>(undefined);\n\n  const [subview, setSubview] = useState<CalendarSubview>(\"day\");\n  const previousSubviewRef = useRef<CalendarSubview>(subview);\n\n  // What a fresh drill navigation (initial mount, or landing back on the day\n  // grid after picking a month) should treat as \"the value\" for initial focus\n  // purposes — the range's end (or start, if no end yet) in range mode, or\n  // the single selected date otherwise. Keeps resolveInitialFocusDate's logic\n  // shared across both modes without changing single mode's actual values.\n  const focusCandidateValue = mode === \"range\" ? (rangeValue.end ?? rangeValue.start) : selectedValue;\n\n  const [focusedDate, setFocusedDate] = useState<CalendarDateString>(() =>\n    resolveInitialFocusDate(\n      focusCandidateValue ?? defaultValue,\n      currentMonth,\n      initialFocusDate,\n      isDisabled,\n    ),\n  );\n  const [focusedMonthIndex, setFocusedMonthIndex] = useState(() => currentMonth.month - 1);\n  const [focusedYearIndex, setFocusedYearIndex] = useState(0);\n  const [yearPageStart, setYearPageStart] = useState(() => getYearPageStart(currentMonth.year));\n\n  const cells = useMemo(\n    () => generateMonthGrid(currentMonth, { weekStartsOn }),\n    [currentMonth, weekStartsOn],\n  );\n\n  const weeks = useMemo(() => {\n    const rows: typeof cells[] = [];\n    for (let index = 0; index < cells.length; index += 7) {\n      rows.push(cells.slice(index, index + 7));\n    }\n    return rows;\n  }, [cells]);\n\n  const weekdayLabels = useMemo(\n    () =>\n      Array.from({ length: 7 }, (_, index) =>\n        formatWeekday?.(index) ?? formatWeekdayLabel(index, locale, weekStartsOn),\n      ),\n    [formatWeekday, locale, weekStartsOn],\n  );\n\n  const monthLabel = useMemo(\n    () => formatMonth?.(currentMonth) ?? formatMonthLabel(currentMonth, locale),\n    [currentMonth, formatMonth, locale],\n  );\n\n  const today = getTodayCalendarDate();\n  const todayParts = getCalendarDateParts(today);\n  const selectedParts =\n    selectedValue && parseCalendarDate(selectedValue) ? getCalendarDateParts(selectedValue) : null;\n\n  const handleSelect = useCallback(\n    (date: CalendarDateString) => {\n      if (isDisabled(date)) return;\n      setSelectedValue(date);\n      setFocusedDate(date);\n    },\n    [isDisabled, setSelectedValue],\n  );\n\n  const handleRangeSelect = useCallback(\n    (date: CalendarDateString) => {\n      if (isDisabled(date)) return;\n      setFocusedDate(date);\n      setHoveredDate(undefined);\n\n      if (rangeValue.start === undefined || rangeValue.end !== undefined) {\n        // No range in progress, or a complete range already exists — every\n        // click/Enter in that state starts a fresh range from here rather\n        // than extending or replacing just one end of the old one.\n        setRangeValue({ start: date, end: undefined });\n        return;\n      }\n\n      // A start is set and end is not — this commits the end.\n      // Decision: if the chosen date is before the current start, SWAP the\n      // two so the range stays chronological, rather than discarding the\n      // first click and restarting from this one. Both dates the user\n      // actually clicked remain part of the final range this way, matching\n      // the convention most mature range pickers use (Airbnb, Google\n      // Flights) — restarting instead would make a backwards second click\n      // feel like it did nothing.\n      if (compareCalendarDates(date, rangeValue.start) < 0) {\n        setRangeValue({ start: date, end: rangeValue.start });\n      } else {\n        setRangeValue({ start: rangeValue.start, end: date });\n      }\n    },\n    [isDisabled, rangeValue, setRangeValue],\n  );\n\n  const handleFocusDate = useCallback(\n    (date: CalendarDateString) => {\n      setFocusedDate(date);\n      // A real focus change (keyboard nav or a click) always supersedes any\n      // stale mouse-hover preview state left over from elsewhere in the grid.\n      if (mode === \"range\") setHoveredDate(undefined);\n    },\n    [mode],\n  );\n\n  const handleKeyDown = useCalendarKeyboard({\n    focusedDate,\n    visibleMonth: currentMonth,\n    weekStartsOn,\n    isDisabled,\n    onFocusedDateChange: handleFocusDate,\n    onVisibleMonthChange: setCurrentMonth,\n    onSelectDate: mode === \"range\" ? handleRangeSelect : handleSelect,\n  });\n\n  const isMonthCellDisabled = useCallback(\n    (index: number) => isMonthFullyDisabled(currentMonth.year, index + 1, isDisabled),\n    [currentMonth.year, isDisabled],\n  );\n\n  const handleSelectMonth = useCallback(\n    (month: number) => {\n      if (isMonthFullyDisabled(currentMonth.year, month, isDisabled)) return;\n      const nextMonth: CalendarMonthParts = { year: currentMonth.year, month };\n      setCurrentMonth(nextMonth);\n      setFocusedDate(resolveInitialFocusDate(focusCandidateValue, nextMonth, undefined, isDisabled));\n      setSubview(\"day\");\n    },\n    [currentMonth.year, focusCandidateValue, isDisabled, setCurrentMonth],\n  );\n\n  const handleMonthKeyDown = useCalendarCellGridKeyboard({\n    focusedIndex: focusedMonthIndex,\n    itemCount: 12,\n    columns: PERIOD_GRID_COLUMNS,\n    isDisabled: isMonthCellDisabled,\n    onFocusedIndexChange: setFocusedMonthIndex,\n    onSelect: (index) => handleSelectMonth(index + 1),\n  });\n\n  const isYearCellDisabled = useCallback(\n    (index: number) => isYearFullyDisabled(yearPageStart + index, isDisabled),\n    [yearPageStart, isDisabled],\n  );\n\n  const handleSelectYear = useCallback(\n    (year: number) => {\n      if (isYearFullyDisabled(year, isDisabled)) return;\n      const nextMonth: CalendarMonthParts = { year, month: currentMonth.month };\n      setCurrentMonth(nextMonth);\n      const nextFocusedIndex = resolveNearestEnabledIndex(currentMonth.month - 1, 12, (index) =>\n        isMonthFullyDisabled(year, index + 1, isDisabled),\n      );\n      setFocusedMonthIndex(nextFocusedIndex);\n      setSubview(\"month\");\n    },\n    [currentMonth.month, isDisabled, setCurrentMonth],\n  );\n\n  const handleYearKeyDown = useCalendarCellGridKeyboard({\n    focusedIndex: focusedYearIndex,\n    itemCount: YEAR_GRID_PAGE_SIZE,\n    columns: PERIOD_GRID_COLUMNS,\n    isDisabled: isYearCellDisabled,\n    onFocusedIndexChange: setFocusedYearIndex,\n    onSelect: (index) => handleSelectYear(yearPageStart + index),\n  });\n\n  const handleDrillUpToMonth = useCallback(() => {\n    const nextFocusedIndex = resolveNearestEnabledIndex(currentMonth.month - 1, 12, (index) =>\n      isMonthFullyDisabled(currentMonth.year, index + 1, isDisabled),\n    );\n    setFocusedMonthIndex(nextFocusedIndex);\n    setSubview(\"month\");\n  }, [currentMonth.month, currentMonth.year, isDisabled]);\n\n  const handleDrillUpToYear = useCallback(() => {\n    const pageStart = getYearPageStart(currentMonth.year);\n    setYearPageStart(pageStart);\n    const nextFocusedIndex = resolveNearestEnabledIndex(\n      currentMonth.year - pageStart,\n      YEAR_GRID_PAGE_SIZE,\n      (index) => isYearFullyDisabled(pageStart + index, isDisabled),\n    );\n    setFocusedYearIndex(nextFocusedIndex);\n    setSubview(\"year\");\n  }, [currentMonth.year, isDisabled]);\n\n  function goToYearPage(delta: number) {\n    const nextPageStart = yearPageStart + delta * YEAR_GRID_PAGE_SIZE;\n    setYearPageStart(nextPageStart);\n    const nextFocusedIndex = resolveNearestEnabledIndex(focusedYearIndex, YEAR_GRID_PAGE_SIZE, (index) =>\n      isYearFullyDisabled(nextPageStart + index, isDisabled),\n    );\n    setFocusedYearIndex(nextFocusedIndex);\n  }\n\n  const canGoPrevYearPage = useMemo(\n    () =>\n      pageHasSelectableYear(yearPageStart - YEAR_GRID_PAGE_SIZE, YEAR_GRID_PAGE_SIZE, (year) =>\n        isYearFullyDisabled(year, isDisabled),\n      ),\n    [yearPageStart, isDisabled],\n  );\n  const canGoNextYearPage = useMemo(\n    () =>\n      pageHasSelectableYear(yearPageStart + YEAR_GRID_PAGE_SIZE, YEAR_GRID_PAGE_SIZE, (year) =>\n        isYearFullyDisabled(year, isDisabled),\n      ),\n    [yearPageStart, isDisabled],\n  );\n\n  useEffect(() => {\n    const node = dayRefs.current.get(focusedDate) ?? null;\n    assignRef(dayButtonRef, node);\n    if (node && gridRef.current?.contains(document.activeElement)) {\n      node.focus();\n    }\n  }, [dayButtonRef, focusedDate, currentMonth]);\n\n  // Keyboard-driven focus movement within the month grid.\n  useEffect(() => {\n    if (subview !== \"month\") return;\n    const node = monthRefs.current.get(focusedMonthIndex + 1);\n    if (node && gridRef.current?.contains(document.activeElement)) {\n      node.focus();\n    }\n  }, [subview, focusedMonthIndex]);\n\n  // Keyboard-driven focus movement within the year grid.\n  useEffect(() => {\n    if (subview !== \"year\") return;\n    const node = yearRefs.current.get(yearPageStart + focusedYearIndex);\n    if (node && gridRef.current?.contains(document.activeElement)) {\n      node.focus();\n    }\n  }, [subview, focusedYearIndex, yearPageStart]);\n\n  // Move DOM focus onto the newly-revealed grid whenever we drill up or down —\n  // the cell that triggered the transition unmounts, so focus can't simply follow it.\n  useEffect(() => {\n    const previous = previousSubviewRef.current;\n    previousSubviewRef.current = subview;\n    if (previous === subview) return;\n\n    if (subview === \"day\") {\n      dayRefs.current.get(focusedDate)?.focus();\n    } else if (subview === \"month\") {\n      monthRefs.current.get(focusedMonthIndex + 1)?.focus();\n    } else {\n      yearRefs.current.get(yearPageStart + focusedYearIndex)?.focus();\n    }\n    // Only the subview transition itself should trigger this — the other\n    // focus-restoration effects above already handle in-subview movement.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [subview]);\n\n  function goToMonth(delta: number) {\n    setCurrentMonth(addMonths(currentMonth, delta));\n  }\n\n  const monthGridCells = useMemo(\n    () => chunkIntoRows(Array.from({ length: 12 }, (_, index) => index + 1), PERIOD_GRID_COLUMNS),\n    [],\n  );\n\n  const yearGridCells = useMemo(\n    () =>\n      chunkIntoRows(\n        Array.from({ length: YEAR_GRID_PAGE_SIZE }, (_, index) => yearPageStart + index),\n        PERIOD_GRID_COLUMNS,\n      ),\n    [yearPageStart],\n  );\n\n  const isRangeComplete =\n    mode === \"range\" && rangeValue.start !== undefined && rangeValue.end !== undefined;\n\n  // The provisional (uncommitted) span shown while a range's start is set but\n  // its end isn't yet — driven by mouse hover, falling back to the keyboard's\n  // focused cell so arrow-key navigation gets the same live preview. Mirrors\n  // the swap-for-chronological-order decision in handleRangeSelect: hovering\n  // an earlier date previews the range as it would actually be committed.\n  const rangePreviewSpan = useMemo(() => {\n    if (mode !== \"range\" || rangeValue.start === undefined || rangeValue.end !== undefined) {\n      return null;\n    }\n    const anchor = hoveredDate ?? focusedDate;\n    if (!anchor || anchor === rangeValue.start) return null;\n    const backwards = compareCalendarDates(rangeValue.start, anchor) > 0;\n    return {\n      start: backwards ? anchor : rangeValue.start,\n      end: backwards ? rangeValue.start : anchor,\n      anchor,\n    };\n  }, [mode, rangeValue.start, rangeValue.end, hoveredDate, focusedDate]);\n\n  const rangeAnnouncement = useMemo(() => {\n    if (mode !== \"range\") return \"\";\n    if (rangeValue.start && rangeValue.end) {\n      return `Date range selected: ${formatAccessibleDateLabel(rangeValue.start, locale)} to ${formatAccessibleDateLabel(rangeValue.end, locale)}.`;\n    }\n    if (rangeValue.start) {\n      return `Start date selected, ${formatAccessibleDateLabel(rangeValue.start, locale)}. Choose an end date.`;\n    }\n    return \"\";\n  }, [mode, rangeValue.start, rangeValue.end, locale]);\n\n  return (\n    <div className={cn(styles.root, className)}>\n      {mode === \"range\" ? (\n        <div aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n          {rangeAnnouncement}\n        </div>\n      ) : null}\n\n      {subview === \"day\" ? (\n        <div className={styles.header}>\n          <button\n            type=\"button\"\n            className={styles.navButton}\n            aria-label=\"Previous month\"\n            onClick={() => goToMonth(-1)}\n          >\n            <CaretLeft size={16} aria-hidden=\"true\" />\n          </button>\n          <h2 id={labelId} className={styles.monthLabel}>\n            <button type=\"button\" className={styles.headerButton} onClick={handleDrillUpToMonth}>\n              {monthLabel}\n            </button>\n          </h2>\n          <button\n            type=\"button\"\n            className={styles.navButton}\n            aria-label=\"Next month\"\n            onClick={() => goToMonth(1)}\n          >\n            <CaretRight size={16} aria-hidden=\"true\" />\n          </button>\n        </div>\n      ) : null}\n\n      {subview === \"month\" ? (\n        <div className={cn(styles.header, styles.headerCentered)}>\n          <h2 id={labelId} className={styles.monthLabel}>\n            <button type=\"button\" className={styles.headerButton} onClick={handleDrillUpToYear}>\n              {currentMonth.year}\n            </button>\n          </h2>\n        </div>\n      ) : null}\n\n      {subview === \"year\" ? (\n        <div className={styles.header}>\n          <button\n            type=\"button\"\n            className={styles.navButton}\n            aria-label=\"Previous 12 years\"\n            disabled={!canGoPrevYearPage}\n            onClick={() => goToYearPage(-1)}\n          >\n            <CaretLeft size={16} aria-hidden=\"true\" />\n          </button>\n          <h2 id={labelId} className={styles.monthLabel}>\n            {yearPageStart}–{yearPageStart + YEAR_GRID_PAGE_SIZE - 1}\n          </h2>\n          <button\n            type=\"button\"\n            className={styles.navButton}\n            aria-label=\"Next 12 years\"\n            disabled={!canGoNextYearPage}\n            onClick={() => goToYearPage(1)}\n          >\n            <CaretRight size={16} aria-hidden=\"true\" />\n          </button>\n        </div>\n      ) : null}\n\n      {subview === \"day\" ? (\n        <div\n          ref={gridRef}\n          role=\"grid\"\n          aria-labelledby={ariaLabel ? undefined : labelId}\n          aria-label={ariaLabel}\n          className={styles.grid}\n          onKeyDown={handleKeyDown}\n        >\n          <div role=\"row\" className={styles.weekdayRow}>\n            {weekdayLabels.map((label) => (\n              <div key={label} role=\"columnheader\" className={styles.weekday}>\n                {label}\n              </div>\n            ))}\n          </div>\n\n          {weeks.map((week) => (\n            <div role=\"row\" key={`${monthKey(currentMonth)}-${week[0]?.date}`} className={styles.weekRow}>\n              {week.map((cell) => {\n                const rangeStartHere = mode === \"range\" && rangeValue.start === cell.date;\n                const rangeEndHere = isRangeComplete && rangeValue.end === cell.date;\n                const rangeMiddleHere =\n                  isRangeComplete &&\n                  !rangeStartHere &&\n                  !rangeEndHere &&\n                  isDateWithinRange(cell.date, rangeValue.start, rangeValue.end);\n                const previewEndHere =\n                  rangePreviewSpan !== null && cell.date === rangePreviewSpan.anchor;\n                const previewMiddleHere =\n                  rangePreviewSpan !== null &&\n                  cell.date !== rangeValue.start &&\n                  !previewEndHere &&\n                  isDateWithinRange(cell.date, rangePreviewSpan.start, rangePreviewSpan.end);\n                const isRangeSelectedHere = rangeStartHere || rangeEndHere || rangeMiddleHere;\n\n                return (\n                  <div\n                    role=\"gridcell\"\n                    key={cell.date}\n                    className={styles.cell}\n                    aria-selected={\n                      (mode === \"range\" ? isRangeSelectedHere : selectedValue === cell.date) ||\n                      undefined\n                    }\n                  >\n                    <CalendarDay\n                      ref={(node) => {\n                        if (node) dayRefs.current.set(cell.date, node);\n                        else dayRefs.current.delete(cell.date);\n                      }}\n                      className={styles.dayInGrid}\n                      date={cell.date}\n                      locale={locale}\n                      selected={mode === \"single\" && selectedValue === cell.date}\n                      today={today === cell.date}\n                      outsideMonth={cell.outsideMonth}\n                      disabled={isDisabled(cell.date)}\n                      rangeStart={rangeStartHere}\n                      rangeEnd={rangeEndHere}\n                      rangeMiddle={rangeMiddleHere}\n                      rangePreviewEnd={previewEndHere}\n                      rangePreviewMiddle={previewMiddleHere}\n                      tabIndex={focusedDate === cell.date ? 0 : -1}\n                      onFocusDate={handleFocusDate}\n                      onHoverDate={mode === \"range\" ? setHoveredDate : undefined}\n                      onDateSelect={mode === \"range\" ? handleRangeSelect : handleSelect}\n                    />\n                  </div>\n                );\n              })}\n            </div>\n          ))}\n        </div>\n      ) : null}\n\n      {subview === \"month\" ? (\n        <div\n          ref={gridRef}\n          role=\"grid\"\n          aria-label={`Choose month, ${currentMonth.year}`}\n          className={styles.periodGrid}\n          onKeyDown={handleMonthKeyDown}\n        >\n          {monthGridCells.map((row) => (\n            <div role=\"row\" key={`month-row-${row[0]}`} className={styles.periodRow}>\n              {row.map((month) => {\n                const index = month - 1;\n                const disabled = isMonthFullyDisabled(currentMonth.year, month, isDisabled);\n                const selected =\n                  selectedParts !== null &&\n                  selectedParts.year === currentMonth.year &&\n                  selectedParts.month === month;\n                const isCurrentMonth =\n                  todayParts.year === currentMonth.year && todayParts.month === month;\n\n                return (\n                  <div\n                    role=\"gridcell\"\n                    key={month}\n                    className={styles.periodCell}\n                    aria-selected={selected || undefined}\n                  >\n                    <CalendarMonthCell\n                      ref={(node) => {\n                        if (node) monthRefs.current.set(month, node);\n                        else monthRefs.current.delete(month);\n                      }}\n                      month={month}\n                      label={formatMonthNameLabel(month, locale)}\n                      selected={selected}\n                      today={isCurrentMonth}\n                      disabled={disabled}\n                      tabIndex={focusedMonthIndex === index ? 0 : -1}\n                      onMonthSelect={handleSelectMonth}\n                      onFocusMonth={(m) => setFocusedMonthIndex(m - 1)}\n                    />\n                  </div>\n                );\n              })}\n            </div>\n          ))}\n        </div>\n      ) : null}\n\n      {subview === \"year\" ? (\n        <div\n          ref={gridRef}\n          role=\"grid\"\n          aria-label=\"Choose year\"\n          className={styles.periodGrid}\n          onKeyDown={handleYearKeyDown}\n        >\n          {yearGridCells.map((row) => (\n            <div role=\"row\" key={`year-row-${row[0]}`} className={styles.periodRow}>\n              {row.map((year) => {\n                const index = year - yearPageStart;\n                const disabled = isYearFullyDisabled(year, isDisabled);\n                const selected = selectedParts !== null && selectedParts.year === year;\n                const isCurrentYear = todayParts.year === year;\n\n                return (\n                  <div\n                    role=\"gridcell\"\n                    key={year}\n                    className={styles.periodCell}\n                    aria-selected={selected || undefined}\n                  >\n                    <CalendarYearCell\n                      ref={(node) => {\n                        if (node) yearRefs.current.set(year, node);\n                        else yearRefs.current.delete(year);\n                      }}\n                      year={year}\n                      selected={selected}\n                      today={isCurrentYear}\n                      disabled={disabled}\n                      tabIndex={focusedYearIndex === index ? 0 : -1}\n                      onYearSelect={handleSelectYear}\n                      onFocusYear={(y) => setFocusedYearIndex(y - yearPageStart)}\n                    />\n                  </div>\n                );\n              })}\n            </div>\n          ))}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/CalendarGrid.tsx"
    },
    {
      "path": "components/ui/calendar-grid.module.css",
      "content": ".root {\n  width: var(--calendar-grid-width);\n  padding: var(--calendar-grid-padding);\n  border: 1px solid var(--calendar-grid-border);\n  border-radius: var(--calendar-grid-radius);\n  background: var(--calendar-grid-surface);\n  overflow: hidden;\n}\n\n.header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: var(--calendar-grid-header-gap);\n  margin-bottom: var(--calendar-grid-header-gap);\n}\n\n.headerCentered {\n  justify-content: center;\n}\n\n.monthLabel {\n  margin: 0;\n  font-size: 0.9375rem;\n  font-weight: 600;\n  color: var(--calendar-grid-month-text);\n}\n\n.headerButton {\n  border: none;\n  background: transparent;\n  padding: 0;\n  font: inherit;\n  font-weight: inherit;\n  color: inherit;\n  cursor: pointer;\n}\n\n.headerButton:focus-visible {\n  outline: 2px solid var(--semantic-focus-ring);\n  outline-offset: 2px;\n}\n\n.navButton {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: 2rem;\n  height: 2rem;\n  border: 1px solid var(--calendar-grid-border);\n  border-radius: min(var(--shape-radius-control), 9999px);\n  background: transparent;\n  color: var(--calendar-grid-month-text);\n  cursor: pointer;\n}\n\n.navButton:focus-visible {\n  outline: 2px solid var(--semantic-focus-ring);\n  outline-offset: -2px;\n}\n\n.navButton:disabled {\n  opacity: 0.4;\n  cursor: not-allowed;\n}\n\n.grid {\n  display: flex;\n  flex-direction: column;\n  gap: var(--calendar-grid-week-gap);\n}\n\n.weekdayRow,\n.weekRow {\n  display: grid;\n  grid-template-columns: repeat(7, 1fr);\n  gap: var(--calendar-grid-day-gap);\n}\n\n.weekday {\n  font-size: 0.75rem;\n  font-weight: 600;\n  text-align: center;\n  color: var(--calendar-grid-weekday-text);\n}\n\n.cell {\n  display: flex;\n  justify-content: center;\n  min-width: 0;\n  overflow: hidden;\n}\n\n.dayInGrid {\n  box-sizing: border-box;\n  width: 100%;\n  max-width: 100%;\n  min-width: 0;\n  height: auto;\n  aspect-ratio: 1;\n  min-height: 0;\n}\n\n.periodGrid {\n  display: flex;\n  flex-direction: column;\n  gap: var(--calendar-grid-week-gap);\n}\n\n.periodRow {\n  display: grid;\n  grid-template-columns: repeat(4, 1fr);\n  gap: var(--calendar-grid-day-gap);\n}\n\n.periodCell {\n  display: flex;\n  justify-content: center;\n  min-width: 0;\n  overflow: hidden;\n}\n\n[data-skrewww-shape=\"pill\"] .root {\n  border-radius: min(var(--calendar-grid-radius), 1.25rem);\n}\n\n[data-skrewww-surface=\"glass\"] .root {\n  background: color-mix(in srgb, var(--calendar-grid-surface) var(--glass-mix-md), white);\n  backdrop-filter: var(--glass-backdrop-filter-md);\n}\n\n@supports not (backdrop-filter: blur(1px)) {\n  [data-skrewww-surface=\"glass\"] .root {\n    background: color-mix(in srgb, var(--calendar-grid-surface) var(--glass-mix-md-fallback), white);\n  }\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/calendar-grid.module.css"
    },
    {
      "path": "lib/cn.ts",
      "content": "export function cn(...classes: Array<string | false | null | undefined>): string {\n  return classes.filter(Boolean).join(\" \");\n}\n",
      "type": "registry:lib",
      "target": "~/lib/cn.ts"
    },
    {
      "path": "lib/use-controllable.ts",
      "content": "import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport function useControllableState<T>({\n  value,\n  defaultValue,\n  onChange,\n  controlled: controlledProp,\n  valueProvided,\n}: {\n  value?: T;\n  defaultValue?: T;\n  onChange?: (next: T) => void;\n  /** Explicit controlled override — prefer `valueProvided` from the component root. */\n  controlled?: boolean;\n  /** True when the parent passed a `value` prop, including `undefined`. */\n  valueProvided?: boolean;\n}) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue as T);\n  const isControlled = controlledProp ?? valueProvided ?? value !== undefined;\n  const current = isControlled ? (value as T) : uncontrolled;\n  const wasControlledRef = useRef(isControlled);\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"development\") return;\n    if (wasControlledRef.current !== isControlled) {\n      console.warn(\n        \"[Skrewww] A component changed between controlled and uncontrolled modes. Keep `value` or `defaultValue` usage consistent across renders.\",\n      );\n    }\n    wasControlledRef.current = isControlled;\n  }, [isControlled]);\n\n  const setValue = useCallback(\n    (next: T) => {\n      if (!isControlled) setUncontrolled(next);\n      onChange?.(next);\n    },\n    [isControlled, onChange],\n  );\n\n  return [current, setValue] as const;\n}\n",
      "type": "registry:lib",
      "target": "~/lib/use-controllable.ts"
    },
    {
      "path": "components/ui/CalendarMonthCell.tsx",
      "content": "\"use client\";\n\nimport { forwardRef, type ButtonHTMLAttributes } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport styles from \"@/components/ui/calendar-period-cell.module.css\";\n\nexport type CalendarMonthCellProps = Omit<\n  ButtonHTMLAttributes<HTMLButtonElement>,\n  \"children\" | \"onClick\" | \"type\"\n> & {\n  /** 1-12 */\n  month: number;\n  label: string;\n  selected?: boolean;\n  today?: boolean;\n  onMonthSelect?: (month: number) => void;\n  onFocusMonth?: (month: number) => void;\n};\n\nexport const CalendarMonthCell = forwardRef<HTMLButtonElement, CalendarMonthCellProps>(\n  function CalendarMonthCell(\n    {\n      month,\n      label,\n      selected = false,\n      today = false,\n      disabled = false,\n      onMonthSelect,\n      onFocusMonth,\n      className,\n      tabIndex = -1,\n      ...props\n    },\n    ref,\n  ) {\n    return (\n      <button\n        {...props}\n        ref={ref}\n        type=\"button\"\n        className={cn(\n          styles.cell,\n          today && styles.today,\n          selected && styles.selected,\n          disabled && styles.disabled,\n          className,\n        )}\n        aria-label={label}\n        aria-current={today ? \"date\" : undefined}\n        aria-disabled={disabled || undefined}\n        disabled={disabled}\n        tabIndex={disabled ? -1 : tabIndex}\n        data-month={month}\n        onClick={() => {\n          if (!disabled) onMonthSelect?.(month);\n        }}\n        onFocus={() => onFocusMonth?.(month)}\n      >\n        <span className={styles.label} aria-hidden=\"true\">\n          {label}\n        </span>\n        {today ? <span className={styles.todayIndicator} aria-hidden=\"true\" /> : null}\n      </button>\n    );\n  },\n);\n",
      "type": "registry:ui",
      "target": "~/components/ui/CalendarMonthCell.tsx"
    },
    {
      "path": "components/ui/CalendarYearCell.tsx",
      "content": "\"use client\";\n\nimport { forwardRef, type ButtonHTMLAttributes } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport styles from \"@/components/ui/calendar-period-cell.module.css\";\n\nexport type CalendarYearCellProps = Omit<\n  ButtonHTMLAttributes<HTMLButtonElement>,\n  \"children\" | \"onClick\" | \"type\"\n> & {\n  year: number;\n  selected?: boolean;\n  today?: boolean;\n  onYearSelect?: (year: number) => void;\n  onFocusYear?: (year: number) => void;\n};\n\nexport const CalendarYearCell = forwardRef<HTMLButtonElement, CalendarYearCellProps>(\n  function CalendarYearCell(\n    {\n      year,\n      selected = false,\n      today = false,\n      disabled = false,\n      onYearSelect,\n      onFocusYear,\n      className,\n      tabIndex = -1,\n      ...props\n    },\n    ref,\n  ) {\n    const label = String(year);\n\n    return (\n      <button\n        {...props}\n        ref={ref}\n        type=\"button\"\n        className={cn(\n          styles.cell,\n          today && styles.today,\n          selected && styles.selected,\n          disabled && styles.disabled,\n          className,\n        )}\n        aria-label={label}\n        aria-current={today ? \"date\" : undefined}\n        aria-disabled={disabled || undefined}\n        disabled={disabled}\n        tabIndex={disabled ? -1 : tabIndex}\n        data-year={year}\n        onClick={() => {\n          if (!disabled) onYearSelect?.(year);\n        }}\n        onFocus={() => onFocusYear?.(year)}\n      >\n        <span className={styles.label} aria-hidden=\"true\">\n          {label}\n        </span>\n        {today ? <span className={styles.todayIndicator} aria-hidden=\"true\" /> : null}\n      </button>\n    );\n  },\n);\n",
      "type": "registry:ui",
      "target": "~/components/ui/CalendarYearCell.tsx"
    },
    {
      "path": "components/ui/calendar-period-cell.module.css",
      "content": ".cell {\n  position: relative;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  box-sizing: border-box;\n  width: 100%;\n  min-height: var(--calendar-day-min-touch);\n  padding: 0.625rem 0.5rem;\n  border: 1px solid transparent;\n  border-radius: var(--calendar-day-radius);\n  background: transparent;\n  color: var(--calendar-day-text);\n  font: inherit;\n  font-size: 0.875rem;\n  line-height: 1;\n  cursor: pointer;\n}\n\n.cell:hover:not(:disabled) {\n  background: var(--calendar-day-hover-surface);\n}\n\n.cell:focus-visible {\n  outline: 2px solid var(--semantic-focus-ring);\n  outline-offset: -2px;\n}\n\n.selected {\n  background: var(--calendar-day-selected-surface);\n  color: var(--calendar-day-selected-text);\n  border-color: var(--calendar-day-selected-surface);\n}\n\n.selected:hover:not(:disabled) {\n  background: var(--calendar-day-selected-hover-surface);\n  color: var(--calendar-day-selected-text);\n  border-color: var(--calendar-day-selected-hover-surface);\n}\n\n.today:not(.selected) {\n  border-color: var(--calendar-day-today-indicator);\n}\n\n.todayIndicator {\n  position: absolute;\n  bottom: 0.25rem;\n  width: 0.25rem;\n  height: 0.25rem;\n  border-radius: 9999px;\n  background: var(--calendar-day-today-indicator);\n}\n\n.selected .todayIndicator {\n  background: var(--calendar-day-selected-text);\n}\n\n.disabled,\n.cell:disabled {\n  color: var(--calendar-day-disabled-text);\n  cursor: not-allowed;\n}\n\n.label {\n  pointer-events: none;\n}\n\n[data-skrewww-shape=\"pill\"] .cell {\n  border-radius: min(var(--calendar-day-radius), 9999px);\n}\n\n[data-skrewww-surface=\"glass\"] .cell:hover:not(:disabled) {\n  background: color-mix(in srgb, var(--calendar-day-hover-surface) 90%, white);\n}\n\n[data-skrewww-surface=\"glass\"] .selected:hover:not(:disabled) {\n  background: var(--calendar-day-selected-hover-surface);\n}\n",
      "type": "registry:ui",
      "target": "~/components/ui/calendar-period-cell.module.css"
    },
    {
      "path": "components/ui/internal/assign-ref.ts",
      "content": "import type { Ref } from \"react\";\n\n/** Write a value into a React ref prop (callback or object) without touching render. */\nexport function assignRef<T>(ref: Ref<T> | undefined | null, value: T) {\n  if (!ref) return;\n  if (typeof ref === \"function\") {\n    ref(value);\n    return;\n  }\n  ref.current = value;\n}\n\nexport function mergeRefs<T>(\n  ...refs: Array<Ref<T> | undefined | null>\n): (value: T) => void {\n  return (value) => {\n    for (const ref of refs) {\n      assignRef(ref, value);\n    }\n  };\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/assign-ref.ts"
    },
    {
      "path": "components/ui/internal/calendar-date.ts",
      "content": "/** Date-only value in ISO YYYY-MM-DD form — never includes time or time zone. */\nexport type CalendarDateString = string;\n\nexport type CalendarDateParts = {\n  year: number;\n  month: number;\n  day: number;\n};\n\nexport type CalendarMonthParts = {\n  year: number;\n  month: number;\n};\n\n/** Range mode's value shape. Either end may be unset while a selection is in progress. */\nexport type CalendarDateRange = {\n  start: CalendarDateString | undefined;\n  end: CalendarDateString | undefined;\n};\n\nconst ISO_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** Default display/accessibility locale for the first Calendar batch. */\nexport const CALENDAR_DEFAULT_LOCALE = \"en-GB\";\n\n/** Initial week-start policy: Monday (ISO). */\nexport const CALENDAR_DEFAULT_WEEK_STARTS_ON = 1 as const;\n\nexport type CalendarFormatterOverrides = {\n  formatMonth?: (month: CalendarMonthParts) => string;\n  formatWeekday?: (dayIndex: number) => string;\n  formatDate?: (date: CalendarDateString) => string;\n  parseDate?: (text: string) => CalendarDateString | null;\n};\n\nconst warnedInvalidLocales = new Set<string>();\n\n/** Resolve a requested locale, falling back to en-GB when Intl rejects it. */\nexport function resolveCalendarLocale(locale?: string): string {\n  const requested = locale ?? CALENDAR_DEFAULT_LOCALE;\n  if (requested === CALENDAR_DEFAULT_LOCALE) return CALENDAR_DEFAULT_LOCALE;\n\n  try {\n    if (typeof Intl.DateTimeFormat.supportedLocalesOf === \"function\") {\n      const supported = Intl.DateTimeFormat.supportedLocalesOf([requested]);\n      if (supported.length === 0) throw new RangeError(`Unsupported locale: ${requested}`);\n      return supported[0] ?? CALENDAR_DEFAULT_LOCALE;\n    }\n    new Intl.DateTimeFormat(requested).format(new Date());\n    return requested;\n  } catch {\n    if (process.env.NODE_ENV !== \"production\" && !warnedInvalidLocales.has(requested)) {\n      warnedInvalidLocales.add(requested);\n      console.warn(\n        `[calendar] Invalid locale \"${requested}\", falling back to \"${CALENDAR_DEFAULT_LOCALE}\".`,\n      );\n    }\n    return CALENDAR_DEFAULT_LOCALE;\n  }\n}\n\n/** Dev-only guard when only one of formatDate / parseDate is supplied. */\nexport function warnIfFormatterPairIncomplete(overrides: CalendarFormatterOverrides): void {\n  if (process.env.NODE_ENV === \"production\") return;\n  const hasFormat = Boolean(overrides.formatDate);\n  const hasParse = Boolean(overrides.parseDate);\n  if (hasFormat !== hasParse) {\n    console.warn(\n      \"[calendar] formatDate and parseDate must both be provided when overriding date text formatting.\",\n    );\n  }\n}\n\nfunction createDateTimeFormat(\n  locale: string,\n  options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n  const resolved = resolveCalendarLocale(locale);\n  return new Intl.DateTimeFormat(resolved, options);\n}\n\nexport function isValidCalendarDateParts(parts: CalendarDateParts): boolean {\n  if (!Number.isInteger(parts.year) || parts.year < 1) return false;\n  if (parts.month < 1 || parts.month > 12) return false;\n  if (parts.day < 1) return false;\n  return parts.day <= daysInMonth(parts.year, parts.month);\n}\n\nexport function daysInMonth(year: number, month: number): number {\n  return new Date(year, month, 0).getDate();\n}\n\nexport function parseCalendarDate(value: string): CalendarDateParts | null {\n  const match = ISO_DATE_RE.exec(value);\n  if (!match) return null;\n  const parts = {\n    year: Number(match[1]),\n    month: Number(match[2]),\n    day: Number(match[3]),\n  };\n  return isValidCalendarDateParts(parts) ? parts : null;\n}\n\nexport function formatCalendarDate(parts: CalendarDateParts): CalendarDateString {\n  return `${String(parts.year).padStart(4, \"0\")}-${String(parts.month).padStart(2, \"0\")}-${String(parts.day).padStart(2, \"0\")}`;\n}\n\nexport function compareCalendarDates(a: CalendarDateString, b: CalendarDateString): number {\n  return a.localeCompare(b);\n}\n\nexport function calendarDateFromParts(parts: CalendarDateParts): CalendarDateString {\n  return formatCalendarDate(parts);\n}\n\nexport function getCalendarDateParts(date: CalendarDateString): CalendarDateParts {\n  const parsed = parseCalendarDate(date);\n  if (!parsed) {\n    throw new Error(`Invalid calendar date: ${date}`);\n  }\n  return parsed;\n}\n\n/** Local calendar arithmetic — avoids UTC conversion when adding days. */\nexport function addDays(date: CalendarDateString, delta: number): CalendarDateString {\n  const parts = getCalendarDateParts(date);\n  const local = new Date(parts.year, parts.month - 1, parts.day);\n  local.setDate(local.getDate() + delta);\n  return formatCalendarDate({\n    year: local.getFullYear(),\n    month: local.getMonth() + 1,\n    day: local.getDate(),\n  });\n}\n\nexport function addMonths(month: CalendarMonthParts, delta: number): CalendarMonthParts {\n  const index = month.year * 12 + (month.month - 1) + delta;\n  return {\n    year: Math.floor(index / 12),\n    month: (index % 12) + 1,\n  };\n}\n\nexport function getTodayCalendarDate(now = new Date()): CalendarDateString {\n  return formatCalendarDate({\n    year: now.getFullYear(),\n    month: now.getMonth() + 1,\n    day: now.getDate(),\n  });\n}\n\nexport function getMonthFromDate(date: CalendarDateString): CalendarMonthParts {\n  const parts = getCalendarDateParts(date);\n  return { year: parts.year, month: parts.month };\n}\n\nexport function formatMonthLabel(\n  month: CalendarMonthParts,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n): string {\n  return createDateTimeFormat(locale, { month: \"long\", year: \"numeric\" }).format(\n    new Date(month.year, month.month - 1, 1),\n  );\n}\n\n/** Month name only (no year) — used to label cells in the month drill-up grid. */\nexport function formatMonthNameLabel(\n  month: number,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n): string {\n  return createDateTimeFormat(locale, { month: \"long\" }).format(new Date(2021, month - 1, 1));\n}\n\nexport function formatDisplayDate(\n  date: CalendarDateString,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n): string {\n  const parts = getCalendarDateParts(date);\n  return createDateTimeFormat(locale, {\n    day: \"numeric\",\n    month: \"short\",\n    year: \"numeric\",\n  }).format(new Date(parts.year, parts.month - 1, parts.day));\n}\n\n/** Short month abbreviations keyed lowercase — built from the same Intl locale as formatDisplayDate. */\nfunction buildDisplayMonthAbbrevMap(locale: string): Map<string, number> {\n  const resolved = resolveCalendarLocale(locale);\n  const map = new Map<string, number>();\n\n  function registerAbbrev(raw: string, month: number) {\n    const lower = raw.toLowerCase();\n    map.set(lower, month);\n    map.set(lower.replace(/\\.$/, \"\"), month);\n  }\n\n  for (let month = 1; month <= 12; month += 1) {\n    registerAbbrev(\n      new Intl.DateTimeFormat(resolved, { month: \"short\" }).format(new Date(2021, month - 1, 1)),\n      month,\n    );\n\n    // Month token inside a full date string can differ from standalone month: \"short\"\n    // (e.g. de-DE uses \"Juli\" in dates but \"Jul\" standalone).\n    const inContext = createDateTimeFormat(resolved, {\n      day: \"numeric\",\n      month: \"short\",\n      year: \"numeric\",\n    }).format(new Date(2021, month - 1, 15));\n    const yearMatch = /(\\d{4})\\s*$/.exec(inContext);\n    if (yearMatch) {\n      const prefix = inContext.slice(0, yearMatch.index).trim();\n      const dayMatch = /^(\\d{1,2})/.exec(prefix);\n      if (dayMatch) {\n        const rest = prefix.slice(dayMatch[0].length);\n        const contextMonth = rest.match(/[A-Za-zÀ-ÿ][A-Za-zÀ-ÿ.]*/)?.[0];\n        if (contextMonth) registerAbbrev(contextMonth, month);\n      }\n    }\n  }\n  return map;\n}\n\nconst displayMonthAbbrevCache = new Map<string, Map<string, number>>();\n\nfunction getDisplayMonthAbbrevMap(locale: string): Map<string, number> {\n  const resolved = resolveCalendarLocale(locale);\n  const cached = displayMonthAbbrevCache.get(resolved);\n  if (cached) return cached;\n  const built = buildDisplayMonthAbbrevMap(resolved);\n  displayMonthAbbrevCache.set(resolved, built);\n  return built;\n}\n\nfunction normalizeMonthToken(token: string): string {\n  return token.toLowerCase().replace(/\\.$/, \"\").trim();\n}\n\nfunction lookupDisplayMonth(monthMap: Map<string, number>, token: string): number | undefined {\n  return monthMap.get(token.toLowerCase()) ?? monthMap.get(normalizeMonthToken(token));\n}\n\n/**\n * Parse a display-formatted date string back to ISO YYYY-MM-DD.\n * Accepts the D MMM YYYY pattern produced by formatDisplayDate for the given locale.\n * Does not accept numeric-only regional formats (DD/MM, MM/DD, etc.).\n */\nexport function parseDisplayDate(\n  text: string,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n): CalendarDateString | null {\n  const trimmed = text.trim();\n  if (!trimmed) return null;\n\n  const resolvedLocale = resolveCalendarLocale(locale);\n  const yearMatch = /(\\d{4})\\s*$/.exec(trimmed);\n  if (!yearMatch) return null;\n\n  const year = Number(yearMatch[1]);\n  const prefix = trimmed.slice(0, yearMatch.index).trim();\n  const dayMatch = /^(\\d{1,2})/.exec(prefix);\n  if (!dayMatch) return null;\n\n  const day = Number(dayMatch[1]);\n  const rest = prefix.slice(dayMatch[0].length);\n  const monthMatch = rest.match(/[A-Za-zÀ-ÿ][A-Za-zÀ-ÿ.]*/);\n  const monthRaw = monthMatch?.[0]?.trim();\n  if (!monthRaw) return null;\n\n  const month = lookupDisplayMonth(getDisplayMonthAbbrevMap(resolvedLocale), monthRaw);\n  if (!month) return null;\n\n  const parts = { year, month, day };\n  return isValidCalendarDateParts(parts) ? formatCalendarDate(parts) : null;\n}\n\nexport function formatAccessibleDateLabel(\n  date: CalendarDateString,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n): string {\n  const parts = getCalendarDateParts(date);\n  return createDateTimeFormat(locale, {\n    day: \"numeric\",\n    month: \"long\",\n    year: \"numeric\",\n  }).format(new Date(parts.year, parts.month - 1, parts.day));\n}\n\nexport function formatWeekdayLabel(\n  weekdayIndex: number,\n  locale: string = CALENDAR_DEFAULT_LOCALE,\n  weekStartsOn: 0 | 1 = CALENDAR_DEFAULT_WEEK_STARTS_ON,\n): string {\n  // Jan 3 2021 is a Sunday — anchor for weekday 0..6.\n  const weekday = (weekStartsOn + weekdayIndex) % 7;\n  const date = new Date(2021, 0, 3 + weekday);\n  return createDateTimeFormat(locale, { weekday: \"short\" }).format(date);\n}\n\nexport function getDayNumber(date: CalendarDateString): number {\n  return getCalendarDateParts(date).day;\n}\n\nexport function isSameCalendarMonth(\n  date: CalendarDateString,\n  month: CalendarMonthParts,\n): boolean {\n  const parts = getCalendarDateParts(date);\n  return parts.year === month.year && parts.month === month.month;\n}\n\nexport function clampDateToMonth(\n  date: CalendarDateString,\n  month: CalendarMonthParts,\n): CalendarDateString {\n  const parts = getCalendarDateParts(date);\n  const day = Math.min(parts.day, daysInMonth(month.year, month.month));\n  return formatCalendarDate({ year: month.year, month: month.month, day });\n}\n\n/** Whether `date` falls within [min, max], inclusive. Either bound is optional. */\nexport function isDateWithinRange(\n  date: CalendarDateString,\n  min?: CalendarDateString,\n  max?: CalendarDateString,\n): boolean {\n  if (min && compareCalendarDates(date, min) < 0) return false;\n  if (max && compareCalendarDates(date, max) > 0) return false;\n  return true;\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/calendar-date.ts"
    },
    {
      "path": "components/ui/internal/calendar-math.ts",
      "content": "import {\n  addDays,\n  calendarDateFromParts,\n  daysInMonth,\n  formatCalendarDate,\n  type CalendarDateString,\n  type CalendarMonthParts,\n} from \"@/components/ui/internal/calendar-date\";\n\n/** Column count for the 12-cell month and year drill-up grids. */\nexport const PERIOD_GRID_COLUMNS = 4;\n\n/** Number of years shown per page in the year drill-up grid. */\nexport const YEAR_GRID_PAGE_SIZE = 12;\n\nexport type CalendarMonthCell = {\n  date: CalendarDateString;\n  outsideMonth: boolean;\n};\n\nexport function getWeekdayIndex(date: CalendarDateString): number {\n  const [year, month, day] = date.split(\"-\").map(Number);\n  return new Date(year, month - 1, day).getDay();\n}\n\nexport function startOfWeekDate(\n  date: CalendarDateString,\n  weekStartsOn: 0 | 1,\n): CalendarDateString {\n  const weekday = getWeekdayIndex(date);\n  const diff = (weekday - weekStartsOn + 7) % 7;\n  return addDays(date, -diff);\n}\n\nexport function endOfWeekDate(date: CalendarDateString, weekStartsOn: 0 | 1): CalendarDateString {\n  const start = startOfWeekDate(date, weekStartsOn);\n  return addDays(start, 6);\n}\n\nexport function generateMonthGrid(\n  month: CalendarMonthParts,\n  options?: {\n    weekStartsOn?: 0 | 1;\n    weeks?: number;\n  },\n): CalendarMonthCell[] {\n  const weekStartsOn = options?.weekStartsOn ?? 1;\n  const weeks = options?.weeks ?? 6;\n  const firstOfMonth = calendarDateFromParts({ ...month, day: 1 });\n  const gridStart = startOfWeekDate(firstOfMonth, weekStartsOn);\n  const cells: CalendarMonthCell[] = [];\n\n  for (let index = 0; index < weeks * 7; index += 1) {\n    const date = addDays(gridStart, index);\n    const [year, monthNumber] = date.split(\"-\").map(Number);\n    cells.push({\n      date,\n      outsideMonth: year !== month.year || monthNumber !== month.month,\n    });\n  }\n\n  return cells;\n}\n\nexport function monthFromDate(date: CalendarDateString): CalendarMonthParts {\n  const [year, month] = date.split(\"-\").map(Number);\n  return { year, month };\n}\n\nexport function firstDateInMonth(month: CalendarMonthParts): CalendarDateString {\n  return formatCalendarDate({ year: month.year, month: month.month, day: 1 });\n}\n\nexport function findNextEnabledDate(\n  start: CalendarDateString,\n  direction: 1 | -1,\n  isDisabled: (date: CalendarDateString) => boolean,\n  maxSteps = 366,\n): CalendarDateString | null {\n  let current = start;\n  for (let step = 0; step < maxSteps; step += 1) {\n    if (!isDisabled(current)) return current;\n    current = addDays(current, direction);\n  }\n  return null;\n}\n\n/** A month is disabled for drill-up purposes only when every day inside it is disabled. */\nexport function isMonthFullyDisabled(\n  year: number,\n  month: number,\n  isDateDisabled: (date: CalendarDateString) => boolean,\n): boolean {\n  const total = daysInMonth(year, month);\n  for (let day = 1; day <= total; day += 1) {\n    if (!isDateDisabled(formatCalendarDate({ year, month, day }))) return false;\n  }\n  return true;\n}\n\n/** A year is disabled for drill-up purposes only when every month inside it is fully disabled. */\nexport function isYearFullyDisabled(\n  year: number,\n  isDateDisabled: (date: CalendarDateString) => boolean,\n): boolean {\n  for (let month = 1; month <= 12; month += 1) {\n    if (!isMonthFullyDisabled(year, month, isDateDisabled)) return false;\n  }\n  return true;\n}\n\n/** Deterministic page anchor: the year page containing `year`. */\nexport function getYearPageStart(year: number, pageSize: number = YEAR_GRID_PAGE_SIZE): number {\n  return Math.floor(year / pageSize) * pageSize;\n}\n\n/** Whether at least one year in the page starting at `pageStart` can be selected. */\nexport function pageHasSelectableYear(\n  pageStart: number,\n  pageSize: number,\n  isYearDisabled: (year: number) => boolean,\n): boolean {\n  for (let index = 0; index < pageSize; index += 1) {\n    if (!isYearDisabled(pageStart + index)) return true;\n  }\n  return false;\n}\n\n/**\n * Resolve the nearest enabled cell index for a flat 12-cell month/year grid,\n * scanning forward from `preferredIndex` and wrapping once within [0, itemCount).\n * Mirrors the forward-scan fallback CalendarGrid uses for initial day focus.\n */\nexport function resolveNearestEnabledIndex(\n  preferredIndex: number,\n  itemCount: number,\n  isDisabled: (index: number) => boolean,\n): number {\n  if (!isDisabled(preferredIndex)) return preferredIndex;\n  for (let index = preferredIndex + 1; index < itemCount; index += 1) {\n    if (!isDisabled(index)) return index;\n  }\n  for (let index = 0; index < preferredIndex; index += 1) {\n    if (!isDisabled(index)) return index;\n  }\n  return preferredIndex;\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/calendar-math.ts"
    },
    {
      "path": "components/ui/internal/useCalendarKeyboard.ts",
      "content": "import { useCallback, type KeyboardEvent as ReactKeyboardEvent } from \"react\";\nimport {\n  addDays,\n  addMonths,\n  clampDateToMonth,\n  getCalendarDateParts,\n  type CalendarDateString,\n  type CalendarMonthParts,\n} from \"@/components/ui/internal/calendar-date\";\nimport {\n  endOfWeekDate,\n  startOfWeekDate,\n} from \"@/components/ui/internal/calendar-math\";\n\ntype UseCalendarKeyboardOptions = {\n  focusedDate: CalendarDateString;\n  visibleMonth: CalendarMonthParts;\n  weekStartsOn: 0 | 1;\n  isDisabled?: (date: CalendarDateString) => boolean;\n  onFocusedDateChange: (date: CalendarDateString) => void;\n  onVisibleMonthChange: (month: CalendarMonthParts) => void;\n  onSelectDate: (date: CalendarDateString) => void;\n};\n\nfunction moveIfEnabled(\n  candidate: CalendarDateString,\n  isDisabled: (date: CalendarDateString) => boolean,\n  direction: 1 | -1,\n): CalendarDateString {\n  let current = candidate;\n  for (let step = 0; step < 42; step += 1) {\n    if (!isDisabled(current)) return current;\n    current = addDays(current, direction);\n  }\n  return candidate;\n}\n\nexport function useCalendarKeyboard({\n  focusedDate,\n  visibleMonth,\n  weekStartsOn,\n  isDisabled = () => false,\n  onFocusedDateChange,\n  onVisibleMonthChange,\n  onSelectDate,\n}: UseCalendarKeyboardOptions) {\n  const syncVisibleMonth = useCallback(\n    (date: CalendarDateString) => {\n      const parts = getCalendarDateParts(date);\n      if (parts.year !== visibleMonth.year || parts.month !== visibleMonth.month) {\n        onVisibleMonthChange({ year: parts.year, month: parts.month });\n      }\n    },\n    [onVisibleMonthChange, visibleMonth.month, visibleMonth.year],\n  );\n\n  const moveFocus = useCallback(\n    (next: CalendarDateString) => {\n      const resolved = moveIfEnabled(next, isDisabled, next >= focusedDate ? 1 : -1);\n      // moveIfEnabled falls back to returning its candidate unchanged if no\n      // enabled date exists within range — that candidate is itself disabled\n      // in that case. Don't move focus onto a disabled date: a disabled\n      // button can't actually receive DOM focus, so doing so would desync\n      // React state from real keyboard focus at a hard min/max boundary.\n      if (isDisabled(resolved)) return;\n      onFocusedDateChange(resolved);\n      syncVisibleMonth(resolved);\n    },\n    [focusedDate, isDisabled, onFocusedDateChange, syncVisibleMonth],\n  );\n\n  return useCallback(\n    (event: ReactKeyboardEvent<HTMLElement>) => {\n      let handled = false;\n      let nextDate = focusedDate;\n\n      switch (event.key) {\n        case \"ArrowRight\":\n          nextDate = addDays(focusedDate, 1);\n          handled = true;\n          break;\n        case \"ArrowLeft\":\n          nextDate = addDays(focusedDate, -1);\n          handled = true;\n          break;\n        case \"ArrowDown\":\n          nextDate = addDays(focusedDate, 7);\n          handled = true;\n          break;\n        case \"ArrowUp\":\n          nextDate = addDays(focusedDate, -7);\n          handled = true;\n          break;\n        case \"Home\":\n          nextDate = startOfWeekDate(focusedDate, weekStartsOn);\n          handled = true;\n          break;\n        case \"End\":\n          nextDate = endOfWeekDate(focusedDate, weekStartsOn);\n          handled = true;\n          break;\n        case \"PageDown\": {\n          const nextMonth = addMonths(visibleMonth, 1);\n          onVisibleMonthChange(nextMonth);\n          nextDate = clampDateToMonth(focusedDate, nextMonth);\n          handled = true;\n          break;\n        }\n        case \"PageUp\": {\n          const previousMonth = addMonths(visibleMonth, -1);\n          onVisibleMonthChange(previousMonth);\n          nextDate = clampDateToMonth(focusedDate, previousMonth);\n          handled = true;\n          break;\n        }\n        case \"Enter\":\n        case \" \":\n          if (!isDisabled(focusedDate)) {\n            event.preventDefault();\n            onSelectDate(focusedDate);\n          }\n          return;\n        default:\n          return;\n      }\n\n      if (!handled) return;\n      event.preventDefault();\n      moveFocus(nextDate);\n    },\n    [\n      focusedDate,\n      isDisabled,\n      moveFocus,\n      onSelectDate,\n      onVisibleMonthChange,\n      visibleMonth,\n      weekStartsOn,\n    ],\n  );\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useCalendarKeyboard.ts"
    },
    {
      "path": "components/ui/internal/useCalendarCellGridKeyboard.ts",
      "content": "import { useCallback, type KeyboardEvent as ReactKeyboardEvent } from \"react\";\n\n/**\n * Shared roving-tabindex/arrow-key behavior for the flat 12-cell month and\n * year drill-up grids. Both grids are plain index-based NxM layouts (unlike\n * the day grid, which needs calendar-date arithmetic), so they share this one\n * hook instead of duplicating the same handler twice.\n */\ntype UseCalendarCellGridKeyboardOptions = {\n  focusedIndex: number;\n  itemCount: number;\n  columns: number;\n  isDisabled?: (index: number) => boolean;\n  onFocusedIndexChange: (index: number) => void;\n  onSelect: (index: number) => void;\n};\n\nfunction moveIndexIfEnabled(\n  candidate: number,\n  itemCount: number,\n  isDisabled: (index: number) => boolean,\n  direction: 1 | -1,\n): number | null {\n  let current = candidate;\n  while (current >= 0 && current < itemCount) {\n    if (!isDisabled(current)) return current;\n    current += direction;\n  }\n  return null;\n}\n\nexport function useCalendarCellGridKeyboard({\n  focusedIndex,\n  itemCount,\n  columns,\n  isDisabled = () => false,\n  onFocusedIndexChange,\n  onSelect,\n}: UseCalendarCellGridKeyboardOptions) {\n  const moveFocus = useCallback(\n    (rawNext: number) => {\n      if (rawNext < 0 || rawNext >= itemCount) return;\n      const direction = rawNext >= focusedIndex ? 1 : -1;\n      const resolved = moveIndexIfEnabled(rawNext, itemCount, isDisabled, direction);\n      // No enabled cell found scanning in that direction — a disabled button\n      // can't actually receive DOM focus, so leave focus where it is rather\n      // than desyncing React state from real keyboard focus at a boundary.\n      if (resolved === null || isDisabled(resolved)) return;\n      onFocusedIndexChange(resolved);\n    },\n    [focusedIndex, isDisabled, itemCount, onFocusedIndexChange],\n  );\n\n  return useCallback(\n    (event: ReactKeyboardEvent<HTMLElement>) => {\n      const row = Math.floor(focusedIndex / columns);\n      let next = focusedIndex;\n      let handled = false;\n\n      switch (event.key) {\n        case \"ArrowRight\":\n          next = focusedIndex + 1;\n          handled = true;\n          break;\n        case \"ArrowLeft\":\n          next = focusedIndex - 1;\n          handled = true;\n          break;\n        case \"ArrowDown\":\n          next = focusedIndex + columns;\n          handled = true;\n          break;\n        case \"ArrowUp\":\n          next = focusedIndex - columns;\n          handled = true;\n          break;\n        case \"Home\":\n          next = row * columns;\n          handled = true;\n          break;\n        case \"End\":\n          next = Math.min(row * columns + columns - 1, itemCount - 1);\n          handled = true;\n          break;\n        case \"Enter\":\n        case \" \":\n          if (!isDisabled(focusedIndex)) {\n            event.preventDefault();\n            onSelect(focusedIndex);\n          }\n          return;\n        default:\n          return;\n      }\n\n      if (!handled) return;\n      event.preventDefault();\n      moveFocus(next);\n    },\n    [columns, focusedIndex, isDisabled, itemCount, moveFocus, onSelect],\n  );\n}\n",
      "type": "registry:lib",
      "target": "~/components/ui/internal/useCalendarCellGridKeyboard.ts"
    }
  ]
}
