{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "event-calendar",
  "type": "registry:component",
  "title": "Event calendar",
  "description": "A scheduling calendar with a week time grid, a month grid with overflow popovers, and a grouped agenda, built on Intl with no date library.",
  "categories": [
    "tables-&-lists"
  ],
  "dependencies": [
    "@tabler/icons-react",
    "@radix-ui/react-popover"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/event-calendar.tsx",
      "type": "registry:component",
      "target": "components/overtrue/event-calendar.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport {\n  IconCalendarMonth,\n  IconCalendarOff,\n  IconCalendarWeek,\n  IconChevronDown,\n  IconChevronLeft,\n  IconChevronRight,\n  IconListDetails,\n  IconMapPin,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport type EventCalendarView = \"week\" | \"month\" | \"agenda\";\nexport type WeekdayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;\n\n/** A series token from the theme, or any CSS color. */\nexport type EventCalendarColor =\n  | \"chart-1\"\n  | \"chart-2\"\n  | \"chart-3\"\n  | \"chart-4\"\n  | \"chart-5\"\n  | \"primary\"\n  | \"muted\"\n  | (string & {});\n\nexport interface EventCalendarAttendee {\n  name: string;\n  /** Avatar image URL. Initials are shown without one. */\n  image?: string;\n}\n\nexport interface EventCalendarEvent {\n  id: string;\n  title: string;\n  /** Local start time. */\n  start: Date;\n  /** Local end time. For all-day events an end at midnight is exclusive. */\n  end: Date;\n  /** Shown in the all-day lane. Events of 24 hours or longer go there too. */\n  allDay?: boolean;\n  /** Defaults to \"chart-1\". */\n  color?: EventCalendarColor;\n  location?: string;\n  attendees?: EventCalendarAttendee[];\n}\n\n/** A span of local time. `end` is exclusive. */\nexport interface EventCalendarRange {\n  start: Date;\n  end: Date;\n}\n\nexport interface EventCalendarSlotDetails {\n  /** True for whole days: the all-day lane, a month cell, or a day picked from the keyboard. */\n  allDay: boolean;\n  source: \"click\" | \"drag\" | \"keyboard\";\n}\n\nexport interface EventCalendarEventClickDetails {\n  view: EventCalendarView;\n  /** The chip that was activated, for anchoring a popover. */\n  element: HTMLElement;\n}\n\nexport interface EventCalendarRenderInfo {\n  view: EventCalendarView | \"popover\";\n  /** The visible part of the event: one day of a multi-day event. */\n  start: Date;\n  end: Date;\n  /** Resolved CSS color of the series. */\n  color: string;\n  /** Formatted time range of the visible part, or the all-day label. */\n  timeLabel: string;\n  /** True when the chip is too short for more than one line. */\n  compact: boolean;\n  allDay: boolean;\n  selected: boolean;\n}\n\n/** Interface copy. Dates, weekdays, and times are localized through `locale`. */\nexport interface EventCalendarLabels {\n  today: string;\n  previous: (view: EventCalendarView) => string;\n  next: (view: EventCalendarView) => string;\n  views: Record<EventCalendarView, string>;\n  viewSwitcher: string;\n  allDay: string;\n  /** Visible text of the overflow button in a month cell. */\n  more: (count: number) => string;\n  /** Accessible name of the overflow button. */\n  showMore: (count: number, day: string) => string;\n  showFewer: string;\n  events: (count: number) => string;\n  noEvents: string;\n  noEventsDescription: string;\n  todayMarker: string;\n  currentTime: string;\n  dayOf: (day: number, total: number) => string;\n  loading: string;\n}\n\nexport interface EventCalendarProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"onChange\" | \"defaultValue\"\n> {\n  events: EventCalendarEvent[];\n  view?: EventCalendarView;\n  defaultView?: EventCalendarView;\n  onViewChange?: (view: EventCalendarView) => void;\n  /** Views offered by the switcher, in order. The switcher hides when there is one. */\n  views?: EventCalendarView[];\n  /** The focused day. The visible week or month is the one that contains it. */\n  date?: Date;\n  defaultDate?: Date;\n  onDateChange?: (date: Date) => void;\n  /** Called with the visible range on mount and whenever it changes, for fetching. */\n  onRangeChange?: (range: EventCalendarRange, view: EventCalendarView) => void;\n  /** The current moment, for the today marker and the time line. Defaults to the clock, ticking each minute. */\n  now?: Date;\n  /** BCP 47 locale for dates, weekdays, and times. Defaults to the runtime locale. */\n  locale?: string;\n  /** First day of the week. Defaults to the locale's. */\n  weekStartsOn?: WeekdayIndex;\n  /** Drop Saturday and Sunday from the week and month grids. */\n  hideWeekends?: boolean;\n  /** First and last hour of the time grid. Defaults to 0 and 24. */\n  startHour?: number;\n  endHour?: number;\n  /** Shades time outside these hours. Pass null to turn shading off. */\n  workingHours?: { start: number; end: number; days?: WeekdayIndex[] } | null;\n  /** The hour scrolled to the top of the week grid on mount. Defaults to the start of working hours. */\n  scrollToHour?: number;\n  /** Height of one hour in the week grid, in px. Defaults to 48. */\n  hourHeight?: number;\n  /** Narrowest day column before the week grid scrolls sideways, in px. Defaults to 56. */\n  minDayWidth?: number;\n  /** Length of the slot a click on the time grid creates, in minutes. Defaults to 30. */\n  slotMinutes?: number;\n  /** Granularity of drag selections, in minutes. Defaults to 15. */\n  snapMinutes?: number;\n  /** Drag across the time grid to select a range. Defaults to true when `onSlotClick` is set. */\n  selectable?: boolean;\n  /** Events shown per month cell before \"+N more\". Defaults to 3. */\n  maxEventsPerDay?: number;\n  /** Days the agenda covers from `date`. Defaults to 14. */\n  agendaDays?: number;\n  /** Height of the calendar. Defaults to 640 for week and agenda; month grows to fit. */\n  height?: number | string;\n  /** Highlights an event. Leave undefined to highlight the last clicked one. */\n  selectedEventId?: string | null;\n  onEventClick?: (\n    event: EventCalendarEvent,\n    details: EventCalendarEventClickDetails,\n  ) => void;\n  /** Called for a click on empty time or a day, and for a drag selection in the week grid. */\n  onSlotClick?: (\n    start: Date,\n    end: Date,\n    details: EventCalendarSlotDetails,\n  ) => void;\n  /** Replaces the contents of every event chip. The chip, its color, and its accessible name stay. */\n  renderEvent?: (\n    event: EventCalendarEvent,\n    info: EventCalendarRenderInfo,\n  ) => React.ReactNode;\n  /** Formats a time of day. Defaults to Intl hours and minutes. */\n  formatTime?: (date: Date) => string;\n  /** Shows a progress line and marks the grid busy while events load. */\n  loading?: boolean;\n  /** Extra controls at the end of the header, such as a New event button. */\n  actions?: React.ReactNode;\n  labels?: Partial<EventCalendarLabels>;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Dates                                                                     */\n/* ------------------------------------------------------------------------ */\n\nconst DAY_MS = 86_400_000;\nconst startOfDay = (date: Date) =>\n  new Date(date.getFullYear(), date.getMonth(), date.getDate());\nconst addDays = (date: Date, days: number) =>\n  new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);\nconst daysInMonth = (year: number, month: number) =>\n  new Date(year, month + 1, 0).getDate();\n/** Sortable key for a calendar day. */\nconst dayKey = (date: Date) =>\n  date.getFullYear() * 10_000 + date.getMonth() * 100 + date.getDate();\nconst fromKey = (key: number) =>\n  new Date(Math.floor(key / 10_000), Math.floor(key / 100) % 100, key % 100);\nconst sameDay = (a: Date, b: Date) => dayKey(a) === dayKey(b);\n/** Whole days since the epoch, immune to daylight-saving shifts. */\nconst epochDay = (date: Date) =>\n  Math.round(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS);\nconst isWeekend = (date: Date) => date.getDay() === 0 || date.getDay() === 6;\nconst minuteOfDay = (date: Date) => date.getHours() * 60 + date.getMinutes();\n/** A wall-clock time on a day; minute 1440 is the next midnight. */\nconst atMinute = (day: Date, minute: number) =>\n  new Date(day.getFullYear(), day.getMonth(), day.getDate(), 0, minute);\nconst clamp = (value: number, min: number, max: number) =>\n  Math.min(max, Math.max(min, value));\n\nfunction addMonths(date: Date, months: number) {\n  const first = new Date(date.getFullYear(), date.getMonth() + months, 1);\n  const year = first.getFullYear();\n  const month = first.getMonth();\n  return new Date(year, month, Math.min(date.getDate(), daysInMonth(year, month)));\n}\n\nfunction startOfWeek(date: Date, weekStartsOn: number) {\n  const day = startOfDay(date);\n  return addDays(day, -((day.getDay() - weekStartsOn + 7) % 7));\n}\n\n/** The span a view shows for a date. Week and month ranges start on `weekStartsOn`. */\nexport function getVisibleRange(\n  view: EventCalendarView,\n  date: Date,\n  options: { weekStartsOn?: WeekdayIndex; agendaDays?: number } = {},\n): EventCalendarRange {\n  const weekStartsOn = options.weekStartsOn ?? 0;\n  if (view === \"week\") {\n    const start = startOfWeek(date, weekStartsOn);\n    return { start, end: addDays(start, 7) };\n  }\n  if (view === \"month\") {\n    const start = startOfWeek(\n      new Date(date.getFullYear(), date.getMonth(), 1),\n      weekStartsOn,\n    );\n    return { start, end: addDays(start, 42) };\n  }\n  const start = startOfDay(date);\n  return { start, end: addDays(start, options.agendaDays ?? 14) };\n}\n\ntype IntlLocaleWithWeek = Intl.Locale & {\n  getWeekInfo?: () => { firstDay: number };\n  weekInfo?: { firstDay: number };\n};\n\nfunction localeWeekStart(locale?: string): WeekdayIndex {\n  try {\n    const resolved = new Intl.Locale(\n      locale ?? new Intl.DateTimeFormat().resolvedOptions().locale,\n    ) as IntlLocaleWithWeek;\n    const info = resolved.getWeekInfo?.() ?? resolved.weekInfo;\n    if (info?.firstDay) return (info.firstDay % 7) as WeekdayIndex;\n  } catch {\n    // Older engines: fall through to Sunday.\n  }\n  return 0;\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\nfunction dtf(locale: string | undefined, options: Intl.DateTimeFormatOptions) {\n  const key = `${locale ?? \"\"}|${JSON.stringify(options)}`;\n  let cached = formatters.get(key);\n  if (!cached) {\n    cached = new Intl.DateTimeFormat(locale, options);\n    formatters.set(key, cached);\n  }\n  return cached;\n}\n\nfunction formatRange(format: Intl.DateTimeFormat, start: Date, end: Date) {\n  try {\n    return format.formatRange(start, end);\n  } catch {\n    return `${format.format(start)} – ${format.format(end)}`;\n  }\n}\n\ninterface Formatters {\n  time: (date: Date) => string;\n  /** Hours and minutes without a day period, for the narrow time-line label. */\n  clock: (date: Date) => string;\n  shortTime: (date: Date) => string;\n  timeRange: (start: Date, end: Date) => string;\n  hour: (hour: number) => string;\n  longDay: (date: Date) => string;\n  dayRange: (first: Date, last: Date) => string;\n  dateTimeRange: (start: Date, end: Date) => string;\n}\n\nfunction createFormatters(\n  locale: string | undefined,\n  formatTime?: (date: Date) => string,\n): Formatters {\n  const clock = dtf(locale, { hour: \"numeric\", minute: \"2-digit\" });\n  const cycle = clock.resolvedOptions().hourCycle;\n  const twelveHour = cycle === \"h12\" || cycle === \"h11\";\n  const hourOnly = dtf(locale, { hour: \"numeric\" });\n  const time = formatTime ?? ((date: Date) => clock.format(date));\n  return {\n    time,\n    clock:\n      formatTime ??\n      ((date) =>\n        clock\n          .formatToParts(date)\n          .filter((part) => part.type !== \"dayPeriod\")\n          .map((part) => part.value)\n          .join(\"\")\n          .trim()),\n    shortTime:\n      formatTime ??\n      ((date) =>\n        twelveHour && date.getMinutes() === 0\n          ? hourOnly.format(date)\n          : clock.format(date)),\n    timeRange: (start, end) =>\n      formatTime\n        ? `${formatTime(start)} – ${formatTime(end)}`\n        : formatRange(clock, start, end),\n    hour: (hour) =>\n      twelveHour\n        ? hourOnly.format(new Date(2026, 0, 1, hour))\n        : dtf(locale, { hour: \"2-digit\", minute: \"2-digit\", hourCycle: \"h23\" }).format(\n            new Date(2026, 0, 1, hour),\n          ),\n    longDay: (date) =>\n      dtf(locale, { weekday: \"long\", month: \"long\", day: \"numeric\" }).format(date),\n    dayRange: (first, last) =>\n      sameDay(first, last)\n        ? dtf(locale, { weekday: \"long\", month: \"long\", day: \"numeric\" }).format(first)\n        : formatRange(dtf(locale, { month: \"long\", day: \"numeric\" }), first, last),\n    dateTimeRange: (start, end) =>\n      formatTime\n        ? `${dtf(locale, { weekday: \"short\", month: \"short\", day: \"numeric\" }).format(start)} ${formatTime(start)} – ${dtf(locale, { weekday: \"short\", month: \"short\", day: \"numeric\" }).format(end)} ${formatTime(end)}`\n        : formatRange(\n            dtf(locale, {\n              weekday: \"short\",\n              month: \"short\",\n              day: \"numeric\",\n              hour: \"numeric\",\n              minute: \"2-digit\",\n            }),\n            start,\n            end,\n          ),\n  };\n}\n\n/** Title parts for the header; the year is quieter than the dates. */\nfunction titleParts(\n  view: EventCalendarView,\n  first: Date,\n  last: Date,\n  locale?: string,\n) {\n  try {\n    const parts =\n      view === \"month\"\n        ? dtf(locale, { month: \"long\", year: \"numeric\" }).formatToParts(first)\n        : dtf(locale, {\n            month: \"short\",\n            day: \"numeric\",\n            year: \"numeric\",\n          }).formatRangeToParts(first, last);\n    return parts.map((part, index) => ({\n      value: part.value,\n      quiet:\n        part.type === \"year\" ||\n        (part.type === \"literal\" && parts[index + 1]?.type === \"year\" && index > 0),\n    }));\n  } catch {\n    return [{ value: `${first.toDateString()} – ${last.toDateString()}`, quiet: false }];\n  }\n}\n\nconst capitalize = (text: string, locale?: string) =>\n  text.charAt(0).toLocaleUpperCase(locale) + text.slice(1);\n\n/* ------------------------------------------------------------------------ */\n/* Layout                                                                    */\n/* ------------------------------------------------------------------------ */\n\nconst SERIES: Record<string, string> = {\n  \"chart-1\": \"var(--color-chart-1)\",\n  \"chart-2\": \"var(--color-chart-2)\",\n  \"chart-3\": \"var(--color-chart-3)\",\n  \"chart-4\": \"var(--color-chart-4)\",\n  \"chart-5\": \"var(--color-chart-5)\",\n  primary: \"var(--color-primary)\",\n  muted: \"var(--color-muted-foreground)\",\n};\nconst resolveColor = (color?: string) =>\n  color ? (SERIES[color] ?? color) : SERIES[\"chart-1\"];\n\ninterface Item {\n  event: EventCalendarEvent;\n  start: Date;\n  end: Date;\n  /** Lives in the all-day lane: all-day, or 24 hours and longer. */\n  lane: boolean;\n  first: number;\n  last: number;\n  color: string;\n}\n\nfunction normalize(events: EventCalendarEvent[]): Item[] {\n  return events\n    .map((event) => {\n      const start = event.start;\n      const end = event.end.getTime() < start.getTime() ? start : event.end;\n      const lane =\n        !!event.allDay || end.getTime() - start.getTime() >= DAY_MS;\n      const first = dayKey(start);\n      let last: number;\n      if (event.allDay) {\n        const endDay = startOfDay(end);\n        last =\n          end.getTime() === endDay.getTime() && dayKey(endDay) > first\n            ? dayKey(addDays(endDay, -1))\n            : dayKey(end);\n      } else {\n        last = end > start ? dayKey(new Date(end.getTime() - 1)) : first;\n      }\n      return {\n        event,\n        start,\n        end,\n        lane,\n        first,\n        last: Math.max(first, last),\n        color: resolveColor(event.color),\n      };\n    })\n    .sort(\n      (a, b) =>\n        a.start.getTime() - b.start.getTime() ||\n        b.end.getTime() - a.end.getTime() ||\n        a.event.title.localeCompare(b.event.title),\n    );\n}\n\ninterface Span {\n  item: Item;\n  startCol: number;\n  endCol: number;\n  lane: number;\n  continuesBefore: boolean;\n  continuesAfter: boolean;\n}\n\n/** Packs items into the lowest free lane across the columns they cover. */\nfunction packLanes(\n  items: Item[],\n  days: Date[],\n  timedOnStartDay: boolean,\n): Span[] {\n  const keys = days.map(dayKey);\n  const spans: Omit<Span, \"lane\">[] = [];\n  for (const item of items) {\n    if (!item.lane && !timedOnStartDay) continue;\n    const last = item.lane ? item.last : item.first;\n    let startCol = -1;\n    let endCol = -1;\n    keys.forEach((key, col) => {\n      if (key >= item.first && key <= last) {\n        if (startCol < 0) startCol = col;\n        endCol = col;\n      }\n    });\n    if (startCol < 0) continue;\n    spans.push({\n      item,\n      startCol,\n      endCol,\n      continuesBefore: item.first < keys[startCol],\n      continuesAfter: last > keys[endCol],\n    });\n  }\n  spans.sort(\n    (a, b) =>\n      Number(!a.item.lane) - Number(!b.item.lane) ||\n      a.startCol - b.startCol ||\n      b.endCol - b.startCol - (a.endCol - a.startCol) ||\n      a.item.start.getTime() - b.item.start.getTime(),\n  );\n  const occupied: boolean[][] = [];\n  return spans.map((span) => {\n    let lane = 0;\n    while (\n      occupied[lane]?.slice(span.startCol, span.endCol + 1).some(Boolean)\n    )\n      lane++;\n    occupied[lane] ??= [];\n    for (let col = span.startCol; col <= span.endCol; col++)\n      occupied[lane][col] = true;\n    return { ...span, lane };\n  });\n}\n\ninterface Segment {\n  item: Item;\n  startMin: number;\n  endMin: number;\n  /** The visual end, stretched so short events stay readable. */\n  visualEnd: number;\n  col: number;\n  span: number;\n  cols: number;\n}\n\n/** Clips timed events to a day and lays overlapping ones out side by side. */\nfunction layoutDay(\n  items: Item[],\n  day: Date,\n  lo: number,\n  hi: number,\n  minMinutes: number,\n): Segment[] {\n  const key = dayKey(day);\n  const segments: Segment[] = [];\n  for (const item of items) {\n    if (item.lane || key < item.first || key > item.last) continue;\n    const s = item.first === key ? minuteOfDay(item.start) : 0;\n    const e = dayKey(item.end) === key ? minuteOfDay(item.end) : 1440;\n    if (s >= hi || (e <= lo && e > s)) continue;\n    const startMin = clamp(s, lo, hi);\n    const endMin = clamp(Math.max(e, s), lo, hi);\n    segments.push({\n      item,\n      startMin,\n      endMin,\n      visualEnd: Math.min(hi, Math.max(endMin, startMin + minMinutes)),\n      col: 0,\n      span: 1,\n      cols: 1,\n    });\n  }\n  segments.sort(\n    (a, b) => a.startMin - b.startMin || b.visualEnd - a.visualEnd,\n  );\n\n  let cluster: Segment[] = [];\n  let clusterEnd = -Infinity;\n  const flush = () => {\n    const columns: Segment[][] = [];\n    for (const segment of cluster) {\n      let col = columns.findIndex(\n        (column) => column[column.length - 1].visualEnd <= segment.startMin,\n      );\n      if (col < 0) {\n        col = columns.length;\n        columns.push([]);\n      }\n      columns[col].push(segment);\n      segment.col = col;\n    }\n    for (const segment of cluster) {\n      segment.cols = columns.length;\n      let span = 1;\n      while (\n        segment.col + span < columns.length &&\n        !columns[segment.col + span].some(\n          (other) =>\n            other.startMin < segment.visualEnd &&\n            other.visualEnd > segment.startMin,\n        )\n      )\n        span++;\n      segment.span = span;\n    }\n  };\n  for (const segment of segments) {\n    if (cluster.length && segment.startMin >= clusterEnd) {\n      flush();\n      cluster = [];\n      clusterEnd = -Infinity;\n    }\n    cluster.push(segment);\n    clusterEnd = Math.max(clusterEnd, segment.visualEnd);\n  }\n  if (cluster.length) flush();\n  return segments;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Shared pieces                                                             */\n/* ------------------------------------------------------------------------ */\n\nconst EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\";\nconst keyframes =\n  \"@keyframes event-calendar-pop{from{opacity:0;transform:translateY(-4px) scale(.97)}to{opacity:1;transform:none}}\" +\n  \"@keyframes event-calendar-load{from{transform:translateX(-100%)}to{transform:translateX(320%)}}\";\n\nconst GUTTER = 48;\nconst LANE = 24;\nconst MONTH_TOP = 32;\nconst MONTH_LANE = 22;\n\nconst defaultLabels: EventCalendarLabels = {\n  today: \"Today\",\n  previous: (view) =>\n    view === \"week\" ? \"Previous week\" : view === \"month\" ? \"Previous month\" : \"Previous days\",\n  next: (view) =>\n    view === \"week\" ? \"Next week\" : view === \"month\" ? \"Next month\" : \"Next days\",\n  views: { week: \"Week\", month: \"Month\", agenda: \"Agenda\" },\n  viewSwitcher: \"Calendar view\",\n  allDay: \"All day\",\n  more: (count) => `+${count} more`,\n  showMore: (count, day) =>\n    `Show ${count} more ${count === 1 ? \"event\" : \"events\"} on ${day}`,\n  showFewer: \"Show fewer all-day events\",\n  events: (count) => (count === 0 ? \"no events\" : count === 1 ? \"1 event\" : `${count} events`),\n  noEvents: \"Nothing scheduled\",\n  noEventsDescription: \"These days are clear. Pick another range or add an event.\",\n  todayMarker: \"today\",\n  currentTime: \"Current time\",\n  dayOf: (day, total) => `Day ${day} of ${total}`,\n  loading: \"Loading events\",\n};\n\nconst DEFAULT_VIEWS: EventCalendarView[] = [\"week\", \"month\", \"agenda\"];\nconst DEFAULT_WORKING_HOURS = { start: 9, end: 17 };\nconst VIEW_ICONS = {\n  week: IconCalendarWeek,\n  month: IconCalendarMonth,\n  agenda: IconListDetails,\n} as const;\n\n/* Chip recipe: the series color tints the surface, an inset accent carries it at full strength. */\nconst chip =\n  \"group/event @container/chip overflow-hidden border text-start outline-none select-none [border-color:color-mix(in_oklab,var(--event-color)_24%,transparent)] [background-color:color-mix(in_oklab,var(--event-color)_12%,var(--color-card))] shadow-[0_0_0_1px_var(--color-card)] transition-[background-color,border-color,box-shadow] duration-150 hover:[background-color:color-mix(in_oklab,var(--event-color)_19%,var(--color-card))] focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\";\nconst chipSelected =\n  \"z-10 [border-color:color-mix(in_oklab,var(--event-color)_50%,transparent)] [background-color:color-mix(in_oklab,var(--event-color)_22%,var(--color-card))] ring-2 ring-primary/30 shadow-[0_0_0_1px_var(--color-card),0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_0_0_1px_var(--color-card),0_8px_22px_-10px_color-mix(in_oklab,var(--color-primary)_55%,transparent)] hover:[background-color:color-mix(in_oklab,var(--event-color)_24%,var(--color-card))]\";\nconst titleInk =\n  \"[color:color-mix(in_oklab,var(--event-color)_38%,var(--color-foreground))]\";\nconst accent =\n  \"pointer-events-none absolute inset-y-[3px] start-[3px] w-[3px] rounded-full bg-[var(--event-color)]\";\n\ninterface Ctx {\n  locale?: string;\n  labels: EventCalendarLabels;\n  fmt: Formatters;\n  today: Date;\n  now: Date;\n  focusDay: Date;\n  selectedId: string | null;\n  renderEvent?: EventCalendarProps[\"renderEvent\"];\n  slot?: EventCalendarProps[\"onSlotClick\"];\n  activate: (\n    event: EventCalendarEvent,\n    element: HTMLElement,\n    view: EventCalendarView,\n  ) => void;\n  eventLabel: (item: Item) => string;\n  timeLabel: (item: Item, day?: Date) => string;\n  countOn: (day: Date) => number;\n  onDayKeyDown: (event: React.KeyboardEvent, day: Date) => void;\n  onEventKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;\n  pickDay: (day: Date) => void;\n  openWeek?: (day: Date) => void;\n}\n\nfunction EventChip({\n  ctx,\n  item,\n  view,\n  tabbable,\n  compact = false,\n  start,\n  end,\n  className,\n  style,\n  children,\n}: {\n  ctx: Ctx;\n  item: Item;\n  view: EventCalendarView;\n  tabbable: boolean;\n  compact?: boolean;\n  start?: Date;\n  end?: Date;\n  className?: string;\n  style?: React.CSSProperties;\n  children: React.ReactNode;\n}) {\n  const selected = ctx.selectedId === item.event.id;\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"event-calendar-event\"\n      data-event={item.event.id}\n      data-event-nav=\"\"\n      data-selected={selected ? \"\" : undefined}\n      data-all-day={item.lane ? \"\" : undefined}\n      tabIndex={tabbable ? 0 : -1}\n      aria-label={ctx.eventLabel(item)}\n      onClick={(event) => ctx.activate(item.event, event.currentTarget, view)}\n      onKeyDown={ctx.onEventKeyDown}\n      style={{ \"--event-color\": item.color, ...style } as React.CSSProperties}\n      className={cn(chip, className, selected && chipSelected)}\n    >\n      {ctx.renderEvent\n        ? ctx.renderEvent(item.event, {\n            view,\n            start: start ?? item.start,\n            end: end ?? item.end,\n            color: item.color,\n            timeLabel: ctx.timeLabel(item),\n            compact,\n            allDay: item.lane,\n            selected,\n          })\n        : children}\n    </button>\n  );\n}\n\nfunction Initials({ attendees }: { attendees: EventCalendarAttendee[] }) {\n  const shown = attendees.slice(0, 3);\n  const extra = attendees.length - shown.length;\n  return (\n    <span aria-hidden=\"true\" className=\"flex shrink-0 items-center -space-x-1.5\">\n      {shown.map((person, index) => {\n        const tone = `var(--color-chart-${(hash(person.name) % 5) + 1})`;\n        return person.image ? (\n          <img\n            key={`${person.name}-${index}`}\n            src={person.image}\n            alt=\"\"\n            className=\"size-7 rounded-full object-cover ring-2 ring-card\"\n          />\n        ) : (\n          <span\n            key={`${person.name}-${index}`}\n            style={{ \"--tone\": tone } as React.CSSProperties}\n            className=\"flex size-7 items-center justify-center rounded-full text-[11px] font-semibold ring-2 ring-card [background-color:color-mix(in_oklab,var(--tone)_18%,var(--color-card))] [color:color-mix(in_oklab,var(--tone)_45%,var(--color-foreground))]\"\n          >\n            {initials(person.name)}\n          </span>\n        );\n      })}\n      {extra > 0 && (\n        <span className=\"flex size-7 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-muted-foreground tabular-nums ring-2 ring-card\">\n          +{extra}\n        </span>\n      )}\n    </span>\n  );\n}\n\nfunction hash(text: string) {\n  let value = 0;\n  for (let i = 0; i < text.length; i++) value = (value * 31 + text.charCodeAt(i)) >>> 0;\n  return value;\n}\n\nfunction initials(name: string) {\n  const words = name.trim().split(/\\s+/);\n  return (\n    (words[0]?.[0] ?? \"\") + (words.length > 1 ? (words[words.length - 1][0] ?? \"\") : \"\")\n  ).toUpperCase();\n}\n\n/* ------------------------------------------------------------------------ */\n/* Component                                                                 */\n/* ------------------------------------------------------------------------ */\n\n/** A scheduling calendar with a week time grid, a month grid, and an agenda. */\nexport function EventCalendar({\n  events,\n  view: viewProp,\n  defaultView = \"week\",\n  onViewChange,\n  views = DEFAULT_VIEWS,\n  date: dateProp,\n  defaultDate,\n  onDateChange,\n  onRangeChange,\n  now: nowProp,\n  locale,\n  weekStartsOn: weekStartsOnProp,\n  hideWeekends = false,\n  startHour = 0,\n  endHour = 24,\n  workingHours = DEFAULT_WORKING_HOURS,\n  scrollToHour,\n  hourHeight = 48,\n  minDayWidth = 56,\n  slotMinutes = 30,\n  snapMinutes = 15,\n  selectable,\n  maxEventsPerDay = 3,\n  agendaDays = 14,\n  height,\n  selectedEventId: selectedProp,\n  onEventClick,\n  onSlotClick,\n  renderEvent,\n  formatTime,\n  loading = false,\n  actions,\n  labels: labelsProp,\n  className,\n  style,\n  ...props\n}: EventCalendarProps) {\n  const labels = { ...defaultLabels, ...labelsProp };\n  const uid = React.useId();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const bodyRef = React.useRef<HTMLDivElement>(null);\n\n  /* ---- Clock ---- */\n  const [clock, setClock] = React.useState(() => new Date());\n  React.useEffect(() => {\n    if (nowProp) return;\n    const tick = () => setClock(new Date());\n    tick();\n    const timer = window.setInterval(tick, 60_000);\n    return () => window.clearInterval(timer);\n  }, [nowProp]);\n  const now = nowProp ?? clock;\n  const todayKey = dayKey(now);\n  const today = React.useMemo(() => startOfDay(now), [todayKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  /* ---- Controlled and uncontrolled state ---- */\n  const [viewState, setViewState] = React.useState<EventCalendarView>(defaultView);\n  const view = viewProp ?? viewState;\n  const [dateState, setDateState] = React.useState(() =>\n    startOfDay(defaultDate ?? new Date()),\n  );\n  const date = startOfDay(dateProp ?? dateState);\n  const [selectedState, setSelectedState] = React.useState<string | null>(null);\n  const selectedId = selectedProp !== undefined ? selectedProp : selectedState;\n\n  const weekStartsOn = React.useMemo(\n    () => weekStartsOnProp ?? localeWeekStart(locale),\n    [weekStartsOnProp, locale],\n  );\n  const range = getVisibleRange(view, date, { weekStartsOn, agendaDays });\n  const rangeKey = `${view}|${dayKey(range.start)}|${dayKey(range.end)}`;\n  const items = React.useMemo(() => normalize(events), [events]);\n  const fmt = React.useMemo(\n    () => createFormatters(locale, formatTime),\n    [locale, formatTime],\n  );\n\n  const visible = (day: Date) => !hideWeekends || !isWeekend(day);\n  /** The focused day, moved off hidden weekends. */\n  const focusDay = visible(date)\n    ? date\n    : addDays(date, date.getDay() === 6 ? -1 : 1);\n\n  const changeDate = (next: Date) => {\n    const day = startOfDay(next);\n    if (sameDay(day, date)) return;\n    if (dateProp === undefined) setDateState(day);\n    onDateChange?.(day);\n  };\n  const changeView = (next: EventCalendarView) => {\n    if (next === view) return;\n    if (viewProp === undefined) setViewState(next);\n    onViewChange?.(next);\n  };\n\n  /* ---- Range notifications, announcements, and motion ---- */\n  const rangeCallback = React.useRef(onRangeChange);\n  rangeCallback.current = onRangeChange;\n  const slide = React.useRef(0);\n  const mounted = React.useRef(false);\n  const [announcement, setAnnouncement] = React.useState(\"\");\n\n  const visibleDays = React.useMemo(() => {\n    const out: Date[] = [];\n    for (let d = range.start; d < range.end; d = addDays(d, 1)) out.push(d);\n    return out;\n  }, [rangeKey]); // eslint-disable-line react-hooks/exhaustive-deps\n  const shownDays = visibleDays.filter(visible);\n  const firstShown = shownDays[0] ?? range.start;\n  const lastShown = shownDays[shownDays.length - 1] ?? addDays(range.end, -1);\n  const title = titleParts(view, view === \"month\" ? date : firstShown, lastShown, locale);\n  const titleText = title.map((part) => part.value).join(\"\");\n  const rangeCount = React.useMemo(() => {\n    const lo = dayKey(range.start);\n    const hi = dayKey(addDays(range.end, -1));\n    return items.filter((item) => item.last >= lo && item.first <= hi).length;\n  }, [items, rangeKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  React.useEffect(() => {\n    rangeCallback.current?.({ start: range.start, end: range.end }, view);\n    if (!mounted.current) {\n      mounted.current = true;\n      return;\n    }\n    setAnnouncement(`${titleText}, ${labels.events(rangeCount)}`);\n  }, [rangeKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  React.useLayoutEffect(() => {\n    const direction = slide.current;\n    slide.current = 0;\n    const body = bodyRef.current;\n    if (!direction || !body) return;\n    if (window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches) return;\n    body.animate?.(\n      [\n        { opacity: 0.35, transform: `translateX(${direction * 14}px)` },\n        { opacity: 1, transform: \"none\" },\n      ],\n      { duration: 300, easing: EASE },\n    );\n  }, [rangeKey]);\n\n  const shift = (direction: -1 | 1) => {\n    slide.current = direction;\n    changeDate(\n      view === \"week\"\n        ? addDays(date, 7 * direction)\n        : view === \"month\"\n          ? addMonths(date, direction)\n          : addDays(date, agendaDays * direction),\n    );\n  };\n  const goToday = () => {\n    slide.current = dayKey(today) > dayKey(date) ? 1 : dayKey(today) < dayKey(date) ? -1 : 0;\n    changeDate(today);\n  };\n\n  /* ---- Focus ---- */\n  const focusRequest = React.useRef<number | null>(null);\n  const focusDayTarget = React.useCallback((day: Date) => {\n    rootRef.current\n      ?.querySelector<HTMLElement>(`[data-day-target=\"${dayKey(day)}\"]`)\n      ?.focus({ preventScroll: false });\n  }, []);\n  React.useEffect(() => {\n    if (focusRequest.current === null || focusRequest.current !== dayKey(focusDay))\n      return;\n    focusRequest.current = null;\n    focusDayTarget(focusDay);\n  });\n\n  const step = (day: Date, direction: number) => {\n    let next = addDays(day, direction);\n    while (!visible(next)) next = addDays(next, direction);\n    return next;\n  };\n  const moveTo = (next: Date) => {\n    const target = visible(next) ? next : step(next, next > date ? 1 : -1);\n    const outside = target < range.start || target >= range.end;\n    if (outside && view !== \"agenda\") slide.current = target > date ? 1 : -1;\n    if (view === \"month\" && (target.getMonth() !== date.getMonth() || target.getFullYear() !== date.getFullYear()))\n      slide.current = target > date ? 1 : -1;\n    focusRequest.current = dayKey(target);\n    if (sameDay(target, focusDay)) {\n      focusRequest.current = null;\n      focusDayTarget(target);\n    } else changeDate(target);\n  };\n\n  const onDayKeyDown = (event: React.KeyboardEvent, day: Date) => {\n    const week = view === \"week\";\n    const rowStart = startOfWeek(day, weekStartsOn);\n    let next: Date | null = null;\n    switch (event.key) {\n      case \"ArrowLeft\":\n        next = step(day, -1);\n        break;\n      case \"ArrowRight\":\n        next = step(day, 1);\n        break;\n      case \"ArrowUp\":\n        if (week) return;\n        next = addDays(day, -7);\n        break;\n      case \"ArrowDown\":\n        if (week) {\n          event.preventDefault();\n          rootRef.current\n            ?.querySelector<HTMLElement>('[data-event-nav][tabindex=\"0\"]')\n            ?.focus();\n          return;\n        }\n        next = addDays(day, 7);\n        break;\n      case \"PageUp\":\n        next = week ? addDays(day, -7) : addMonths(day, event.shiftKey ? -12 : -1);\n        break;\n      case \"PageDown\":\n        next = week ? addDays(day, 7) : addMonths(day, event.shiftKey ? 12 : 1);\n        break;\n      case \"Home\":\n        next = visible(rowStart) ? rowStart : step(rowStart, 1);\n        break;\n      case \"End\": {\n        const rowEnd = addDays(rowStart, 6);\n        next = visible(rowEnd) ? rowEnd : step(rowEnd, -1);\n        break;\n      }\n      default:\n        return;\n    }\n    event.preventDefault();\n    moveTo(next);\n  };\n\n  const onEventKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {\n    const root = rootRef.current;\n    if (!root) return;\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      const list = Array.from(\n        root.querySelectorAll<HTMLElement>('[data-event-nav][tabindex=\"0\"]'),\n      );\n      const index = list.indexOf(event.currentTarget);\n      const next = list[index + (event.key === \"ArrowDown\" ? 1 : -1)];\n      event.preventDefault();\n      if (next) next.focus();\n      else if (event.key === \"ArrowUp\") focusDayTarget(focusDay);\n    } else if (event.key === \"Escape\") {\n      event.preventDefault();\n      focusDayTarget(focusDay);\n    } else if (event.key === \"ArrowLeft\" || event.key === \"ArrowRight\") {\n      event.preventDefault();\n      moveTo(step(focusDay, event.key === \"ArrowLeft\" ? -1 : 1));\n    }\n  };\n\n  /* ---- Events ---- */\n  const activate = (\n    event: EventCalendarEvent,\n    element: HTMLElement,\n    from: EventCalendarView,\n  ) => {\n    if (selectedProp === undefined) setSelectedState(event.id);\n    onEventClick?.(event, { view: from, element });\n  };\n\n  const timeLabel = (item: Item, day?: Date) => {\n    if (item.lane) {\n      if (!day || item.first === item.last) return labels.allDay;\n      const first = epochDay(fromKey(item.first));\n      return labels.dayOf(epochDay(day) - first + 1, epochDay(fromKey(item.last)) - first + 1);\n    }\n    return item.first === item.last\n      ? fmt.timeRange(item.start, item.end)\n      : fmt.dateTimeRange(item.start, item.end);\n  };\n\n  const eventLabel = (item: Item) => {\n    const when = item.lane\n      ? `${labels.allDay}, ${fmt.dayRange(fromKey(item.first), fromKey(item.last))}`\n      : item.first === item.last\n        ? `${fmt.longDay(item.start)}, ${fmt.timeRange(item.start, item.end)}`\n        : fmt.dateTimeRange(item.start, item.end);\n    return [item.event.title, when, item.event.location].filter(Boolean).join(\", \");\n  };\n\n  const countOn = (day: Date) => {\n    const key = dayKey(day);\n    return items.filter((item) => item.first <= key && item.last >= key).length;\n  };\n\n  const ctx: Ctx = {\n    locale,\n    labels,\n    fmt,\n    today,\n    now,\n    focusDay,\n    selectedId,\n    renderEvent,\n    slot: onSlotClick,\n    activate,\n    eventLabel,\n    timeLabel,\n    countOn,\n    onDayKeyDown,\n    onEventKeyDown,\n    pickDay: (day) => changeDate(day),\n    openWeek: views.includes(\"week\")\n      ? (day) => {\n          // Land on the same day in the week grid.\n          focusRequest.current = dayKey(\n            visible(day) ? day : addDays(day, day.getDay() === 6 ? -1 : 1),\n          );\n          changeDate(day);\n          changeView(\"week\");\n        }\n      : undefined,\n  };\n\n  /* ---- Header ---- */\n  const viewSwitcher = views.length > 1 && (\n    <div\n      role=\"tablist\"\n      aria-label={labels.viewSwitcher}\n      data-slot=\"event-calendar-views\"\n      onKeyDown={(event) => {\n        const index = views.indexOf(view);\n        const next =\n          event.key === \"ArrowRight\"\n            ? views[(index + 1) % views.length]\n            : event.key === \"ArrowLeft\"\n              ? views[(index - 1 + views.length) % views.length]\n              : event.key === \"Home\"\n                ? views[0]\n                : event.key === \"End\"\n                  ? views[views.length - 1]\n                  : null;\n        if (!next) return;\n        event.preventDefault();\n        changeView(next);\n        event.currentTarget\n          .querySelector<HTMLElement>(`[data-view-tab=\"${next}\"]`)\n          ?.focus();\n      }}\n      className=\"inline-flex h-8 shrink-0 items-center gap-0.5 rounded-[10px] bg-muted/60 p-1 shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-border)_70%,transparent)] dark:bg-muted/40\"\n    >\n      {views.map((option) => {\n        const active = option === view;\n        const Icon = VIEW_ICONS[option];\n        return (\n          <button\n            key={option}\n            type=\"button\"\n            role=\"tab\"\n            id={`${uid}-tab-${option}`}\n            data-view-tab={option}\n            data-state={active ? \"active\" : \"inactive\"}\n            aria-selected={active}\n            aria-controls={`${uid}-panel`}\n            tabIndex={active ? 0 : -1}\n            onClick={() => changeView(option)}\n            className={cn(\n              \"inline-flex h-6 items-center justify-center gap-1.5 rounded-md px-1.5 text-xs font-medium whitespace-nowrap @min-[30rem]/event-calendar:px-2 transition-[color,background-color,box-shadow] duration-150 outline-none focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none @min-[36rem]/event-calendar:px-2.5\",\n              active\n                ? \"bg-card text-foreground shadow-[0_1px_2px_rgb(0_0_0/0.08),0_0_0_1px_rgb(0_0_0/0.04)] dark:bg-foreground/10 dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.07),0_1px_2px_rgb(0_0_0/0.5)]\"\n                : \"text-muted-foreground hover:text-foreground\",\n            )}\n          >\n            <Icon\n              aria-hidden=\"true\"\n              className=\"size-3.5 @min-[36rem]/event-calendar:hidden\"\n            />\n            <span className=\"sr-only @min-[36rem]/event-calendar:not-sr-only\">\n              {labels.views[option]}\n            </span>\n          </button>\n        );\n      })}\n    </div>\n  );\n\n  const navButton =\n    \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\";\n\n  const header = (\n    <div\n      data-slot=\"event-calendar-header\"\n      className=\"relative flex shrink-0 items-center gap-1.5 border-b border-border/60 px-3 py-2.5 @min-[30rem]/event-calendar:gap-2 @min-[36rem]/event-calendar:gap-3 @min-[36rem]/event-calendar:px-4\"\n    >\n      <h2\n        id={`${uid}-title`}\n        data-slot=\"event-calendar-title\"\n        className=\"min-w-0 flex-1 truncate text-sm font-semibold tracking-[-0.01em] tabular-nums @min-[30rem]/event-calendar:text-[15px]\"\n      >\n        {title.map((part, index) =>\n          part.quiet ? (\n            <span\n              key={index}\n              className=\"hidden font-medium text-muted-foreground @min-[30rem]/event-calendar:inline\"\n            >\n              {part.value}\n            </span>\n          ) : (\n            <React.Fragment key={index}>{part.value}</React.Fragment>\n          ),\n        )}\n      </h2>\n      <div\n        data-slot=\"event-calendar-nav\"\n        className=\"inline-flex h-8 shrink-0 items-center gap-0.5 rounded-[10px] border border-border/70 bg-card p-0.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)]\"\n      >\n        <button\n          type=\"button\"\n          aria-label={labels.previous(view)}\n          onClick={() => shift(-1)}\n          className={navButton}\n        >\n          <IconChevronLeft aria-hidden=\"true\" className=\"size-4 rtl:rotate-180\" />\n        </button>\n        <button\n          type=\"button\"\n          onClick={goToday}\n          data-current={\n            dayKey(today) >= dayKey(range.start) && dayKey(today) < dayKey(range.end)\n              ? \"\"\n              : undefined\n          }\n          className=\"inline-flex h-7 items-center rounded-md px-1.5 text-[13px] font-medium text-foreground @min-[30rem]/event-calendar:px-2 transition-colors duration-150 outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n        >\n          {labels.today}\n        </button>\n        <button\n          type=\"button\"\n          aria-label={labels.next(view)}\n          onClick={() => shift(1)}\n          className={navButton}\n        >\n          <IconChevronRight aria-hidden=\"true\" className=\"size-4 rtl:rotate-180\" />\n        </button>\n      </div>\n      {viewSwitcher}\n      {actions && <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>}\n      {loading && (\n        <span\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 -bottom-px h-0.5 overflow-hidden\"\n        >\n          <span className=\"block h-full w-1/4 rounded-full bg-primary/70 motion-safe:animate-[event-calendar-load_1.1s_cubic-bezier(0.4,0,0.2,1)_infinite]\" />\n        </span>\n      )}\n    </div>\n  );\n\n  const resolvedHeight = height ?? (view === \"month\" ? undefined : 640);\n  const allowDrag = selectable ?? !!onSlotClick;\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"event-calendar\"\n      data-view={view}\n      className={cn(\n        \"@container/event-calendar relative isolate flex min-w-0 flex-col overflow-hidden rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        className,\n      )}\n      style={{ height: resolvedHeight, ...style }}\n      {...props}\n    >\n      <style>{keyframes}</style>\n      {header}\n      <div\n        ref={bodyRef}\n        id={`${uid}-panel`}\n        role=\"tabpanel\"\n        aria-labelledby={views.length > 1 ? `${uid}-tab-${view} ${uid}-title` : `${uid}-title`}\n        aria-busy={loading || undefined}\n        data-slot=\"event-calendar-body\"\n        className=\"flex min-h-0 flex-1 flex-col\"\n      >\n        {view === \"week\" ? (\n          <WeekView\n            key={`week-${hourHeight}-${startHour}`}\n            ctx={ctx}\n            days={shownDays}\n            items={items}\n            startHour={startHour}\n            endHour={endHour}\n            hourHeight={hourHeight}\n            minDayWidth={minDayWidth}\n            workingHours={workingHours}\n            scrollToHour={scrollToHour ?? workingHours?.start ?? 8}\n            slotMinutes={slotMinutes}\n            snapMinutes={snapMinutes}\n            selectable={allowDrag}\n          />\n        ) : view === \"month\" ? (\n          <MonthView\n            ctx={ctx}\n            days={visibleDays}\n            visible={visible}\n            month={date}\n            items={items}\n            maxEvents={maxEventsPerDay}\n            fill={resolvedHeight !== undefined}\n          />\n        ) : (\n          <AgendaView ctx={ctx} days={shownDays} items={items} />\n        )}\n      </div>\n      <div aria-live=\"polite\" className=\"sr-only\">\n        {loading ? labels.loading : announcement}\n      </div>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Week                                                                      */\n/* ------------------------------------------------------------------------ */\n\ninterface Draft {\n  col: number;\n  anchor: number;\n  current: number;\n  y: number;\n  moved: boolean;\n  mouse: boolean;\n}\n\nfunction WeekView({\n  ctx,\n  days,\n  items,\n  startHour,\n  endHour,\n  hourHeight,\n  minDayWidth,\n  workingHours,\n  scrollToHour,\n  slotMinutes,\n  snapMinutes,\n  selectable,\n}: {\n  ctx: Ctx;\n  days: Date[];\n  items: Item[];\n  startHour: number;\n  endHour: number;\n  hourHeight: number;\n  minDayWidth: number;\n  workingHours: EventCalendarProps[\"workingHours\"];\n  scrollToHour: number;\n  slotMinutes: number;\n  snapMinutes: number;\n  selectable: boolean;\n}) {\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const [scrolled, setScrolled] = React.useState(false);\n  const [expanded, setExpanded] = React.useState(false);\n  const [draft, setDraft] = React.useState<Draft | null>(null);\n  const [hover, setHover] = React.useState<{ col: number; min: number } | null>(null);\n\n  const n = days.length;\n  const lo = startHour * 60;\n  const hi = endHour * 60;\n  const pxPerMin = hourHeight / 60;\n  const bodyHeight = (endHour - startHour) * hourHeight;\n  const columns = `${GUTTER}px repeat(${n}, minmax(${minDayWidth}px, 1fr))`;\n\n  /* All-day lane */\n  const spans = React.useMemo(() => packLanes(items, days, false), [items, days]);\n  const laneCount = spans.reduce((max, span) => Math.max(max, span.lane + 1), 0);\n  const MAX_LANES = 3;\n  const overflow = laneCount > MAX_LANES;\n  const shownLanes = overflow && !expanded ? MAX_LANES - 1 : laneCount;\n  const hiddenPerCol = days.map(\n    (_, col) =>\n      spans.filter(\n        (span) =>\n          span.lane >= shownLanes && span.startCol <= col && span.endCol >= col,\n      ).length,\n  );\n  const laneHeight =\n    Math.max(1, shownLanes + (overflow && !expanded ? 1 : 0)) * LANE + 6;\n\n  /* Time grid */\n  const minMinutes = 22 / pxPerMin;\n  const segments = React.useMemo(\n    () => days.map((day) => layoutDay(items, day, lo, hi, minMinutes)),\n    [items, days, lo, hi, minMinutes],\n  );\n\n  React.useLayoutEffect(() => {\n    const el = scrollRef.current;\n    if (!el) return;\n    el.scrollTop = Math.max(0, (scrollToHour - startHour) * hourHeight - 12);\n    const todayIndex = days.findIndex((day) => sameDay(day, ctx.today));\n    if (todayIndex > 0 && el.scrollWidth > el.clientWidth) {\n      const colWidth = (el.scrollWidth - GUTTER) / n;\n      const x = todayIndex * colWidth;\n      if (GUTTER + x + colWidth > el.clientWidth) el.scrollLeft = x;\n    }\n    // Scroll once on mount; later navigation keeps the reader's position.\n  }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n  React.useEffect(() => {\n    if (!draft) return;\n    const cancel = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") setDraft(null);\n    };\n    window.addEventListener(\"keydown\", cancel);\n    return () => window.removeEventListener(\"keydown\", cancel);\n  }, [draft]);\n\n  const minuteAt = (event: React.PointerEvent<HTMLElement>) => {\n    const rect = event.currentTarget.getBoundingClientRect();\n    return lo + clamp((event.clientY - rect.top) / pxPerMin, 0, hi - lo - 0.01);\n  };\n  const snap = (minute: number, size: number) => Math.floor(minute / size) * size;\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>, col: number) => {\n    if (!ctx.slot || event.button !== 0) return;\n    if ((event.target as HTMLElement).closest(\"[data-event]\")) return;\n    const minute = minuteAt(event);\n    const mouse = event.pointerType === \"mouse\";\n    if (mouse) {\n      event.preventDefault();\n      event.currentTarget.setPointerCapture(event.pointerId);\n    }\n    setHover(null);\n    setDraft({ col, anchor: minute, current: minute, y: event.clientY, moved: false, mouse });\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>, col: number) => {\n    if (!ctx.slot) return;\n    if (draft) {\n      if (!draft.mouse || draft.col !== col) return;\n      const minute = minuteAt(event);\n      const moved = draft.moved || Math.abs(event.clientY - draft.y) > 4;\n      if (moved !== draft.moved || snap(minute, snapMinutes) !== snap(draft.current, snapMinutes))\n        setDraft({ ...draft, current: minute, moved });\n      return;\n    }\n    if (event.pointerType !== \"mouse\") return;\n    if ((event.target as HTMLElement).closest(\"[data-event]\")) {\n      if (hover) setHover(null);\n      return;\n    }\n    const min = snap(minuteAt(event), slotMinutes);\n    if (!hover || hover.col !== col || hover.min !== min) setHover({ col, min });\n  };\n  const onPointerUp = (_event: React.PointerEvent<HTMLDivElement>, col: number) => {\n    if (!draft || draft.col !== col || !ctx.slot) return;\n    const day = days[col];\n    if (draft.moved && selectable) {\n      const a = snap(Math.min(draft.anchor, draft.current), snapMinutes);\n      const b = Math.min(hi, snap(Math.max(draft.anchor, draft.current), snapMinutes) + snapMinutes);\n      ctx.slot(atMinute(day, a), atMinute(day, b), { allDay: false, source: \"drag\" });\n    } else if (!draft.moved) {\n      const a = snap(draft.anchor, slotMinutes);\n      ctx.slot(atMinute(day, a), atMinute(day, Math.min(hi, a + slotMinutes)), {\n        allDay: false,\n        source: \"click\",\n      });\n    }\n    setDraft(null);\n  };\n\n  const ghost = (col: number) => {\n    if (draft && draft.col === col && (draft.moved ? selectable : draft.mouse)) {\n      const a = draft.moved\n        ? snap(Math.min(draft.anchor, draft.current), snapMinutes)\n        : snap(draft.anchor, slotMinutes);\n      const b = draft.moved\n        ? Math.min(hi, snap(Math.max(draft.anchor, draft.current), snapMinutes) + snapMinutes)\n        : Math.min(hi, a + slotMinutes);\n      return { a, b, solid: true };\n    }\n    if (!draft && hover && hover.col === col)\n      return { a: hover.min, b: Math.min(hi, hover.min + slotMinutes), solid: false };\n    return null;\n  };\n\n  const nowMin = minuteOfDay(ctx.now);\n  const nowTop = (nowMin - lo) * pxPerMin;\n  const todayCol = days.findIndex((day) => sameDay(day, ctx.today));\n  const showNow = todayCol >= 0 && nowMin >= lo && nowMin <= hi;\n  const lineColor = \"color-mix(in oklab, var(--color-foreground) 7%, transparent)\";\n  const halfColor = \"color-mix(in oklab, var(--color-foreground) 3.5%, transparent)\";\n  const offHours = \"color-mix(in oklab, var(--color-muted) 60%, transparent)\";\n\n  const hours: number[] = [];\n  for (let h = startHour + 1; h < endHour; h++) hours.push(h);\n\n  return (\n    <div\n      ref={scrollRef}\n      data-slot=\"event-calendar-week\"\n      onScroll={(event) => {\n        const next = event.currentTarget.scrollTop > 0;\n        if (next !== scrolled) setScrolled(next);\n      }}\n      className=\"relative min-h-0 flex-1 overflow-auto overscroll-contain [scrollbar-width:thin]\"\n    >\n      {/* Sticky header: days and the all-day lane */}\n      <div\n        data-slot=\"event-calendar-week-header\"\n        data-scrolled={scrolled ? \"\" : undefined}\n        className=\"sticky top-0 z-30 border-b border-border/60 bg-card transition-shadow duration-200 data-[scrolled]:shadow-[0_8px_16px_-12px_rgb(0_0_0/0.18)] motion-reduce:transition-none dark:data-[scrolled]:shadow-[0_8px_16px_-10px_rgb(0_0_0/0.7)]\"\n        style={{ minWidth: GUTTER + n * minDayWidth }}\n      >\n        <div className=\"grid\" style={{ gridTemplateColumns: columns }}>\n          <div className=\"sticky start-0 z-10 bg-card\" />\n          {days.map((day) => {\n            const isToday = sameDay(day, ctx.today);\n            const focused = sameDay(day, ctx.focusDay);\n            const count = ctx.countOn(day);\n            return (\n              <div\n                key={dayKey(day)}\n                className=\"min-w-0 border-s border-border/60 p-1\"\n              >\n                <button\n                  type=\"button\"\n                  data-slot=\"event-calendar-day\"\n                  data-day-target={dayKey(day)}\n                  data-today={isToday ? \"\" : undefined}\n                  data-focused={focused ? \"\" : undefined}\n                  tabIndex={focused ? 0 : -1}\n                  aria-current={isToday ? \"date\" : undefined}\n                  aria-label={[\n                    ctx.fmt.longDay(day),\n                    isToday ? ctx.labels.todayMarker : null,\n                    ctx.labels.events(count),\n                  ]\n                    .filter(Boolean)\n                    .join(\", \")}\n                  onKeyDown={(event) => ctx.onDayKeyDown(event, day)}\n                  onClick={(event) => {\n                    ctx.pickDay(day);\n                    ctx.slot?.(day, addDays(day, 1), {\n                      allDay: true,\n                      source: event.detail === 0 ? \"keyboard\" : \"click\",\n                    });\n                  }}\n                  className=\"group/day flex h-11 w-full min-w-0 flex-col items-center justify-center gap-0.5 rounded-lg @min-[36rem]/event-calendar:h-9 @min-[36rem]/event-calendar:flex-row @min-[36rem]/event-calendar:gap-1.5 outline-none transition-colors duration-150 hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n                >\n                  <span\n                    className={cn(\n                      \"truncate text-xs\",\n                      isToday ? \"font-medium text-primary\" : \"text-muted-foreground\",\n                    )}\n                  >\n                    {dtf(ctx.locale, { weekday: \"short\" }).format(day)}\n                  </span>\n                  <span\n                    className={cn(\n                      \"flex h-6 min-w-6 items-center justify-center rounded-full px-1 text-[13px] font-semibold tabular-nums\",\n                      isToday\n                        ? \"bg-primary text-primary-foreground shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_4px_12px_-4px_color-mix(in_oklab,var(--color-primary)_70%,transparent)]\"\n                        : \"text-foreground\",\n                    )}\n                  >\n                    {day.getDate()}\n                  </span>\n                </button>\n              </div>\n            );\n          })}\n        </div>\n\n        <div\n          data-slot=\"event-calendar-all-day\"\n          className=\"grid border-t border-border/60\"\n          style={{ gridTemplateColumns: columns }}\n        >\n          <div className=\"sticky start-0 z-10 flex flex-col items-end gap-0.5 bg-card pe-2 pt-1\">\n            <span className=\"text-[11px] leading-5 whitespace-nowrap text-muted-foreground\">\n              {ctx.labels.allDay}\n            </span>\n            {overflow && (\n              <button\n                type=\"button\"\n                aria-label={\n                  expanded\n                    ? ctx.labels.showFewer\n                    : ctx.labels.showMore(\n                        spans.filter((span) => span.lane >= shownLanes).length,\n                        ctx.labels.allDay,\n                      )\n                }\n                aria-expanded={expanded}\n                onClick={() => setExpanded((value) => !value)}\n                className=\"-me-1 inline-flex size-5 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n              >\n                <IconChevronDown\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"size-3.5 transition-transform duration-150 motion-reduce:transition-none\",\n                    expanded && \"rotate-180\",\n                  )}\n                />\n              </button>\n            )}\n          </div>\n          <div\n            className=\"relative grid\"\n            style={{\n              gridColumn: `2 / span ${n}`,\n              gridTemplateColumns: `repeat(${n}, minmax(0, 1fr))`,\n              height: laneHeight,\n            }}\n          >\n            {days.map((day, col) => (\n              <div\n                key={dayKey(day)}\n                className={cn(\n                  \"border-s border-border/60\",\n                  ctx.slot && \"transition-colors duration-150 hover:bg-muted/40\",\n                )}\n                onClick={(event) => {\n                  if ((event.target as HTMLElement).closest(\"button\")) return;\n                  ctx.slot?.(day, addDays(day, 1), { allDay: true, source: \"click\" });\n                }}\n              >\n                {spans\n                  .filter((span) => span.startCol === col && span.lane < shownLanes)\n                  .sort((a, b) => a.lane - b.lane)\n                  .map((span) => (\n                    <EventChip\n                      key={span.item.event.id}\n                      ctx={ctx}\n                      item={span.item}\n                      view=\"week\"\n                      compact\n                      tabbable={sameDay(days[span.startCol], ctx.focusDay)}\n                      className={cn(\n                        \"absolute flex h-[22px] items-center rounded-md ps-2.5 pe-1.5\",\n                        span.continuesBefore && \"rounded-s-sm ps-2\",\n                        span.continuesAfter && \"rounded-e-sm\",\n                      )}\n                      style={{\n                        top: 3 + span.lane * LANE,\n                        left: `calc(${(span.startCol / n) * 100}% + 3px)`,\n                        width: `calc(${((span.endCol - span.startCol + 1) / n) * 100}% - 6px)`,\n                      }}\n                    >\n                      {!span.continuesBefore && <span aria-hidden=\"true\" className={accent} />}\n                      <span\n                        className={cn(\n                          \"truncate text-[12px] leading-5 font-medium\",\n                          titleInk,\n                        )}\n                      >\n                        {span.continuesBefore && (\n                          <IconChevronLeft\n                            aria-hidden=\"true\"\n                            className=\"-ms-0.5 me-0.5 inline size-3 align-[-2px] rtl:rotate-180\"\n                          />\n                        )}\n                        {span.item.event.title}\n                      </span>\n                    </EventChip>\n                  ))}\n                {hiddenPerCol[col] > 0 && (\n                  <button\n                    type=\"button\"\n                    data-event-nav=\"\"\n                    tabIndex={sameDay(day, ctx.focusDay) ? 0 : -1}\n                    aria-label={ctx.labels.showMore(hiddenPerCol[col], ctx.fmt.longDay(day))}\n                    onKeyDown={ctx.onEventKeyDown}\n                    onClick={() => setExpanded(true)}\n                    className=\"absolute h-5 rounded-md px-1.5 text-start text-[11px] font-medium text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\"\n                    style={{\n                      top: 3 + shownLanes * LANE,\n                      left: `calc(${(col / n) * 100}% + 3px)`,\n                    }}\n                  >\n                    {ctx.labels.more(hiddenPerCol[col])}\n                  </button>\n                )}\n              </div>\n            ))}\n          </div>\n        </div>\n      </div>\n\n      {/* Time grid */}\n      <div\n        className=\"relative grid\"\n        style={{ gridTemplateColumns: columns, minWidth: GUTTER + n * minDayWidth }}\n      >\n        <div\n          aria-hidden=\"true\"\n          className=\"sticky start-0 z-20 bg-card\"\n          style={{ height: bodyHeight }}\n        >\n          {hours.map((h) => {\n            const top = (h - startHour) * hourHeight;\n            const nearNow = showNow && Math.abs(top - nowTop) < 16;\n            return (\n              <React.Fragment key={h}>\n                <span\n                  className={cn(\n                    \"absolute end-2 -translate-y-1/2 text-[11px] leading-none whitespace-nowrap text-muted-foreground tabular-nums transition-opacity\",\n                    nearNow && \"opacity-0\",\n                  )}\n                  style={{ top }}\n                >\n                  {ctx.fmt.hour(h)}\n                </span>\n                <span\n                  className=\"absolute end-0 h-px w-1.5\"\n                  style={{ top, background: lineColor }}\n                />\n              </React.Fragment>\n            );\n          })}\n          {showNow && (\n            <span\n              data-slot=\"event-calendar-now-label\"\n              className=\"absolute end-1.5 z-10 -translate-y-1/2 rounded-[5px] bg-primary px-1 py-px text-[11px] leading-4 font-semibold whitespace-nowrap text-primary-foreground tabular-nums shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_2px_8px_-2px_color-mix(in_oklab,var(--color-primary)_60%,transparent)]\"\n              style={{ top: nowTop }}\n            >\n              {ctx.fmt.clock(ctx.now)}\n            </span>\n          )}\n        </div>\n        {days.map((day, col) => {\n          const isToday = col === todayCol;\n          const workDay =\n            !!workingHours &&\n            (workingHours.days\n              ? workingHours.days.includes(day.getDay() as WeekdayIndex)\n              : !isWeekend(day));\n          const workStart = workingHours ? clamp(workingHours.start * 60, lo, hi) : lo;\n          const workEnd = workingHours ? clamp(workingHours.end * 60, lo, hi) : hi;\n          const shade = ghost(col);\n          const focused = sameDay(day, ctx.focusDay);\n          return (\n            <div\n              key={dayKey(day)}\n              role=\"group\"\n              aria-label={ctx.fmt.longDay(day)}\n              data-slot=\"event-calendar-column\"\n              data-today={isToday ? \"\" : undefined}\n              onPointerDown={(event) => onPointerDown(event, col)}\n              onPointerMove={(event) => onPointerMove(event, col)}\n              onPointerUp={(event) => onPointerUp(event, col)}\n              onPointerCancel={() => setDraft(null)}\n              onPointerLeave={() => setHover(null)}\n              className={cn(\n                \"relative min-w-0 border-s border-border/60 touch-pan-y\",\n                isToday && \"bg-primary/[0.025] dark:bg-primary/[0.04]\",\n              )}\n              style={{\n                height: bodyHeight,\n                backgroundImage: `linear-gradient(to bottom, ${lineColor} 1px, transparent 1px), linear-gradient(to bottom, transparent ${hourHeight / 2}px, ${halfColor} ${hourHeight / 2}px, ${halfColor} ${hourHeight / 2 + 1}px, transparent ${hourHeight / 2 + 1}px)`,\n                backgroundSize: `100% ${hourHeight}px`,\n              }}\n            >\n              {workingHours && (\n                <>\n                  {(workDay ? [[lo, workStart], [workEnd, hi]] : [[lo, hi]]).map(\n                    ([a, b]) =>\n                      b > a && (\n                        <span\n                          key={a}\n                          aria-hidden=\"true\"\n                          className=\"pointer-events-none absolute inset-x-0\"\n                          style={{\n                            top: (a - lo) * pxPerMin,\n                            height: (b - a) * pxPerMin,\n                            background: offHours,\n                          }}\n                        />\n                      ),\n                  )}\n                </>\n              )}\n              {showNow && !isToday && (\n                // Other days get a faint guide that passes under their events.\n                <span\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute inset-x-0 h-px -translate-y-1/2 bg-primary/25\"\n                  style={{ top: nowTop }}\n                />\n              )}\n              {shade && (\n                <span\n                  aria-hidden=\"true\"\n                  data-slot=\"event-calendar-selection\"\n                  className={cn(\n                    \"pointer-events-none absolute inset-x-[3px] z-10 flex items-start rounded-md px-2 py-1 text-[11px] leading-4 font-medium tabular-nums\",\n                    shade.solid\n                      ? \"bg-primary/12 text-primary ring-1 ring-primary/40 ring-inset shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_6px_16px_-10px_color-mix(in_oklab,var(--color-primary)_70%,transparent)]\"\n                      : \"bg-foreground/[0.04] text-muted-foreground\",\n                  )}\n                  style={{\n                    top: (shade.a - lo) * pxPerMin + 1,\n                    height: Math.max(18, (shade.b - shade.a) * pxPerMin - 2),\n                  }}\n                >\n                  <span className=\"truncate\">\n                    {shade.solid\n                      ? ctx.fmt.timeRange(atMinute(day, shade.a), atMinute(day, shade.b))\n                      : ctx.fmt.shortTime(atMinute(day, shade.a))}\n                  </span>\n                </span>\n              )}\n              {segments[col].map((segment) => {\n                const top = (segment.startMin - lo) * pxPerMin;\n                const blockHeight = Math.max(22, (segment.endMin - segment.startMin) * pxPerMin);\n                const compact = blockHeight < 38;\n                // Room for a two-line title, the time, and the location.\n                const tall = blockHeight >= 76;\n                const segStart = atMinute(day, segment.startMin);\n                const segEnd = atMinute(day, segment.endMin);\n                const range = ctx.fmt.timeRange(segment.item.start, segment.item.end);\n                const gap = segment.col + segment.span < segment.cols ? 2 : 0;\n                return (\n                  <EventChip\n                    key={segment.item.event.id}\n                    ctx={ctx}\n                    item={segment.item}\n                    view=\"week\"\n                    compact={compact}\n                    start={segStart}\n                    end={segEnd}\n                    tabbable={focused}\n                    className={cn(\n                      \"absolute flex rounded-md ps-2 pe-1 @min-[5rem]/chip:ps-2.5 @min-[5rem]/chip:pe-1.5\",\n                      compact ? \"items-center py-0\" : \"flex-col py-1\",\n                    )}\n                    style={{\n                      top: top + 1,\n                      height: blockHeight - 2,\n                      // Leave a strip on the right so empty time stays clickable.\n                      left: `calc(2px + (100% - 2px - min(8px, 10%)) * ${segment.col / segment.cols})`,\n                      width: `calc((100% - 2px - min(8px, 10%)) * ${segment.span / segment.cols} - ${gap}px)`,\n                    }}\n                  >\n                    <span aria-hidden=\"true\" className={accent} />\n                    {compact ? (\n                      <span className=\"flex min-w-0 flex-1 items-baseline gap-1.5 text-[12px] leading-4\">\n                        <span\n                          className={cn(\n                            \"min-w-0 truncate font-medium opacity-0 @min-[1.5rem]/chip:opacity-100\",\n                            titleInk,\n                          )}\n                        >\n                          {segment.item.event.title}\n                        </span>\n                        <span className=\"hidden shrink-0 text-[11px] text-foreground/65 tabular-nums @min-[7.5rem]/chip:inline\">\n                          {ctx.fmt.shortTime(segment.item.start)}\n                        </span>\n                      </span>\n                    ) : (\n                      <>\n                        <span\n                          className={cn(\n                            // Narrow chips hyphenate where they can and fade a long word at the edge instead of splitting it.\n                            \"text-[11px] leading-4 font-medium opacity-0 [hyphens:auto] [mask-image:linear-gradient(to_left,transparent,#000_6px)] @min-[1.5rem]/chip:opacity-100 @min-[4rem]/chip:text-[12px] @min-[4rem]/chip:[mask-image:none]\",\n                            titleInk,\n                            // Narrow chips spend every line on the title; wider ones make room for the time.\n                            \"line-clamp-(--title-lines) @min-[4rem]/chip:line-clamp-(--title-lines-wide)\",\n                          )}\n                          style={\n                            {\n                              \"--title-lines\": Math.max(1, Math.floor((blockHeight - 12) / 16)),\n                              \"--title-lines-wide\": clamp(\n                                Math.floor(\n                                  (blockHeight - 28 - (tall && segment.item.event.location ? 16 : 0)) / 16,\n                                ),\n                                1,\n                                3,\n                              ),\n                            } as React.CSSProperties\n                          }\n                        >\n                          {segment.item.event.title}\n                        </span>\n                        <span className=\"hidden truncate text-[11px] leading-4 text-foreground/65 tabular-nums @min-[4rem]/chip:block\">\n                          {range}\n                        </span>\n                        {tall && segment.item.event.location && (\n                          <span className=\"mt-auto hidden min-w-0 items-center gap-1 pb-px text-[11px] leading-4 text-foreground/60 @min-[5rem]/chip:flex\">\n                            <IconMapPin aria-hidden=\"true\" className=\"size-3 shrink-0\" />\n                            <span className=\"truncate\">{segment.item.event.location}</span>\n                          </span>\n                        )}\n                      </>\n                    )}\n                  </EventChip>\n                );\n              })}\n              {showNow && isToday && (\n                <span\n                  aria-hidden=\"true\"\n                  data-slot=\"event-calendar-now\"\n                  className=\"pointer-events-none absolute inset-x-0 z-20\"\n                  style={{ top: nowTop }}\n                >\n                  <span className=\"absolute inset-x-0 h-0.5 -translate-y-1/2 bg-primary dark:shadow-[0_0_8px_color-mix(in_oklab,var(--color-primary)_55%,transparent)]\" />\n                  <span className=\"absolute -start-[5px] size-2.5 -translate-y-1/2 rounded-full bg-primary ring-2 ring-card\" />\n                </span>\n              )}\n            </div>\n          );\n        })}\n        {showNow && <span className=\"sr-only\">{`${ctx.labels.currentTime}, ${ctx.fmt.time(ctx.now)}`}</span>}\n      </div>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Month                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction MonthView({\n  ctx,\n  days,\n  visible,\n  month,\n  items,\n  maxEvents,\n  fill,\n}: {\n  ctx: Ctx;\n  days: Date[];\n  visible: (day: Date) => boolean;\n  month: Date;\n  items: Item[];\n  maxEvents: number;\n  fill: boolean;\n}) {\n  const weeks = Array.from({ length: 6 }, (_, week) =>\n    days.slice(week * 7, week * 7 + 7).filter(visible),\n  );\n  const n = weeks[0].length;\n  const columns = `repeat(${n}, minmax(0, 1fr))`;\n  const rowMin = MONTH_TOP + maxEvents * MONTH_LANE + 24;\n  const weekdayShort = dtf(ctx.locale, { weekday: \"short\" });\n  const weekdayLong = dtf(ctx.locale, { weekday: \"long\" });\n  const monthDay = dtf(ctx.locale, { month: \"short\", day: \"numeric\" });\n  const caption = dtf(ctx.locale, { month: \"long\", year: \"numeric\" }).format(month);\n\n  return (\n    <div\n      role=\"grid\"\n      aria-label={caption}\n      data-slot=\"event-calendar-month\"\n      className={cn(\"flex min-h-0 flex-col\", fill && \"flex-1 overflow-y-auto\")}\n    >\n      <div\n        role=\"row\"\n        className=\"grid shrink-0 border-b border-border/60\"\n        style={{ gridTemplateColumns: columns }}\n      >\n        {weeks[0].map((day) => (\n          <div\n            key={day.getDay()}\n            role=\"columnheader\"\n            aria-label={weekdayLong.format(day)}\n            className=\"truncate px-3 py-2 text-xs text-muted-foreground\"\n          >\n            <abbr title={weekdayLong.format(day)} className=\"no-underline\">\n              {weekdayShort.format(day)}\n            </abbr>\n          </div>\n        ))}\n      </div>\n      <div\n        className={cn(\"grid\", fill && \"min-h-0 flex-1\")}\n        style={{ gridTemplateRows: `repeat(6, minmax(${rowMin}px, 1fr))` }}\n      >\n        {weeks.map((week) => (\n          <MonthWeek\n            key={dayKey(week[0])}\n            ctx={ctx}\n            week={week}\n            month={month}\n            items={items}\n            maxEvents={maxEvents}\n            columns={columns}\n            monthDay={monthDay}\n          />\n        ))}\n      </div>\n    </div>\n  );\n}\n\nfunction MonthWeek({\n  ctx,\n  week,\n  month,\n  items,\n  maxEvents,\n  columns,\n  monthDay,\n}: {\n  ctx: Ctx;\n  week: Date[];\n  month: Date;\n  items: Item[];\n  maxEvents: number;\n  columns: string;\n  monthDay: Intl.DateTimeFormat;\n}) {\n  const n = week.length;\n  const spans = React.useMemo(() => packLanes(items, week, true), [items, week]);\n  return (\n    <div\n      role=\"row\"\n      className=\"relative grid border-b border-border/60 last:border-b-0\"\n      style={{ gridTemplateColumns: columns }}\n    >\n      {week.map((day, col) => {\n        const outside = day.getMonth() !== month.getMonth();\n        const isToday = sameDay(day, ctx.today);\n        const focused = sameDay(day, ctx.focusDay);\n        const covering = spans.filter((span) => span.startCol <= col && span.endCol >= col);\n        const hidden = covering.filter((span) => span.lane >= maxEvents).length;\n        const starting = spans\n          .filter((span) => span.startCol === col && span.lane < maxEvents)\n          .sort((a, b) => a.lane - b.lane);\n        const dayItems = [...covering]\n          .sort((a, b) => a.lane - b.lane)\n          .map((span) => span.item);\n        return (\n          <div\n            key={dayKey(day)}\n            role=\"gridcell\"\n            data-slot=\"event-calendar-cell\"\n            data-outside={outside ? \"\" : undefined}\n            data-today={isToday ? \"\" : undefined}\n            data-focused={focused ? \"\" : undefined}\n            onClick={(event) => {\n              if ((event.target as HTMLElement).closest(\"button\")) return;\n              ctx.slot?.(day, addDays(day, 1), { allDay: true, source: \"click\" });\n            }}\n            className={cn(\n              \"min-w-0 border-s border-border/60 px-1.5 pt-1.5 first:border-s-0\",\n              outside && \"bg-muted/30 dark:bg-muted/20\",\n              ctx.slot && \"transition-colors duration-150 hover:bg-muted/45\",\n            )}\n          >\n            <button\n              type=\"button\"\n              data-slot=\"event-calendar-day\"\n              data-day-target={dayKey(day)}\n              tabIndex={focused ? 0 : -1}\n              aria-current={isToday ? \"date\" : undefined}\n              aria-label={[\n                ctx.fmt.longDay(day),\n                isToday ? ctx.labels.todayMarker : null,\n                ctx.labels.events(dayItems.length),\n              ]\n                .filter(Boolean)\n                .join(\", \")}\n              onKeyDown={(event) => ctx.onDayKeyDown(event, day)}\n              onClick={() => (ctx.openWeek ? ctx.openWeek(day) : ctx.pickDay(day))}\n              className={cn(\n                \"inline-flex h-6 min-w-6 items-center justify-center rounded-full px-1.5 text-xs font-medium whitespace-nowrap tabular-nums outline-none transition-[color,background-color,box-shadow] duration-150 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\",\n                isToday\n                  ? \"bg-primary font-semibold text-primary-foreground shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_4px_12px_-4px_color-mix(in_oklab,var(--color-primary)_70%,transparent)] hover:bg-primary/90\"\n                  : outside\n                    ? \"text-muted-foreground hover:bg-muted hover:text-foreground\"\n                    : \"text-foreground hover:bg-muted\",\n              )}\n            >\n              {day.getDate() === 1 && !isToday ? monthDay.format(day) : day.getDate()}\n            </button>\n            {starting.map((span) => {\n              const item = span.item;\n              const timed = !item.lane;\n              return (\n                <EventChip\n                  key={item.event.id}\n                  ctx={ctx}\n                  item={item}\n                  view=\"month\"\n                  compact\n                  tabbable={focused}\n                  className={cn(\n                    \"absolute flex h-5 items-center gap-1.5 rounded-[5px] ps-2.5 pe-1.5 text-[12px] leading-[18px]\",\n                    span.continuesBefore && \"rounded-s-sm ps-2\",\n                    span.continuesAfter && \"rounded-e-sm\",\n                    timed &&\n                      \"[background-color:color-mix(in_oklab,var(--event-color)_8%,var(--color-card))] [border-color:color-mix(in_oklab,var(--event-color)_16%,transparent)]\",\n                  )}\n                  style={{\n                    top: MONTH_TOP + 4 + span.lane * MONTH_LANE,\n                    left: `calc(${(span.startCol / n) * 100}% + 4px)`,\n                    width: `calc(${((span.endCol - span.startCol + 1) / n) * 100}% - 8px)`,\n                  }}\n                >\n                  {!span.continuesBefore && <span aria-hidden=\"true\" className={accent} />}\n                  <span className={cn(\"min-w-0 flex-1 truncate font-medium\", titleInk)}>\n                    {item.event.title}\n                  </span>\n                  {timed && (\n                    <span className=\"hidden shrink-0 text-[11px] text-foreground/65 tabular-nums @min-[8.5rem]/chip:inline\">\n                      {ctx.fmt.shortTime(item.start)}\n                    </span>\n                  )}\n                </EventChip>\n              );\n            })}\n            {hidden > 0 && (\n              <MorePopover\n                ctx={ctx}\n                day={day}\n                items={dayItems}\n                count={hidden}\n                tabbable={focused}\n                style={{\n                  top: MONTH_TOP + 4 + maxEvents * MONTH_LANE,\n                  left: `calc(${(col / n) * 100}% + 4px)`,\n                }}\n              />\n            )}\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\nfunction MorePopover({\n  ctx,\n  day,\n  items,\n  count,\n  tabbable,\n  style,\n}: {\n  ctx: Ctx;\n  day: Date;\n  items: Item[];\n  count: number;\n  tabbable: boolean;\n  style: React.CSSProperties;\n}) {\n  const [open, setOpen] = React.useState(false);\n  const longDay = ctx.fmt.longDay(day);\n  const onListKeyDown = (event: React.KeyboardEvent<HTMLUListElement>) => {\n    if (![\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"].includes(event.key)) return;\n    const list = Array.from(\n      event.currentTarget.querySelectorAll<HTMLElement>(\"[data-event]\"),\n    );\n    const index = list.indexOf(document.activeElement as HTMLElement);\n    const next =\n      event.key === \"Home\"\n        ? 0\n        : event.key === \"End\"\n          ? list.length - 1\n          : clamp(index + (event.key === \"ArrowDown\" ? 1 : -1), 0, list.length - 1);\n    event.preventDefault();\n    list[next]?.focus();\n  };\n  return (\n    <PopoverPrimitive.Root open={open} onOpenChange={setOpen}>\n      <PopoverPrimitive.Trigger asChild>\n        <button\n          type=\"button\"\n          data-slot=\"event-calendar-more\"\n          data-event-nav=\"\"\n          data-state={open ? \"open\" : \"closed\"}\n          tabIndex={tabbable ? 0 : -1}\n          aria-label={ctx.labels.showMore(count, longDay)}\n          onKeyDown={ctx.onEventKeyDown}\n          className=\"absolute flex h-5 items-center rounded-[5px] px-1.5 text-[12px] leading-5 font-medium text-muted-foreground transition-colors duration-150 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 data-[state=open]:bg-muted data-[state=open]:text-foreground motion-reduce:transition-none\"\n          style={style}\n        >\n          {ctx.labels.more(count)}\n        </button>\n      </PopoverPrimitive.Trigger>\n      <PopoverPrimitive.Portal>\n        <PopoverPrimitive.Content\n          side=\"bottom\"\n          align=\"start\"\n          sideOffset={6}\n          collisionPadding={12}\n          aria-label={longDay}\n          data-slot=\"event-calendar-more-content\"\n          className=\"z-50 w-64 max-w-[calc(100vw-24px)] origin-(--radix-popover-content-transform-origin) rounded-xl border border-border/70 bg-popover/90 p-1.5 text-popover-foreground shadow-xl backdrop-blur-md outline-none motion-safe:animate-[event-calendar-pop_180ms_cubic-bezier(0.22,1,0.36,1)]\"\n        >\n          <div className=\"flex items-baseline justify-between gap-3 px-2 pt-1 pb-2\">\n            <span className=\"text-sm font-semibold tracking-tight\">\n              {dtf(ctx.locale, { weekday: \"long\" }).format(day)}\n            </span>\n            <span className=\"text-xs text-muted-foreground tabular-nums\">\n              {dtf(ctx.locale, { month: \"long\", day: \"numeric\" }).format(day)}\n            </span>\n          </div>\n          <ul className=\"flex max-h-72 flex-col gap-1 overflow-y-auto p-0.5\" onKeyDown={onListKeyDown}>\n            {items.map((item) => (\n              <li key={item.event.id}>\n                <EventChip\n                  ctx={{\n                    ...ctx,\n                    onEventKeyDown: () => {},\n                    activate: (event, element, view) => {\n                      ctx.activate(event, element, view);\n                      setOpen(false);\n                    },\n                  }}\n                  item={item}\n                  view=\"month\"\n                  tabbable\n                  className=\"relative flex w-full flex-col rounded-lg py-1.5 ps-3 pe-2 shadow-none\"\n                >\n                  <span aria-hidden=\"true\" className={cn(accent, \"inset-y-1.5 start-1\")} />\n                  <span className={cn(\"truncate text-[13px] leading-5 font-medium\", titleInk)}>\n                    {item.event.title}\n                  </span>\n                  <span className=\"truncate text-xs leading-4 text-foreground/65 tabular-nums\">\n                    {ctx.timeLabel(item, day)}\n                  </span>\n                </EventChip>\n              </li>\n            ))}\n          </ul>\n        </PopoverPrimitive.Content>\n      </PopoverPrimitive.Portal>\n    </PopoverPrimitive.Root>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Agenda                                                                    */\n/* ------------------------------------------------------------------------ */\n\nfunction AgendaView({\n  ctx,\n  days,\n  items,\n}: {\n  ctx: Ctx;\n  days: Date[];\n  items: Item[];\n}) {\n  const uid = React.useId();\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const groups = React.useMemo(\n    () =>\n      days\n        .map((day) => {\n          const key = dayKey(day);\n          const entries = items\n            .filter((item) =>\n              item.lane\n                ? item.first <= key && item.last >= key\n                : item.first === key,\n            )\n            .sort(\n              (a, b) =>\n                Number(b.lane) - Number(a.lane) ||\n                a.start.getTime() - b.start.getTime(),\n            );\n          return { day, entries };\n        })\n        .filter((group) => group.entries.length > 0),\n    [days, items],\n  );\n  const rowIds = groups.flatMap((group) =>\n    group.entries.map((item) => `${dayKey(group.day)}:${item.event.id}`),\n  );\n  const [active, setActive] = React.useState<string | null>(null);\n  const activeId = active && rowIds.includes(active) ? active : (rowIds[0] ?? null);\n  const relative = React.useMemo(() => {\n    try {\n      return new Intl.RelativeTimeFormat(ctx.locale, { numeric: \"auto\" });\n    } catch {\n      return null;\n    }\n  }, [ctx.locale]);\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const list = Array.from(\n      listRef.current?.querySelectorAll<HTMLElement>(\"[data-agenda-row]\") ?? [],\n    );\n    const index = list.indexOf(document.activeElement as HTMLElement);\n    if (index < 0) return;\n    const groupOf = (el: HTMLElement) => el.dataset.agendaRow?.split(\":\")[0];\n    let next = -1;\n    switch (event.key) {\n      case \"ArrowDown\":\n        next = Math.min(list.length - 1, index + 1);\n        break;\n      case \"ArrowUp\":\n        next = Math.max(0, index - 1);\n        break;\n      case \"Home\":\n        next = 0;\n        break;\n      case \"End\":\n        next = list.length - 1;\n        break;\n      case \"PageDown\": {\n        const current = groupOf(list[index]);\n        next = list.findIndex((el, i) => i > index && groupOf(el) !== current);\n        if (next < 0) next = list.length - 1;\n        break;\n      }\n      case \"PageUp\": {\n        const current = groupOf(list[index]);\n        const before = list.slice(0, index).filter((el) => groupOf(el) !== current);\n        const target = before.length ? groupOf(before[before.length - 1]) : current;\n        next = list.findIndex((el) => groupOf(el) === target);\n        break;\n      }\n      default:\n        return;\n    }\n    event.preventDefault();\n    list[next]?.focus();\n  };\n\n  if (!groups.length) {\n    return (\n      <div\n        data-slot=\"event-calendar-empty\"\n        className=\"flex flex-1 flex-col items-center justify-center gap-3 px-6 py-12 text-center\"\n      >\n        <span className=\"flex size-11 items-center justify-center rounded-xl bg-muted/40 text-muted-foreground ring-1 ring-border/60 ring-inset\">\n          <IconCalendarOff aria-hidden=\"true\" className=\"size-5\" />\n        </span>\n        <div className=\"space-y-1\">\n          <p className=\"text-sm font-semibold tracking-tight\">{ctx.labels.noEvents}</p>\n          <p className=\"max-w-xs text-[13px] leading-5 text-muted-foreground\">\n            {ctx.labels.noEventsDescription}\n          </p>\n        </div>\n      </div>\n    );\n  }\n\n  return (\n    <div\n      ref={listRef}\n      data-slot=\"event-calendar-agenda\"\n      onKeyDown={onKeyDown}\n      className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 py-1 [scrollbar-width:thin] @min-[36rem]/event-calendar:px-3\"\n    >\n      {groups.map(({ day, entries }) => {\n        const key = dayKey(day);\n        const isToday = sameDay(day, ctx.today);\n        const offset = epochDay(day) - epochDay(ctx.today);\n        const near =\n          relative && Math.abs(offset) <= 1\n            ? capitalize(relative.format(offset, \"day\"), ctx.locale)\n            : null;\n        const headingId = `${uid}-${key}`;\n        return (\n          <section\n            key={key}\n            aria-labelledby={headingId}\n            data-slot=\"event-calendar-agenda-day\"\n            data-today={isToday ? \"\" : undefined}\n            className=\"grid grid-cols-[3.25rem_minmax(0,1fr)] gap-x-2 border-t border-border/60 py-2.5 first:border-t-0 @min-[36rem]/event-calendar:grid-cols-[4.5rem_minmax(0,1fr)] @min-[36rem]/event-calendar:gap-x-3\"\n          >\n            <h3\n              id={headingId}\n              className=\"sticky top-2.5 flex flex-col items-center self-start pt-1.5\"\n            >\n              <span aria-hidden=\"true\" className={cn(\"text-xs\", isToday ? \"font-medium text-primary\" : \"text-muted-foreground\")}>\n                {dtf(ctx.locale, { weekday: \"short\" }).format(day)}\n              </span>\n              <span\n                aria-hidden=\"true\"\n                className={cn(\n                  \"mt-0.5 flex size-8 items-center justify-center rounded-full text-lg font-semibold tracking-[-0.02em] tabular-nums\",\n                  isToday &&\n                    \"bg-primary text-primary-foreground shadow-[0_1px_2px_rgb(0_0_0/0.12)] dark:shadow-[0_4px_12px_-4px_color-mix(in_oklab,var(--color-primary)_70%,transparent)]\",\n                )}\n              >\n                {day.getDate()}\n              </span>\n              {near && (\n                <span aria-hidden=\"true\" className={cn(\"mt-1 text-[11px] font-medium\", isToday ? \"text-primary\" : \"text-muted-foreground\")}>\n                  {near}\n                </span>\n              )}\n              <span className=\"sr-only\">\n                {[near, ctx.fmt.longDay(day), ctx.labels.events(entries.length)]\n                  .filter(Boolean)\n                  .join(\", \")}\n              </span>\n            </h3>\n            <ul className=\"flex min-w-0 flex-col gap-0.5 py-0.5\">\n              {entries.map((item) => {\n                const rowId = `${key}:${item.event.id}`;\n                const selected = ctx.selectedId === item.event.id;\n                const time = ctx.timeLabel(item, day);\n                return (\n                  <li key={item.event.id}>\n                    <button\n                      type=\"button\"\n                      data-slot=\"event-calendar-event\"\n                      data-event={item.event.id}\n                      data-agenda-row={rowId}\n                      data-selected={selected ? \"\" : undefined}\n                      tabIndex={rowId === activeId ? 0 : -1}\n                      aria-label={ctx.eventLabel(item)}\n                      onFocus={() => setActive(rowId)}\n                      onClick={(event) => ctx.activate(item.event, event.currentTarget, \"agenda\")}\n                      style={{ \"--event-color\": item.color } as React.CSSProperties}\n                      className={cn(\n                        \"group/event relative grid w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 rounded-lg py-2 ps-4 pe-2 text-start outline-none transition-[background-color,box-shadow] duration-150 hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none @min-[36rem]/event-calendar:grid-cols-[8.5rem_minmax(0,1fr)_auto]\",\n                        selected &&\n                          \"[background-color:color-mix(in_oklab,var(--event-color)_10%,transparent)] ring-2 ring-primary/30 hover:[background-color:color-mix(in_oklab,var(--event-color)_14%,transparent)]\",\n                      )}\n                    >\n                      <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-y-2 start-1.5 w-[3px] rounded-full bg-[var(--event-color)]\" />\n                      {ctx.renderEvent ? (\n                        <span className=\"col-span-full min-w-0\">\n                          {ctx.renderEvent(item.event, {\n                            view: \"agenda\",\n                            start: item.start,\n                            end: item.end,\n                            color: item.color,\n                            timeLabel: time,\n                            compact: false,\n                            allDay: item.lane,\n                            selected,\n                          })}\n                        </span>\n                      ) : (\n                        <>\n                          <span className=\"hidden text-xs text-muted-foreground tabular-nums @min-[36rem]/event-calendar:block\">\n                            {time}\n                          </span>\n                          <span className=\"min-w-0\">\n                            <span className=\"block truncate text-sm leading-5 font-medium text-foreground\">\n                              {item.event.title}\n                            </span>\n                            <span className=\"flex min-w-0 items-center gap-1.5 text-xs leading-5 text-muted-foreground\">\n                              <span className=\"shrink-0 tabular-nums @min-[36rem]/event-calendar:hidden\">\n                                {time}\n                              </span>\n                              {item.event.location && (\n                                <>\n                                  <span aria-hidden=\"true\" className=\"@min-[36rem]/event-calendar:hidden\">·</span>\n                                  <IconMapPin aria-hidden=\"true\" className=\"hidden size-3 shrink-0 @min-[36rem]/event-calendar:block\" />\n                                  <span className=\"truncate\">{item.event.location}</span>\n                                </>\n                              )}\n                            </span>\n                          </span>\n                          {item.event.attendees?.length ? (\n                            <Initials attendees={item.event.attendees} />\n                          ) : (\n                            <span />\n                          )}\n                        </>\n                      )}\n                    </button>\n                  </li>\n                );\n              })}\n            </ul>\n          </section>\n        );\n      })}\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/event-calendar. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
