{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "time-grid",
  "title": "Time Grid",
  "description": "The hour grid behind the day and week views: all-day row, time axis and current-time line, with drag, resize and create.",
  "dependencies": [
    "date-fns"
  ],
  "registryDependencies": [
    "@calendarcn/calendar-core",
    "@calendarcn/event-details"
  ],
  "files": [
    {
      "path": "src/components/time-grid.tsx",
      "content": "\"use client\";\n\nimport {\n  addDays,\n  differenceInCalendarDays,\n  eachDayOfInterval,\n  format,\n  isSameDay,\n} from \"date-fns\";\nimport type { Locale } from \"date-fns\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  formatHourLabel,\n  formatTimeOfDayLabel,\n  getPeriodStart,\n  getVisibleDayCount,\n  getWeekViewStepDays,\n  isMultiDayEvent,\n} from \"@/lib/event-utils\";\nimport {\n  getSecondaryTimeAxisInstant,\n  getTimeZoneOffsetDifference,\n  getViewerTimeZone,\n} from \"@/lib/time-zones\";\nimport { getTimeZoneLabel } from \"@/lib/timezone-label\";\nimport { expandRecurringEvents } from \"@/lib/recurrence\";\nimport { useHorizontalScroll } from \"@/hooks/use-horizontal-scroll\";\nimport { useEventKeyboard } from \"@/hooks/use-event-keyboard\";\nimport { useEventDrag } from \"@/hooks/use-event-drag\";\nimport { useEventResize } from \"@/hooks/use-event-resize\";\nimport { useAllDayResize } from \"@/hooks/use-all-day-resize\";\nimport { useToday } from \"@/hooks/use-now\";\nimport { useTimeZoneLabel } from \"@/hooks/use-timezone-label\";\nimport type {\n  CalendarEvent,\n  HourCycle,\n  HourSlot,\n  NewEventRange,\n  TimeGridProps,\n  TimeGridView,\n  WeekDay,\n} from \"./week-view-types\";\nimport {\n  useCalendar,\n  useCalendarConfig,\n  useCalendarViewSync,\n} from \"./calendar-provider\";\nimport { WeekViewAllDayRow } from \"./week-view-all-day-row\";\nimport { CalendarDayHeaders } from \"./calendar-day-headers\";\nimport { WeekViewGrid } from \"./week-view-grid\";\nimport { WeekViewTimeAxis } from \"./week-view-time-axis\";\nimport { WeekViewTimeIndicator } from \"./week-view-time-indicator\";\nimport {\n  CalendarPopoverBoundaryProvider,\n  isEventInsideCalendarPopover,\n} from \"./calendar-popover-context\";\nimport { CalendarLoadingBar } from \"./calendar-loading-bar\";\n\n/** Minimum height of each hour row in pixels */\nconst MIN_HOUR_HEIGHT = 48;\n\n/**\n * Width of one time axis column in pixels (4rem = 64px). A second time zone\n * adds a second column of the same width.\n */\nexport const TIME_AXIS_WIDTH = 64;\n\n/** Hour labels of a second time zone column before they're known (on the server and during hydration) */\nconst NO_LABELS: string[] = [];\n\n/** Buffer days per view mode (each side, for horizontal scroll) */\nconst BUFFER_DAYS_BY_VIEW: Record<TimeGridView, number> = {\n  day: 1,\n  week: 7,\n};\n\n/** Buffer extension step size per view mode */\nconst BUFFER_STEP_BY_VIEW: Record<TimeGridView, number> = {\n  day: 1,\n  week: 7,\n};\n\n/** Days the day view moves when a drag or resize is held at its side edge */\nconst DAY_VIEW_EDGE_NAV_DAYS = 7;\n\n/**\n * Generates an array of WeekDay objects starting from the given date.\n * Note: isToday is added separately from the shared `useToday` clock, so it\n * stays correct across midnight and is never computed on the server\n */\nfunction generateWeekDays(\n  startDate: Date,\n  count: number,\n  locale: Locale,\n): Omit<WeekDay, \"isToday\">[] {\n  const end = addDays(startDate, count - 1);\n\n  return eachDayOfInterval({ start: startDate, end }).map((date) => ({\n    date,\n    dayName: format(date, \"EEE\", { locale }),\n    dayNumber: date.getDate(),\n  }));\n}\n\n/**\n * Generates an extended array of days including buffer days on both sides\n * for smooth horizontal scroll transitions\n */\nfunction generateBufferedDays(\n  startDate: Date,\n  bufferDays: number,\n  visibleDays: number,\n  locale: Locale,\n): Omit<WeekDay, \"isToday\">[] {\n  const bufferStart = addDays(startDate, -bufferDays);\n  const bufferEnd = addDays(startDate, visibleDays + bufferDays - 1);\n\n  return eachDayOfInterval({ start: bufferStart, end: bufferEnd }).map(\n    (date) => ({\n      date,\n      dayName: format(date, \"EEE\", { locale }),\n      dayNumber: date.getDate(),\n    }),\n  );\n}\n\n/**\n * Generates an HourSlot for each visible hour, from `dayStartHour` up to\n * (not including) `dayEndHour`\n */\nfunction generateHours(\n  dayStartHour: number,\n  dayEndHour: number,\n  hourCycle: HourCycle,\n  locale: Locale,\n): HourSlot[] {\n  return Array.from({ length: dayEndHour - dayStartHour }, (_, i) => {\n    const hour = dayStartHour + i;\n    return { hour, label: formatHourLabel(hour, hourCycle, locale) };\n  });\n}\n\n/** Marks the day matching `today` (none while `today` is unknown). */\nfunction withIsToday(\n  days: Omit<WeekDay, \"isToday\">[],\n  today: Date | null,\n): WeekDay[] {\n  return days.map((day) => ({\n    ...day,\n    isToday: today !== null && isSameDay(day.date, today),\n  }));\n}\n\n/**\n * Hourly time grid behind DayView and WeekView: day headers, the all-day\n * row, the time axis and the timed-event columns, with horizontal scroll\n * navigation. `view` sets the column count (one day, or `numberOfDays`);\n * date, events and selection come from the surrounding CalendarProvider,\n * which adopts `view` and `numberOfDays` while it doesn't control them.\n *\n * Changing `view` re-lays out the same grid instead of remounting it, so\n * driving it from the provider (`<TimeGrid view={view} />`) keeps the\n * vertical scroll position across day/week switches.\n *\n * With the provider's `secondaryTimeZone`, the time axis gets a second\n * column on its left: that zone's hours on the same lines, its short label\n * above them. The now line keeps its one badge, in the viewer's column.\n *\n * Renders the same markup on the server and during hydration: everything that\n * depends on the viewer's clock (today, the current-time line, past events)\n * reads the shared `useNow` clock, which is unknown until hydration finishes.\n */\nexport function TimeGrid({\n  view,\n  numberOfDays: numberOfDaysProp,\n  showEventPopover = true,\n  onEventPopoverExpand,\n  scrollToHour,\n  className,\n}: TimeGridProps) {\n  const {\n    view: providerView,\n    currentDate,\n    events,\n    selectedEvent,\n    highlightedDate,\n    selectEvent,\n    clearSelection,\n    addEventFromRange,\n    updateEvent,\n    goToDate,\n    numberOfDays: providerNumberOfDays,\n    weekStartsOn,\n    loading,\n  } = useCalendar();\n  const {\n    snapMinutes,\n    dayStartHour,\n    dayEndHour,\n    hourCycle,\n    locale,\n    secondaryTimeZone,\n  } = useCalendarConfig();\n  const {\n    reportView,\n    reportVisibleDays,\n    closeEventPopover,\n    reportPasteTarget,\n  } = useCalendarViewSync();\n  const numberOfDays = numberOfDaysProp ?? providerNumberOfDays;\n  /** Day columns this grid pins the provider to (none in day view) */\n  const fixedNumberOfDays = view === \"week\" ? numberOfDaysProp : undefined;\n  /**\n   * Whether the provider navigates by this grid's type and day count. False\n   * for the commit before it adopts them (on mount, or right after a switch\n   * this grid doesn't follow).\n   */\n  const isProviderInSync =\n    providerView === view &&\n    (fixedNumberOfDays === undefined ||\n      providerNumberOfDays === fixedNumberOfDays);\n  // `null` on the server and during hydration\n  const today = useToday();\n  const selectedEventId = selectedEvent?.id;\n  const VISIBLE_DAYS = getVisibleDayCount(view, numberOfDays);\n  const visibleHourCount = dayEndHour - dayStartHour;\n  /** Width of the time axis: one column, or two with a second time zone */\n  const timeAxisWidth = secondaryTimeZone\n    ? TIME_AXIS_WIDTH * 2\n    : TIME_AXIS_WIDTH;\n  // A drag held at the grid's side edge moves by one prev/next step\n  const edgeNavigationDays =\n    view === \"day\" ? DAY_VIEW_EDGE_NAV_DAYS : getWeekViewStepDays(numberOfDays);\n  const BUFFER_DAYS = BUFFER_DAYS_BY_VIEW[view];\n  const BUFFER_STEP = BUFFER_STEP_BY_VIEW[view];\n  const scrollContainerRef = React.useRef<HTMLDivElement>(null);\n  const dayColumnsScrollRef = React.useRef<HTMLDivElement>(null);\n  const allDayScrollRef = React.useRef<HTMLDivElement>(null);\n  const allDayScrollContentRef = React.useRef<HTMLDivElement>(null);\n\n  // Visible days starting from currentDate\n  const baseDays = React.useMemo(\n    () => generateWeekDays(currentDate, VISIBLE_DAYS, locale),\n    [currentDate, VISIBLE_DAYS, locale],\n  );\n\n  const days = withIsToday(baseDays, today);\n\n  const hours = React.useMemo(\n    () => generateHours(dayStartHour, dayEndHour, hourCycle, locale),\n    [dayStartHour, dayEndHour, hourCycle, locale],\n  );\n\n  // The second time zone's column: its short label, and the time its clock\n  // shows at each hour row. Both depend on the viewer's zone, so like the\n  // viewer's own label they stay blank on the server and during hydration\n  // (`today` is null until then). The offset is read at noon on today, or\n  // on the first day shown when today isn't on screen.\n  const secondaryAxis = React.useMemo(() => {\n    if (!secondaryTimeZone || today === null) return null;\n    const primaryTimeZone = getViewerTimeZone();\n    const instant = getSecondaryTimeAxisInstant(\n      baseDays.map((day) => day.date),\n      today,\n      primaryTimeZone,\n    );\n    const offsetMinutes = getTimeZoneOffsetDifference(\n      instant,\n      primaryTimeZone,\n      secondaryTimeZone,\n    );\n    return {\n      label: getTimeZoneLabel(instant, secondaryTimeZone),\n      hourLabels: hours.map((slot) =>\n        formatTimeOfDayLabel(slot.hour * 60 + offsetMinutes, hourCycle, locale),\n      ),\n    };\n  }, [secondaryTimeZone, today, baseDays, hours, hourCycle, locale]);\n\n  // The stored events, for the drag and resize hooks to commit from\n  const allDayEvents = React.useMemo(\n    () => events.filter((e) => e.isAllDay || isMultiDayEvent(e)),\n    [events],\n  );\n\n  const timedEvents = React.useMemo(\n    () => events.filter((e) => !e.isAllDay && !isMultiDayEvent(e)),\n    [events],\n  );\n\n  // Compute day column width and dynamic hour height from container\n  const [dayColumnWidth, setDayColumnWidth] = React.useState(0);\n  const [hourHeight, setHourHeight] = React.useState(MIN_HOUR_HEIGHT);\n  const [contextMenuOpen, setContextMenuOpen] = React.useState(false);\n  const [isAllDayResizing, setIsAllDayResizing] = React.useState(false);\n  // Empty on the server and during hydration, the viewer's zone afterwards\n  const timeZoneLabel = useTimeZoneLabel();\n\n  React.useEffect(() => {\n    const updateDimensions = () => {\n      const container = scrollContainerRef.current;\n      if (!container) return;\n      const availableWidth = container.clientWidth - timeAxisWidth;\n      setDayColumnWidth(availableWidth / VISIBLE_DAYS);\n      setHourHeight(\n        Math.max(MIN_HOUR_HEIGHT, container.clientHeight / visibleHourCount),\n      );\n    };\n\n    updateDimensions();\n\n    const observer = new ResizeObserver(updateDimensions);\n    if (scrollContainerRef.current) {\n      observer.observe(scrollContainerRef.current);\n    }\n    return () => observer.disconnect();\n  }, [VISIBLE_DAYS, visibleHourCount, timeAxisWidth]);\n\n  /** Whether `scrollToHour` has been applied; it only applies once */\n  const hasScrolledToHourRef = React.useRef(false);\n\n  // Scroll to `scrollToHour` before the first paint. A grid mounted hidden\n  // (e.g. in an inactive tab) has no height yet, so wait until it has one.\n  React.useLayoutEffect(() => {\n    if (scrollToHour === undefined || hasScrolledToHourRef.current) return;\n    const container = scrollContainerRef.current;\n    if (!container) return;\n\n    const applyScroll = () => {\n      if (hasScrolledToHourRef.current || container.clientHeight === 0) return;\n      hasScrolledToHourRef.current = true;\n      // Same row height the grid settles on (see updateDimensions above)\n      const rowHeight = Math.max(\n        MIN_HOUR_HEIGHT,\n        container.clientHeight / visibleHourCount,\n      );\n      const hour = Math.min(Math.max(scrollToHour, dayStartHour), dayEndHour);\n      container.scrollTop = (hour - dayStartHour) * rowHeight;\n    };\n\n    applyScroll();\n    if (hasScrolledToHourRef.current) return;\n\n    const observer = new ResizeObserver(applyScroll);\n    observer.observe(container);\n    return () => observer.disconnect();\n  }, [scrollToHour, dayStartHour, dayEndHour, visibleHourCount]);\n\n  // Track whether navigation was initiated by scroll (to avoid double-animation)\n  const scrollNavigatedRef = React.useRef(false);\n  const prevDateRef = React.useRef(currentDate);\n  const wasProviderInSyncRef = React.useRef(isProviderInSync);\n\n  // Tell the provider which view is on screen. `reportView` changes with the\n  // provider's state, so this also re-checks after every switch. A layout\n  // effect: the provider adopts this grid before the first paint.\n  React.useLayoutEffect(() => {\n    reportView({ view, numberOfDays: fixedNumberOfDays });\n  }, [view, fixedNumberOfDays, reportView]);\n\n  const handleNavigate = React.useCallback(\n    (daysDelta: number) => {\n      scrollNavigatedRef.current = true;\n      goToDate(addDays(currentDate, daysDelta));\n    },\n    [currentDate, goToDate],\n  );\n\n  const handleDragNavigate = React.useCallback(\n    (daysDelta: number) => {\n      goToDate(addDays(currentDate, daysDelta));\n    },\n    [currentDate, goToDate],\n  );\n\n  const handleEventClick = React.useCallback(\n    (event: CalendarEvent) => selectEvent(event.id),\n    [selectEvent],\n  );\n\n  const visibleDayDates = React.useMemo(() => days.map((d) => d.date), [days]);\n\n  const { resizeState, handleResizePointerDown } = useEventResize({\n    hourHeight,\n    scrollContainerRef,\n    events: timedEvents,\n    days: visibleDayDates,\n    dayColumnWidth,\n    timeAxisWidth,\n    snapMinutes,\n    dayStartHour,\n    dayEndHour,\n    edgeNavigationDays,\n    onEventChange: updateEvent,\n    onEventClick: handleEventClick,\n    onResizeNavigate: handleDragNavigate,\n  });\n\n  const { dragState, handleEventPointerDown } = useEventDrag({\n    hourHeight,\n    scrollContainerRef,\n    events: timedEvents,\n    days: visibleDayDates,\n    dayColumnWidth,\n    timeAxisWidth,\n    snapMinutes,\n    dayStartHour,\n    dayEndHour,\n    edgeNavigationDays,\n    onEventChange: updateEvent,\n    onEventClick: handleEventClick,\n    onDragNavigate: handleDragNavigate,\n  });\n\n  const { scrollOffset, slideOffset, isAnimating, triggerSlideAnimation } =\n    useHorizontalScroll({\n      containerRef: scrollContainerRef,\n      dayColumnWidth,\n      onNavigate: handleNavigate,\n      disabled:\n        dragState?.isDragging ||\n        resizeState?.isResizing ||\n        isAllDayResizing ||\n        contextMenuOpen,\n    });\n\n  // Compute how many days the scroll has shifted from center\n  const scrollDaysDelta =\n    dayColumnWidth > 0 ? Math.round(-scrollOffset / dayColumnWidth) : 0;\n\n  // Report visible days to the provider in real-time as scroll crosses day\n  // boundaries. Not while it is adopting this grid: it sets them itself, and\n  // these would be the days of the date it is moving away from.\n  React.useEffect(() => {\n    if (!isProviderInSync) return;\n    const start = addDays(currentDate, scrollDaysDelta);\n    const end = addDays(start, VISIBLE_DAYS - 1);\n    reportVisibleDays(eachDayOfInterval({ start, end }));\n  }, [\n    isProviderInSync,\n    currentDate,\n    scrollDaysDelta,\n    reportVisibleDays,\n    VISIBLE_DAYS,\n  ]);\n\n  // Dynamic buffer: extends in BUFFER_STEP chunks based on scroll distance\n  const extraScrollDays =\n    dayColumnWidth > 0 && BUFFER_STEP > 0\n      ? Math.ceil(Math.abs(scrollOffset) / dayColumnWidth / BUFFER_STEP) *\n        BUFFER_STEP\n      : 0;\n  const dynamicBuffer = BUFFER_DAYS + extraScrollDays;\n  const totalDays = dynamicBuffer + VISIBLE_DAYS + dynamicBuffer;\n\n  // Extended buffered days for scroll (grows dynamically with scroll distance)\n  const bufferedBaseDays = React.useMemo(\n    () =>\n      generateBufferedDays(currentDate, dynamicBuffer, VISIBLE_DAYS, locale),\n    [currentDate, dynamicBuffer, VISIBLE_DAYS, locale],\n  );\n\n  const bufferedDays = withIsToday(bufferedBaseDays, today);\n\n  const bufferedDayDates = React.useMemo(\n    () => bufferedBaseDays.map((d) => d.date),\n    [bufferedBaseDays],\n  );\n\n  // What the grid draws: repeating events on each of their dates in the\n  // buffered days, generated for them and never stored (ADR-007)\n  const bufferStartTime = bufferedDayDates[0].getTime();\n  const bufferEndTime = addDays(\n    bufferedDayDates[bufferedDayDates.length - 1],\n    1,\n  ).getTime();\n  const displayedEvents = React.useMemo(\n    () =>\n      expandRecurringEvents(events, {\n        start: new Date(bufferStartTime),\n        end: new Date(bufferEndTime),\n      }),\n    [events, bufferStartTime, bufferEndTime],\n  );\n  const displayedAllDayEvents = React.useMemo(\n    () => displayedEvents.filter((e) => e.isAllDay || isMultiDayEvent(e)),\n    [displayedEvents],\n  );\n  const displayedTimedEvents = React.useMemo(\n    () => displayedEvents.filter((e) => !e.isAllDay && !isMultiDayEvent(e)),\n    [displayedEvents],\n  );\n\n  const { allDayResizeState, handleAllDayResizePointerDown } = useAllDayResize({\n    days: bufferedDayDates,\n    dayColumnWidth,\n    allDayContainerRef: allDayScrollContentRef,\n    events: allDayEvents,\n    onEventChange: updateEvent,\n    onEventClick: handleEventClick,\n  });\n\n  React.useEffect(() => {\n    setIsAllDayResizing(allDayResizeState?.isResizing ?? false);\n  }, [allDayResizeState?.isResizing]);\n\n  // Trigger slide animation when currentDate changes externally (not from scroll)\n  React.useEffect(() => {\n    const wasProviderInSync = wasProviderInSyncRef.current;\n    wasProviderInSyncRef.current = isProviderInSync;\n\n    if (scrollNavigatedRef.current) {\n      scrollNavigatedRef.current = false;\n      prevDateRef.current = currentDate;\n      return;\n    }\n\n    const prevDate = prevDateRef.current;\n    const daysDiff = differenceInCalendarDays(currentDate, prevDate);\n    prevDateRef.current = currentDate;\n\n    if (daysDiff === 0) return;\n    // Dates set while the provider adopts this grid (its starting date, or an\n    // undone switch) are not navigation\n    if (!wasProviderInSync || !isProviderInSync) return;\n\n    triggerSlideAnimation(daysDiff);\n  }, [currentDate, isProviderInSync, triggerSlideAnimation]);\n\n  // The base translateX centers on the visible days (skip dynamicBuffer columns)\n  const baseTranslateX = -(dynamicBuffer * dayColumnWidth);\n  const transformX = baseTranslateX + scrollOffset + slideOffset;\n\n  const scrollStyle: React.CSSProperties = {\n    width: `${(totalDays / VISIBLE_DAYS) * 100}%`,\n    transform: `translateX(${transformX}px)`,\n    transition: isAnimating ? `transform ${200}ms ease-out` : \"none\",\n  };\n\n  // Ref for the popover collision boundary (constrains popovers within the calendar area)\n  const calendarBoundaryRef = React.useRef<HTMLDivElement>(null);\n  // Ref for the header (weekday columns + all-day row) to measure its height for popover top inset\n  const calendarHeaderRef = React.useRef<HTMLDivElement>(null);\n\n  const isDayVisible = React.useCallback(\n    (date: Date) => visibleDayDates.some((day) => isSameDay(day, date)),\n    [visibleDayDates],\n  );\n\n  const revealDay = React.useCallback(\n    (date: Date) =>\n      goToDate(getPeriodStart(date, view, weekStartsOn, numberOfDays)),\n    [goToDate, view, weekStartsOn, numberOfDays],\n  );\n\n  /** The slot under the mouse: where the next paste goes */\n  const handleSlotHover = React.useCallback(\n    (range: NewEventRange) =>\n      reportPasteTarget({ date: range.start, hasTime: true }),\n    [reportPasteTarget],\n  );\n\n  const handleEventKeyDown = useEventKeyboard({\n    containerRef: calendarBoundaryRef,\n    scrollContainerRef,\n    isDayVisible,\n    revealDay,\n  });\n\n  return (\n    <CalendarPopoverBoundaryProvider\n      boundaryRef={calendarBoundaryRef}\n      headerRef={calendarHeaderRef}\n      view={view}\n    >\n      <div\n        ref={calendarBoundaryRef}\n        className={cn(\"flex h-full flex-col\", className)}\n        aria-busy={loading || undefined}\n        onKeyDown={handleEventKeyDown}\n        onClick={(e) => {\n          if (isEventInsideCalendarPopover(e)) return;\n          clearSelection();\n        }}\n      >\n        {/* Header - day columns and all-day row with synchronized scroll */}\n        <div className=\"relative flex-shrink-0\">\n          <div\n            ref={(el) => {\n              (\n                dayColumnsScrollRef as React.MutableRefObject<HTMLDivElement | null>\n              ).current = el;\n              (\n                calendarHeaderRef as React.MutableRefObject<HTMLDivElement | null>\n              ).current = el;\n            }}\n            className=\"overflow-hidden\"\n          >\n            <div className=\"flex bg-background\">\n              {/* Time zone labels, one per time axis column - rendered outside scroll container */}\n              {secondaryTimeZone && (\n                <div className=\"text-muted-foreground flex w-16 flex-shrink-0 items-center justify-end pr-2 text-xxs\">\n                  {secondaryAxis?.label}\n                </div>\n              )}\n              <div className=\"text-muted-foreground flex w-16 flex-shrink-0 items-center justify-end pr-2 text-xxs\">\n                {timeZoneLabel}\n              </div>\n              <div className=\"min-w-0 flex-1 overflow-clip\">\n                <div style={scrollStyle}>\n                  <CalendarDayHeaders\n                    days={bufferedDays}\n                    standalone\n                    highlightedDate={highlightedDate}\n                  />\n                </div>\n              </div>\n            </div>\n          </div>\n          <div className=\"overflow-hidden\" ref={allDayScrollRef}>\n            <WeekViewAllDayRow\n              days={bufferedDays}\n              allDayEvents={displayedAllDayEvents}\n              onEventClick={handleEventClick}\n              selectedEventId={selectedEventId}\n              scrollStyle={scrollStyle}\n              allDayResizeState={allDayResizeState ?? undefined}\n              onAllDayResizePointerDown={handleAllDayResizePointerDown}\n              onEventChange={updateEvent}\n              onContextMenuOpenChange={setContextMenuOpen}\n              allDayScrollContentRef={allDayScrollContentRef}\n              showEventPopover={showEventPopover}\n              onEventPopoverExpand={onEventPopoverExpand}\n              onEventPopoverClose={closeEventPopover}\n              visibleStartIndex={dynamicBuffer}\n              visibleCount={VISIBLE_DAYS}\n              dayColumnWidth={dayColumnWidth}\n              highlightedDate={highlightedDate}\n              timeAxisWidth={timeAxisWidth}\n            />\n          </div>\n          {/* Under the day columns, along the header's bottom border */}\n          {loading && (\n            <CalendarLoadingBar\n              className={secondaryTimeZone ? \"left-32\" : \"left-16\"}\n            />\n          )}\n        </div>\n\n        {/* Scrollable grid area \\u2014 also serves as the collision boundary for popovers */}\n        <div\n          ref={scrollContainerRef}\n          className=\"flex-1 overflow-auto scrollbar-hide\"\n        >\n          <div\n            className=\"relative flex\"\n            style={{ height: hours.length * hourHeight }}\n          >\n            {secondaryTimeZone && (\n              <WeekViewTimeAxis\n                hours={hours}\n                hourHeight={hourHeight}\n                labels={secondaryAxis?.hourLabels ?? NO_LABELS}\n              />\n            )}\n            <WeekViewTimeAxis hours={hours} hourHeight={hourHeight} />\n            {/* Buffer wrappers clip rather than hide: a hidden box can still be\n                scrolled by script or the browser (e.g. scrollIntoView before\n                an automated click), which would slide the grid out of line\n                with the day headers. The buffer only moves by scrollStyle. */}\n            <div className=\"relative min-w-0 flex-1 overflow-clip\">\n              <div style={scrollStyle}>\n                <WeekViewGrid\n                  days={bufferedDays}\n                  hours={hours}\n                  hourHeight={hourHeight}\n                  events={displayedTimedEvents}\n                  onEventClick={handleEventClick}\n                  selectedEventId={selectedEventId}\n                  onEventCreate={addEventFromRange}\n                  onSlotHover={handleSlotHover}\n                  dragState={dragState ?? undefined}\n                  onEventDragPointerDown={handleEventPointerDown}\n                  resizeState={resizeState ?? undefined}\n                  onEventResizePointerDown={handleResizePointerDown}\n                  onEventChange={updateEvent}\n                  onContextMenuOpenChange={setContextMenuOpen}\n                  showEventPopover={showEventPopover}\n                  onEventPopoverExpand={onEventPopoverExpand}\n                  onEventPopoverClose={closeEventPopover}\n                  highlightedDate={highlightedDate}\n                  visibleStartIndex={dynamicBuffer}\n                  visibleCount={VISIBLE_DAYS}\n                />\n              </div>\n            </div>\n            <WeekViewTimeIndicator\n              days={days}\n              hourHeight={hourHeight}\n              scrollDays={bufferedDays}\n              scrollStyle={scrollStyle}\n              behindSelection={!!selectedEventId}\n              timeAxisWidth={timeAxisWidth}\n            />\n          </div>\n        </div>\n      </div>\n    </CalendarPopoverBoundaryProvider>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/calendar-day-headers.tsx",
      "content": "\"use client\";\n\nimport { isSameDay } from \"date-fns\";\nimport { cn } from \"@/lib/utils\";\nimport { useTimeZoneLabel } from \"@/hooks/use-timezone-label\";\nimport type { WeekViewDayColumnsProps } from \"./week-view-types\";\n\n/**\n * Day column headers showing day names and date numbers\n * Includes timezone label on the left (unless standalone mode)\n * Highlights the current day\n */\nexport function CalendarDayHeaders({\n  days,\n  standalone,\n  highlightedDate,\n  className,\n}: WeekViewDayColumnsProps) {\n  // Empty on the server and during hydration, the viewer's zone afterwards\n  const timezone = useTimeZoneLabel();\n\n  // Standalone mode: just render the day columns (used inside scroll container)\n  if (standalone) {\n    // Visual only (including the off-screen buffer days): each day column\n    // in the grid is labeled with its full date\n    return (\n      <div\n        aria-hidden\n        className={cn(\"grid\", className)}\n        style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n      >\n        {days.map((day) => (\n          <div\n            key={day.date.toISOString()}\n            className={cn(\n              \"flex items-center justify-center py-2 text-sm\",\n              day.isToday ? \"gap-0.5 \" : \"gap-0\",\n              highlightedDate &&\n                isSameDay(day.date, highlightedDate) &&\n                \"column-highlight\",\n            )}\n          >\n            <span\n              className={cn(\n                day.isToday\n                  ? \"text-foreground font-medium\"\n                  : \"text-muted-foreground font-normal\",\n              )}\n            >\n              {day.dayName}\n            </span>\n            <span\n              className={cn(\n                \"flex h-5 w-[1.2rem] items-center justify-center rounded-xs text-sm\",\n                day.isToday\n                  ? \"bg-primary text-primary-foreground font-medium\"\n                  : \"text-muted-foreground\",\n              )}\n            >\n              {day.dayNumber}\n            </span>\n          </div>\n        ))}\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className={cn(\"grid bg-background\", className)}\n      style={{ gridTemplateColumns: \"4rem 1fr\" }}\n    >\n      {/* Timezone label */}\n      <div className=\"text-muted-foreground flex items-center justify-end pr-2 text-xxs\">\n        {timezone}\n      </div>\n\n      {/* Day columns */}\n      <div\n        className=\"grid\"\n        style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n      >\n        {days.map((day) => (\n          <div\n            key={day.date.toISOString()}\n            className={cn(\n              \"flex items-center justify-center py-2 text-sm\",\n              day.isToday ? \"gap-0.5 \" : \"gap-0\",\n              highlightedDate &&\n                isSameDay(day.date, highlightedDate) &&\n                \"column-highlight\",\n            )}\n          >\n            <span\n              className={cn(\n                day.isToday\n                  ? \"text-foreground font-medium\"\n                  : \"text-muted-foreground font-normal\",\n              )}\n            >\n              {day.dayName}\n            </span>\n            <span\n              className={cn(\n                \"flex h-5 w-[1.2rem] items-center justify-center rounded-xs text-sm\",\n                day.isToday\n                  ? \"bg-primary text-primary-foreground font-medium\"\n                  : \"text-muted-foreground\",\n              )}\n            >\n              {day.dayNumber}\n            </span>\n          </div>\n        ))}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/week-view-all-day-row.tsx",
      "content": "\"use client\";\n\nimport type React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { cn } from \"@/lib/utils\";\nimport { isSameDay } from \"date-fns\";\nimport { useCallback } from \"react\";\nimport { calculateAllDayEventRows } from \"@/lib/event-utils\";\nimport { AllDayEventItem } from \"./calendar-event-item\";\nimport { useCalendarPopoverBoundary } from \"./calendar-popover-context\";\nimport type {\n  CalendarEvent,\n  EventItemPopoverProps,\n  WeekViewAllDayRowProps,\n} from \"./week-view-types\";\n\nconst ALL_DAY_EVENT_HEIGHT = 24;\nconst ALL_DAY_ROW_GAP = 2;\n\n/**\n * All-day row for displaying all-day events\n * Shows \"All-day\" label on the left with day columns\n */\nexport function WeekViewAllDayRow({\n  days,\n  allDayEvents = [],\n  onEventClick,\n  selectedEventId,\n  scrollStyle,\n  allDayResizeState,\n  onAllDayResizePointerDown,\n  allDayScrollContentRef,\n  onEventChange,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  visibleStartIndex,\n  visibleCount,\n  dayColumnWidth,\n  highlightedDate,\n  timeAxisWidth,\n  className,\n}: WeekViewAllDayRowProps) {\n  const allEventRows = calculateAllDayEventRows(allDayEvents, days);\n\n  // Filter out events entirely within buffer columns so they don't peek\n  // through due to sub-pixel rendering at the scroll boundary.\n  const visibleEnd =\n    visibleStartIndex != null && visibleCount != null\n      ? visibleStartIndex + visibleCount - 1\n      : days.length - 1;\n  const eventRows =\n    visibleStartIndex != null\n      ? allEventRows.filter(\n          ({ startColumn, endColumn }) =>\n            endColumn >= visibleStartIndex && startColumn <= visibleEnd,\n        )\n      : allEventRows;\n  const maxRow =\n    eventRows.length > 0 ? Math.max(...eventRows.map((r) => r.row)) + 1 : 0;\n  const contentHeight =\n    maxRow > 0 ? maxRow * (ALL_DAY_EVENT_HEIGHT + ALL_DAY_ROW_GAP) + 8 : 32;\n\n  const isMoveDrag =\n    allDayResizeState?.isResizing && allDayResizeState.edge === \"move\";\n\n  return (\n    <div\n      className={cn(\n        \"border-border flex border-t border-b bg-background\",\n        className,\n      )}\n    >\n      {/* All-day label, as wide as the time axis below it */}\n      <div\n        className=\"border-border text-muted-foreground flex w-16 flex-shrink-0 items-start justify-end border-r px-2 py-2 text-xxs\"\n        style={\n          timeAxisWidth === undefined ? undefined : { width: timeAxisWidth }\n        }\n      >\n        All-day\n      </div>\n\n      {/* Day columns for all-day events - wrapped for scroll sync */}\n      <div className=\"min-w-0 flex-1 overflow-clip\">\n        <div ref={allDayScrollContentRef} style={scrollStyle}>\n          <div className=\"relative\" style={{ minHeight: `${contentHeight}px` }}>\n            {/* Background grid */}\n            <div\n              aria-hidden\n              className=\"absolute inset-0 grid\"\n              style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n            >\n              {days.map((day) => {\n                const isWeekend =\n                  day.date.getDay() === 0 || day.date.getDay() === 6;\n                return (\n                  <div\n                    key={day.date.toISOString()}\n                    className={cn(\n                      \"border-border border-l first:border-l-0 h-full\",\n                      isWeekend && \"bg-calendar-weekend\",\n                      highlightedDate &&\n                        isSameDay(day.date, highlightedDate) &&\n                        \"column-highlight\",\n                    )}\n                  />\n                );\n              })}\n            </div>\n\n            {/* Events */}\n            <div className=\"relative py-1 px-0.5\">\n              {eventRows.map(({ event, startColumn, endColumn, row }) => {\n                const isBeingResized =\n                  allDayResizeState?.eventId === event.id &&\n                  allDayResizeState.isResizing;\n                const isBeingMoved =\n                  isBeingResized && allDayResizeState.edge === \"move\";\n\n                // For move: ghost stays at original, event renders at target\n                // For resize: event renders at target (current columns)\n                const displayStartColumn = isBeingResized\n                  ? isBeingMoved\n                    ? startColumn\n                    : allDayResizeState.currentStartColumn\n                  : startColumn;\n                const displayEndColumn = isBeingResized\n                  ? isBeingMoved\n                    ? endColumn\n                    : allDayResizeState.currentEndColumn\n                  : endColumn;\n\n                return (\n                  <AllDayEventRow\n                    key={event.id}\n                    event={event}\n                    startColumn={displayStartColumn}\n                    endColumn={displayEndColumn}\n                    row={row}\n                    totalColumns={days.length}\n                    days={days}\n                    onEventClick={onEventClick}\n                    isSelected={event.id === selectedEventId}\n                    onAllDayResizePointerDown={onAllDayResizePointerDown}\n                    originalStartColumn={startColumn}\n                    originalEndColumn={endColumn}\n                    isBeingResized={isBeingResized}\n                    isBeingMoved={isBeingMoved}\n                    onEventChange={onEventChange}\n                    onContextMenuOpenChange={onContextMenuOpenChange}\n                    showEventPopover={showEventPopover}\n                    onEventPopoverExpand={onEventPopoverExpand}\n                    onEventPopoverClose={onEventPopoverClose}\n                    visibleStartIndex={visibleStartIndex}\n                  />\n                );\n              })}\n\n              {/* Placeholder at target position during move */}\n              {isMoveDrag &&\n                (() => {\n                  const movedRow = eventRows.find(\n                    (r) => r.event.id === allDayResizeState.eventId,\n                  );\n                  if (!movedRow) return null;\n                  return (\n                    <AllDayPlaceholderRow\n                      event={movedRow.event}\n                      startColumn={allDayResizeState.currentStartColumn}\n                      endColumn={allDayResizeState.currentEndColumn}\n                      row={movedRow.row}\n                      totalColumns={days.length}\n                    />\n                  );\n                })()}\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {/* Floating drag copy via portal */}\n      {isMoveDrag &&\n        allDayResizeState.clientX != null &&\n        allDayResizeState.clientY != null &&\n        (() => {\n          const movedRow = eventRows.find(\n            (r) => r.event.id === allDayResizeState.eventId,\n          );\n          if (!movedRow) return null;\n          const span = movedRow.endColumn - movedRow.startColumn + 1;\n          const colWidthPx = dayColumnWidth ?? 100;\n          const floatingWidth = span * colWidthPx;\n          const offsetX = allDayResizeState.cursorOffsetX ?? 0;\n\n          return createPortal(\n            <div\n              aria-hidden\n              className=\"pointer-events-none\"\n              style={{\n                position: \"fixed\",\n                top: 0,\n                left: 0,\n                width: \"100vw\",\n                height: \"100vh\",\n                zIndex: 9999,\n              }}\n            >\n              <div\n                style={{\n                  position: \"fixed\",\n                  left: `${allDayResizeState.clientX - offsetX}px`,\n                  top: `${allDayResizeState.clientY - (allDayResizeState.cursorOffsetY ?? 12)}px`,\n                  width: `${floatingWidth}px`,\n                }}\n              >\n                <AllDayEventItem\n                  event={movedRow.event}\n                  spanStart\n                  spanEnd\n                  dragVariant=\"dragging\"\n                />\n              </div>\n            </div>,\n            document.body,\n          );\n        })()}\n    </div>\n  );\n}\n\ninterface AllDayEventRowProps extends EventItemPopoverProps {\n  event: CalendarEvent;\n  startColumn: number;\n  endColumn: number;\n  row: number;\n  totalColumns: number;\n  days: WeekViewAllDayRowProps[\"days\"];\n  onEventClick?: (event: CalendarEvent) => void;\n  isSelected?: boolean;\n  onAllDayResizePointerDown?: WeekViewAllDayRowProps[\"onAllDayResizePointerDown\"];\n  originalStartColumn: number;\n  originalEndColumn: number;\n  isBeingResized?: boolean;\n  isBeingMoved?: boolean;\n  /** Callback when an event is changed (e.g. color change from context menu) */\n  onEventChange?: (event: CalendarEvent) => void;\n  /** Callback when context menu open state changes */\n  onContextMenuOpenChange?: (open: boolean) => void;\n  /** Index of the first visible column (for sticky-title offset) */\n  visibleStartIndex?: number;\n}\n\nfunction AllDayEventRow({\n  event,\n  startColumn,\n  endColumn,\n  row,\n  totalColumns,\n  days,\n  onEventClick,\n  isSelected,\n  onAllDayResizePointerDown,\n  originalStartColumn,\n  originalEndColumn,\n  isBeingResized,\n  isBeingMoved,\n  onEventChange,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  visibleStartIndex,\n}: AllDayEventRowProps) {\n  const { view } = useCalendarPopoverBoundary();\n  const isDayView = view === \"day\";\n\n  const left = (startColumn / totalColumns) * 100;\n  // Day view uses a smaller right gap than week view so events nearly fill\n  // the column but still show a sliver of the grid \\u2014 matching Notion Calendar.\n  const columnWidth = 100 / totalColumns;\n  const rightGap = isDayView ? columnWidth * 0.02 : columnWidth * 0.08;\n  const width = ((endColumn - startColumn + 1) / totalColumns) * 100 - rightGap;\n  const top = row * (ALL_DAY_EVENT_HEIGHT + ALL_DAY_ROW_GAP);\n\n  // During resize, both edges are always visible so force rounding on both sides\n  const spanStart =\n    isBeingResized || isSameDay(event.start, days[startColumn].date);\n  const spanEnd = isBeingResized || isSameDay(event.end, days[endColumn].date);\n\n  /**\n   * In day view with buffer days (3 columns: buffer | visible | buffer),\n   * the visible column is index 1. Multi-day events that start in the left\n   * buffer (column 0) have their title off-screen. Calculate the percentage\n   * offset needed to push the title into the visible area.\n   *\n   * CSS `padding-left` percentages are relative to the **containing block's\n   * width** (the wrapper div), not the grid container. We must convert from\n   * container-relative coordinates to wrapper-relative coordinates:\n   *   offset = (visibleStart% - left%) \\u00D7 (100 / width%)\n   */\n  const visibleColumnIndex = visibleStartIndex ?? 1;\n  const visibleStartPercent = (visibleColumnIndex / totalColumns) * 100;\n  const hiddenContainerPercent = isDayView\n    ? Math.max(0, visibleStartPercent - left)\n    : 0;\n  /** Small extra nudge (in container %) so the title doesn't sit flush\n   *  against the visible column edge \\u2014 gives it a bit of breathing room. */\n  const TITLE_NUDGE_PERCENT = 0.1;\n  const titleOffsetPercent =\n    hiddenContainerPercent > 0 && width > 0\n      ? ((hiddenContainerPercent + TITLE_NUDGE_PERCENT) / width) * 100\n      : 0;\n\n  const handleResizePointerDown = useCallback(\n    (\n      e: React.PointerEvent<HTMLElement>,\n      ev: CalendarEvent,\n      edge: \"left\" | \"right\" | \"move\",\n    ) => {\n      onAllDayResizePointerDown?.(\n        e,\n        ev,\n        edge,\n        originalStartColumn,\n        originalEndColumn,\n      );\n    },\n    [onAllDayResizePointerDown, originalStartColumn, originalEndColumn],\n  );\n\n  return (\n    <div\n      className=\"absolute\"\n      style={{\n        left: `${left}%`,\n        width: `${width}%`,\n        top: `${top}px`,\n        paddingLeft: \"2px\",\n        paddingRight: \"2px\",\n      }}\n    >\n      <AllDayEventItem\n        event={event}\n        isSelected={isBeingMoved ? false : isSelected}\n        onClick={onEventClick}\n        spanStart={spanStart}\n        spanEnd={spanEnd}\n        onResizePointerDown={handleResizePointerDown}\n        onEventChange={onEventChange}\n        onContextMenuOpenChange={onContextMenuOpenChange}\n        showEventPopover={showEventPopover}\n        onEventPopoverExpand={onEventPopoverExpand}\n        onEventPopoverClose={onEventPopoverClose}\n        titleOffsetPercent={titleOffsetPercent}\n        dragVariant={isBeingMoved ? \"ghost\" : undefined}\n        isResizing={isBeingResized && !isBeingMoved}\n      />\n    </div>\n  );\n}\n\n/** Placeholder border-only outline rendered at the target position during move */\nfunction AllDayPlaceholderRow({\n  event,\n  startColumn,\n  endColumn,\n  row,\n  totalColumns,\n}: {\n  event: CalendarEvent;\n  startColumn: number;\n  endColumn: number;\n  row: number;\n  totalColumns: number;\n}) {\n  const columnWidth = 100 / totalColumns;\n  const left = (startColumn / totalColumns) * 100;\n  const rightGap = columnWidth * 0.08;\n  const width = ((endColumn - startColumn + 1) / totalColumns) * 100 - rightGap;\n  const top = row * (ALL_DAY_EVENT_HEIGHT + ALL_DAY_ROW_GAP);\n\n  return (\n    <div\n      aria-hidden\n      className=\"absolute pointer-events-none\"\n      style={{\n        left: `${left}%`,\n        width: `${width}%`,\n        top: `${top}px`,\n        paddingLeft: \"2px\",\n        paddingRight: \"2px\",\n        zIndex: 25,\n      }}\n    >\n      <AllDayEventItem\n        event={event}\n        spanStart\n        spanEnd\n        dragVariant=\"placeholder\"\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/week-view-grid.tsx",
      "content": "\"use client\";\n\nimport React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { isSameDay, startOfDay, addDays } from \"date-fns\";\nimport { cn } from \"@/lib/utils\";\nimport { isPrimaryPress, usePointerGesture } from \"@/hooks/use-pointer-gesture\";\nimport {\n  calculatePositionedEvents,\n  formatFullDate,\n  getNewEventRange,\n} from \"@/lib/event-utils\";\nimport { CalendarEventItem } from \"./calendar-event-item\";\nimport { useCalendarPopoverBoundary } from \"./calendar-popover-context\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport type {\n  CalendarEvent,\n  EventDragState,\n  EventItemPopoverProps,\n  EventResizeState,\n  PositionedEvent,\n  WeekViewGridProps,\n} from \"./week-view-types\";\n\n/**\n * Max pointer travel (px) between pointerdown and click for a click on an\n * empty slot to create an event. Matches the drag threshold in\n * use-event-drag so a press that moves far enough to count as a drag never\n * also creates an event.\n */\nconst CREATE_CLICK_TOLERANCE_PX = 4;\n\n/** Pointer position recorded when a mouse or pen press lands on an empty day column */\ninterface PendingCreateClick {\n  clientX: number;\n  clientY: number;\n}\n\n/**\n * Main grid displaying hour/day intersection cells with events\n * Each cell represents one hour in one day\n */\nexport function WeekViewGrid({\n  days,\n  hours,\n  hourHeight,\n  events = [],\n  onEventClick,\n  selectedEventId,\n  onEventCreate,\n  onSlotHover,\n  dragState,\n  onEventDragPointerDown,\n  resizeState,\n  onEventResizePointerDown,\n  onEventChange,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  highlightedDate,\n  visibleStartIndex = 0,\n  visibleCount,\n  className,\n}: WeekViewGridProps) {\n  const { view } = useCalendarPopoverBoundary();\n  const config = useCalendarConfig();\n  const isDayView = view === \"day\";\n  const gridRef = React.useRef<HTMLDivElement>(null);\n  /** Set only by a mouse or pen press directly on empty column space */\n  const pendingCreateRef = React.useRef<PendingCreateClick | null>(null);\n  const [gridWidth, setGridWidth] = React.useState(0);\n  const { startGesture } = usePointerGesture({ containerRef: gridRef });\n\n  React.useEffect(() => {\n    const el = gridRef.current;\n    if (!el) return;\n\n    const observer = new ResizeObserver((entries) => {\n      for (const entry of entries) {\n        setGridWidth(entry.contentRect.width);\n      }\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  /** The new-event range of the slot at a viewport Y position in a column */\n  const getSlotRange = React.useCallback(\n    (column: HTMLElement, columnDate: Date, clientY: number) => {\n      // The column's top edge is `dayStartHour`, not midnight\n      const columnTop = column.getBoundingClientRect().top;\n      const minutesFromMidnight =\n        config.dayStartHour * 60 + ((clientY - columnTop) / hourHeight) * 60;\n      return getNewEventRange(columnDate, minutesFromMidnight, config);\n    },\n    [hourHeight, config],\n  );\n\n  /** Creates an event in a column at a viewport Y position */\n  const createEventAt = React.useCallback(\n    (column: HTMLElement, columnDate: Date, clientY: number) => {\n      if (!onEventCreate) return;\n      onEventCreate(getSlotRange(column, columnDate, clientY));\n    },\n    [onEventCreate, getSlotRange],\n  );\n\n  /**\n   * Reports the mouse's slot, where a paste goes. Pointer moves in a\n   * popover or menu bubble here through React portals: those are skipped,\n   * since their DOM is outside the column.\n   */\n  const handleColumnPointerMove = React.useCallback(\n    (e: React.PointerEvent<HTMLDivElement>, columnDate: Date) => {\n      if (!onSlotHover || e.pointerType !== \"mouse\") return;\n      if (!(e.target instanceof Node)) return;\n      if (!e.currentTarget.contains(e.target)) return;\n      onSlotHover(getSlotRange(e.currentTarget, columnDate, e.clientY));\n    },\n    [onSlotHover, getSlotRange],\n  );\n\n  /**\n   * Capture phase runs before event items stop pointerdown propagation, so\n   * a press that starts on an event (drag, resize, select) always clears any\n   * pending create left over from an earlier press.\n   */\n  const handleColumnPointerDownCapture = React.useCallback(() => {\n    pendingCreateRef.current = null;\n  }, []);\n\n  const handleColumnPointerDown = React.useCallback(\n    (e: React.PointerEvent<HTMLDivElement>, columnDate: Date) => {\n      if (e.target !== e.currentTarget) return;\n      // Touch creates with a long press, so a swipe over empty space still\n      // scrolls and a tap only clears the selection\n      if (e.pointerType === \"touch\") {\n        startGesture(e, ({ clientY, element }) =>\n          createEventAt(element, columnDate, clientY),\n        );\n        return;\n      }\n      if (!isPrimaryPress(e)) return;\n      pendingCreateRef.current = { clientX: e.clientX, clientY: e.clientY };\n    },\n    [startGesture, createEventAt],\n  );\n\n  /**\n   * Creates an event when a press started and ended on empty space in the\n   * same column without moving. With an event selected the click is left to\n   * bubble so WeekView's background click deselects instead.\n   */\n  const handleColumnClick = React.useCallback(\n    (e: React.MouseEvent<HTMLDivElement>, columnDate: Date) => {\n      const pending = pendingCreateRef.current;\n      pendingCreateRef.current = null;\n\n      if (!pending || !onEventCreate) return;\n      if (e.target !== e.currentTarget) return;\n      if (selectedEventId) return;\n\n      const movedX = Math.abs(e.clientX - pending.clientX);\n      const movedY = Math.abs(e.clientY - pending.clientY);\n      if (\n        movedX > CREATE_CLICK_TOLERANCE_PX ||\n        movedY > CREATE_CLICK_TOLERANCE_PX\n      ) {\n        return;\n      }\n\n      e.stopPropagation();\n      createEventAt(e.currentTarget, columnDate, e.clientY);\n    },\n    [onEventCreate, selectedEventId, createEventAt],\n  );\n\n  return (\n    <div ref={gridRef} className={cn(\"relative\", className)}>\n      {/* Background grid */}\n      <div\n        aria-hidden\n        className=\"grid\"\n        style={{\n          gridTemplateColumns: `repeat(${days.length}, 1fr)`,\n          gridTemplateRows: `repeat(${hours.length}, ${hourHeight}px)`,\n        }}\n      >\n        {hours.map((hourSlot) =>\n          days.map((day) => {\n            const isWeekend =\n              day.date.getDay() === 0 || day.date.getDay() === 6;\n            return (\n              <div\n                key={`${day.date.toISOString()}-${hourSlot.hour}`}\n                className={cn(\n                  \"border-border border-b border-l\",\n                  isWeekend && \"bg-calendar-weekend\",\n                )}\n              />\n            );\n          }),\n        )}\n      </div>\n\n      {/* Column highlight layer — brief background fade for \"+N more\" navigation */}\n      {highlightedDate && (\n        <div\n          aria-hidden\n          className=\"absolute inset-0 grid pointer-events-none\"\n          style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n        >\n          {days.map((day) => (\n            <div\n              key={day.date.toISOString()}\n              className={cn(\n                isSameDay(day.date, highlightedDate) && \"column-highlight\",\n              )}\n            />\n          ))}\n        </div>\n      )}\n\n      {/* Events layer */}\n      <div\n        className=\"absolute inset-0 grid pointer-events-none\"\n        style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n      >\n        {days.map((day, index) => {\n          const isOnScreen =\n            index >= visibleStartIndex &&\n            index < visibleStartIndex + (visibleCount ?? days.length);\n          /**\n           * Day view uses a smaller right gap than week view so events\n           * nearly fill the column but still show a sliver of the grid\n           * line — matching Notion Calendar's day-view styling.\n           */\n          const rightGap = isDayView ? 2 : 8;\n          const positionedEvents = calculatePositionedEvents(\n            events,\n            day,\n            config,\n            rightGap,\n          );\n\n          return (\n            <DayEventsColumn\n              key={day.date.toISOString()}\n              columnDate={day.date}\n              label={formatFullDate(day.date, config.locale)}\n              isOnScreen={isOnScreen}\n              events={positionedEvents}\n              hourHeight={hourHeight}\n              onEventClick={onEventClick}\n              selectedEventId={selectedEventId}\n              dragState={dragState}\n              onEventDragPointerDown={onEventDragPointerDown}\n              resizeState={resizeState}\n              onEventResizePointerDown={onEventResizePointerDown}\n              onEventChange={onEventChange}\n              onContextMenuOpenChange={onContextMenuOpenChange}\n              showEventPopover={showEventPopover}\n              onEventPopoverExpand={onEventPopoverExpand}\n              onEventPopoverClose={onEventPopoverClose}\n              onColumnPointerDownCapture={handleColumnPointerDownCapture}\n              onColumnPointerDown={handleColumnPointerDown}\n              onColumnPointerMove={handleColumnPointerMove}\n              onColumnClick={handleColumnClick}\n            />\n          );\n        })}\n      </div>\n\n      {/* Resize placeholder overlay — rendered at grid level for cross-day support */}\n      {resizeState?.isResizing &&\n        !isSameDay(\n          resizeState.currentStartDate,\n          resizeState.currentEndDate,\n        ) && (\n          <ResizePlaceholderOverlay\n            days={days}\n            hourHeight={hourHeight}\n            resizeState={resizeState}\n          />\n        )}\n\n      {/* Drag placeholder overlay — rendered at grid level for cross-column support */}\n      {dragState?.isDragging && (\n        <DragPlaceholderOverlay\n          days={days}\n          hourHeight={hourHeight}\n          dragState={dragState}\n        />\n      )}\n\n      {/* Floating dragging copy — rendered at grid level so it can move freely */}\n      {dragState?.isDragging && (\n        <FloatingDragCopy\n          days={days}\n          hourHeight={hourHeight}\n          dragState={dragState}\n          gridWidth={gridWidth}\n        />\n      )}\n    </div>\n  );\n}\n\ninterface DragPlaceholderOverlayProps {\n  days: WeekViewGridProps[\"days\"];\n  hourHeight: number;\n  dragState: EventDragState;\n}\n\nfunction DragPlaceholderOverlay({\n  days,\n  hourHeight,\n  dragState,\n}: DragPlaceholderOverlayProps) {\n  // Find the target column index using dragState.currentDate\n  const targetColumnIndex = days.findIndex((d) =>\n    isSameDay(d.date, dragState.currentDate),\n  );\n\n  if (targetColumnIndex === -1) return null;\n\n  // Build a minimal PositionedEvent from the drag state event\n  const placeholderPositioned: PositionedEvent = {\n    event: dragState.event,\n    top: 0,\n    height: 0,\n    left: 0,\n    width: 92,\n    column: 0,\n    totalColumns: 1,\n  };\n\n  return (\n    <div\n      aria-hidden\n      className=\"absolute inset-0 grid pointer-events-none\"\n      style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n    >\n      {days.map((day, i) => {\n        if (i !== targetColumnIndex) {\n          return <div key={day.date.toISOString()} />;\n        }\n\n        return (\n          <div key={day.date.toISOString()} className=\"relative\">\n            <CalendarEventItem\n              key={`${dragState.eventId}-placeholder`}\n              positionedEvent={placeholderPositioned}\n              hourHeight={hourHeight}\n              dragVariant=\"placeholder\"\n              overrideStart={dragState.currentStart}\n              overrideEnd={dragState.currentEnd}\n            />\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\ninterface ResizePlaceholderOverlayProps {\n  days: WeekViewGridProps[\"days\"];\n  hourHeight: number;\n  resizeState: EventResizeState;\n}\n\nfunction ResizePlaceholderOverlay({\n  days,\n  hourHeight,\n  resizeState,\n}: ResizePlaceholderOverlayProps) {\n  if (resizeState.effectiveEdge === \"bottom\") {\n    return (\n      <BottomEdgeOverlay\n        days={days}\n        hourHeight={hourHeight}\n        resizeState={resizeState}\n      />\n    );\n  }\n\n  return (\n    <TopEdgeOverlay\n      days={days}\n      hourHeight={hourHeight}\n      resizeState={resizeState}\n    />\n  );\n}\n\nfunction BottomEdgeOverlay({\n  days,\n  hourHeight,\n  resizeState,\n}: ResizePlaceholderOverlayProps) {\n  const endDay = resizeState.currentEndDate;\n\n  const startColIndex = days.findIndex((d) =>\n    isSameDay(d.date, resizeState.currentStartDate),\n  );\n  const endColIndex = days.findIndex((d) => isSameDay(d.date, endDay));\n\n  if (startColIndex === -1 || endColIndex === -1) return null;\n  if (endColIndex <= startColIndex) return null;\n\n  return (\n    <div\n      aria-hidden\n      className=\"absolute inset-0 grid pointer-events-none\"\n      style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n    >\n      {days.map((day, i) => {\n        // Skip start column (handled by DayEventsColumn) and columns outside range\n        if (i <= startColIndex || i > endColIndex) {\n          return <div key={day.date.toISOString()} />;\n        }\n\n        const isEndColumn = i === endColIndex;\n        const segmentPosition = isEndColumn\n          ? (\"end\" as const)\n          : (\"middle\" as const);\n\n        const midnight = startOfDay(day.date);\n        const overrideStart = midnight;\n        const overrideEnd = isEndColumn\n          ? resizeState.currentEnd\n          : addDays(midnight, 1);\n\n        const positioned: PositionedEvent = {\n          event: resizeState.event,\n          top: 0,\n          height: 0,\n          left: 0,\n          width: 92,\n          column: 0,\n          totalColumns: 1,\n          segmentPosition,\n        };\n\n        return (\n          <div key={day.date.toISOString()} className=\"relative\">\n            <CalendarEventItem\n              positionedEvent={positioned}\n              hourHeight={hourHeight}\n              isSelected\n              isResizing\n              overrideStart={overrideStart}\n              overrideEnd={overrideEnd}\n            />\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\nfunction TopEdgeOverlay({\n  days,\n  hourHeight,\n  resizeState,\n}: ResizePlaceholderOverlayProps) {\n  const startDay = resizeState.currentStartDate;\n\n  const startColIndex = days.findIndex((d) => isSameDay(d.date, startDay));\n  const endColIndex = days.findIndex((d) =>\n    isSameDay(d.date, resizeState.currentEndDate),\n  );\n\n  if (startColIndex === -1 || endColIndex === -1) return null;\n  if (endColIndex <= startColIndex) return null;\n\n  return (\n    <div\n      aria-hidden\n      className=\"absolute inset-0 grid pointer-events-none\"\n      style={{ gridTemplateColumns: `repeat(${days.length}, 1fr)` }}\n    >\n      {days.map((day, i) => {\n        // Skip end column (handled by DayEventsColumn) and columns outside range\n        if (i < startColIndex || i >= endColIndex) {\n          return <div key={day.date.toISOString()} />;\n        }\n\n        const isStartColumn = i === startColIndex;\n        const segmentPosition = isStartColumn\n          ? (\"start\" as const)\n          : (\"middle\" as const);\n\n        const midnight = startOfDay(day.date);\n        const overrideStart = isStartColumn\n          ? resizeState.currentStart\n          : midnight;\n        const overrideEnd = addDays(midnight, 1);\n\n        const positioned: PositionedEvent = {\n          event: resizeState.event,\n          top: 0,\n          height: 0,\n          left: 0,\n          width: 92,\n          column: 0,\n          totalColumns: 1,\n          segmentPosition,\n        };\n\n        return (\n          <div key={day.date.toISOString()} className=\"relative\">\n            <CalendarEventItem\n              positionedEvent={positioned}\n              hourHeight={hourHeight}\n              isSelected\n              isResizing\n              overrideStart={overrideStart}\n              overrideEnd={overrideEnd}\n            />\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\ninterface FloatingDragCopyProps {\n  days: WeekViewGridProps[\"days\"];\n  hourHeight: number;\n  dragState: EventDragState;\n  gridWidth: number;\n}\n\nfunction FloatingDragCopy({\n  days,\n  hourHeight,\n  dragState,\n  gridWidth,\n}: FloatingDragCopyProps) {\n  const floatingPositioned: PositionedEvent = {\n    event: dragState.event,\n    top: 0,\n    height: 0,\n    left: 0,\n    width: 92,\n    column: 0,\n    totalColumns: 1,\n  };\n\n  const durationMinutes =\n    (dragState.currentEnd.getTime() - dragState.currentStart.getTime()) / 60000;\n  const heightPx = (durationMinutes / 60) * hourHeight;\n  const columnWidthPx =\n    (days.length > 0 ? gridWidth / days.length : 200) * 0.92;\n\n  return createPortal(\n    <div\n      aria-hidden\n      className=\"pointer-events-none\"\n      style={{\n        position: \"fixed\",\n        top: 0,\n        left: 0,\n        width: \"100vw\",\n        height: \"100vh\",\n        zIndex: 9999,\n      }}\n    >\n      <CalendarEventItem\n        key={`${dragState.eventId}-dragging`}\n        positionedEvent={floatingPositioned}\n        hourHeight={hourHeight}\n        dragVariant=\"dragging\"\n        overrideStart={dragState.currentStart}\n        overrideEnd={dragState.currentEnd}\n        cursorY={dragState.clientY}\n        cursorX={dragState.clientX}\n        fixedWidth={columnWidthPx}\n        fixedHeight={heightPx}\n      />\n    </div>,\n    document.body,\n  );\n}\n\ninterface DayEventsColumnProps extends EventItemPopoverProps {\n  columnDate: Date;\n  /** Accessible name: the column's full date */\n  label: string;\n  /**\n   * Whether the column is on screen. Off-screen scroll buffer columns are\n   * inert, so their events can't be tabbed to or read out.\n   */\n  isOnScreen: boolean;\n  events: ReturnType<typeof calculatePositionedEvents>;\n  hourHeight: number;\n  onEventClick?: (event: CalendarEvent) => void;\n  selectedEventId?: string;\n  dragState?: EventDragState;\n  onEventDragPointerDown?: WeekViewGridProps[\"onEventDragPointerDown\"];\n  resizeState?: EventResizeState;\n  onEventResizePointerDown?: WeekViewGridProps[\"onEventResizePointerDown\"];\n  onEventChange?: (event: CalendarEvent) => void;\n  onContextMenuOpenChange?: (open: boolean) => void;\n  onColumnPointerDownCapture?: () => void;\n  onColumnPointerDown?: (\n    e: React.PointerEvent<HTMLDivElement>,\n    columnDate: Date,\n  ) => void;\n  onColumnPointerMove?: (\n    e: React.PointerEvent<HTMLDivElement>,\n    columnDate: Date,\n  ) => void;\n  onColumnClick?: (\n    e: React.MouseEvent<HTMLDivElement>,\n    columnDate: Date,\n  ) => void;\n}\n\nfunction renderColumnGhost(\n  positionedEvent: PositionedEvent,\n  hourHeight: number,\n) {\n  return (\n    <CalendarEventItem\n      key={`${positionedEvent.event.id}-ghost`}\n      positionedEvent={positionedEvent}\n      hourHeight={hourHeight}\n      dragVariant=\"ghost\"\n    />\n  );\n}\n\nfunction DayEventsColumn({\n  columnDate,\n  label,\n  isOnScreen,\n  events,\n  hourHeight,\n  onEventClick,\n  selectedEventId,\n  dragState,\n  onEventDragPointerDown,\n  resizeState,\n  onEventResizePointerDown,\n  onEventChange,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  onColumnPointerDownCapture,\n  onColumnPointerDown,\n  onColumnPointerMove,\n  onColumnClick,\n}: DayEventsColumnProps) {\n  return (\n    <div\n      role=\"group\"\n      aria-label={label}\n      inert={!isOnScreen}\n      className=\"relative h-full pointer-events-auto\"\n      onPointerDownCapture={onColumnPointerDownCapture}\n      onPointerDown={(e) => onColumnPointerDown?.(e, columnDate)}\n      onPointerMove={(e) => onColumnPointerMove?.(e, columnDate)}\n      onClick={(e) => onColumnClick?.(e, columnDate)}\n    >\n      {events.map((positionedEvent) => {\n        const eventId = positionedEvent.event.id;\n        const isBeingDragged =\n          dragState?.isDragging && dragState.eventId === eventId;\n\n        if (isBeingDragged) {\n          return renderColumnGhost(positionedEvent, hourHeight);\n        }\n\n        const isBeingResized =\n          resizeState?.isResizing && resizeState.eventId === eventId;\n\n        if (isBeingResized) {\n          const { effectiveEdge, currentStartDate, currentEndDate } =\n            resizeState;\n          const isCrossDay = !isSameDay(currentStartDate, currentEndDate);\n\n          // Determine if this column is the anchor column\n          const isAnchorColumn =\n            (effectiveEdge === \"bottom\" &&\n              isSameDay(columnDate, currentStartDate)) ||\n            (effectiveEdge === \"top\" && isSameDay(columnDate, currentEndDate));\n\n          // Check if this column is within the new range at all\n          const colTime = columnDate.getTime();\n          const inRange =\n            colTime >= currentStartDate.getTime() &&\n            colTime <= currentEndDate.getTime();\n\n          // Non-anchor columns with original segments: render as ghost\n          // Columns outside new range with original segments: render as ghost\n          if (!isAnchorColumn || !inRange) {\n            return renderColumnGhost(positionedEvent, hourHeight);\n          }\n\n          // Anchor column rendering\n          let displayStart: Date;\n          let displayEnd: Date;\n          let segmentPosition: \"start\" | \"middle\" | \"end\" | \"full\";\n\n          if (!isCrossDay) {\n            // Same day: show currentStart to currentEnd\n            displayStart = resizeState.currentStart;\n            displayEnd = resizeState.currentEnd;\n            segmentPosition = \"full\";\n          } else if (effectiveEdge === \"bottom\") {\n            // Anchor is start column: show currentStart to end-of-day\n            displayStart = resizeState.currentStart;\n            displayEnd = addDays(startOfDay(columnDate), 1);\n            segmentPosition = \"start\";\n          } else {\n            // Anchor is end column: show start-of-day to currentEnd\n            displayStart = startOfDay(columnDate);\n            displayEnd = resizeState.currentEnd;\n            segmentPosition = \"end\";\n          }\n\n          const resizePositioned = { ...positionedEvent, segmentPosition };\n\n          return (\n            <React.Fragment key={eventId}>\n              {renderColumnGhost(positionedEvent, hourHeight)}\n              <CalendarEventItem\n                key={`${eventId}-resizing`}\n                positionedEvent={resizePositioned}\n                hourHeight={hourHeight}\n                isSelected={isCrossDay || eventId === selectedEventId}\n                isResizing\n                overrideStart={displayStart}\n                overrideEnd={displayEnd}\n                onEventChange={onEventChange}\n              />\n            </React.Fragment>\n          );\n        }\n\n        return (\n          <CalendarEventItem\n            key={eventId}\n            positionedEvent={positionedEvent}\n            hourHeight={hourHeight}\n            isSelected={eventId === selectedEventId}\n            onClick={onEventClick}\n            onDragPointerDown={onEventDragPointerDown}\n            onResizePointerDown={onEventResizePointerDown}\n            onEventChange={onEventChange}\n            onContextMenuOpenChange={onContextMenuOpenChange}\n            showEventPopover={showEventPopover}\n            onEventPopoverExpand={onEventPopoverExpand}\n            onEventPopoverClose={onEventPopoverClose}\n          />\n        );\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/week-view-time-axis.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport type { WeekViewTimeAxisProps } from \"./week-view-types\";\n\n/**\n * Column of hour labels beside the grid, using CSS Grid with the same rows\n * as the main grid for guaranteed alignment. One column (4rem), like the\n * time zone and all-day labels above it. `labels` replaces the slots' own\n * labels: the time grid draws a second axis for a second time zone.\n */\nexport function WeekViewTimeAxis({\n  hours,\n  hourHeight,\n  labels,\n  className,\n}: WeekViewTimeAxisProps) {\n  return (\n    // Hour labels are visual only: each event's label already reads its time\n    <div\n      aria-hidden\n      className={cn(\"grid w-16 flex-shrink-0\", className)}\n      style={{\n        gridTemplateRows: `repeat(${hours.length}, ${hourHeight}px)`,\n        gridTemplateColumns: \"1fr\",\n      }}\n    >\n      {hours.map((hourSlot, index) => {\n        const label = labels ? labels[index] : hourSlot.label;\n        return (\n          <div\n            key={hourSlot.hour}\n            className=\"text-muted-foreground relative pr-2 text-right text-xxs\"\n          >\n            {/* Show label at top of each cell, skip the first row (it would sit on the grid's top edge) */}\n            {index > 0 && label && (\n              <span className=\"absolute top-0 right-2 -translate-y-[55%] leading-none whitespace-nowrap\">\n                {label}\n              </span>\n            )}\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/week-view-time-indicator.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useNow } from \"@/hooks/use-now\";\nimport { formatNowLineTime } from \"@/lib/event-utils\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport type { WeekViewTimeIndicatorProps } from \"./week-view-types\";\n\n/** Width of the badge column in pixels (4rem), the viewer's column of the time axis */\nconst BADGE_COLUMN_WIDTH = 64;\n\n/**\n * Current time indicator showing time badge and horizontal lines\n * - Time badge with current time (e.g., \"5:48PM\", or \"17:48\" on a 24-hour clock) on the left\n * - With a second time zone, still one badge: in the viewer's column, the one next to the days\n * - Thick line on today's column\n * - Thin line on other day columns\n * Moves on every minute boundary via the shared `useNow` clock. Renders\n * nothing on the server and during hydration, where the time is unknown,\n * and outside the visible hours (`dayStartHour` to `dayEndHour`).\n */\nexport function WeekViewTimeIndicator({\n  days,\n  hourHeight,\n  scrollDays,\n  scrollStyle,\n  behindSelection,\n  timeAxisWidth = BADGE_COLUMN_WIDTH,\n  className,\n}: WeekViewTimeIndicatorProps) {\n  const currentTime = useNow();\n  const { dayStartHour, dayEndHour, hourCycle, locale } = useCalendarConfig();\n\n  // Check if today is visible in the current week\n  const isTodayVisible = days.some((day) => day.isToday);\n\n  if (!currentTime || !isTodayVisible) {\n    return null;\n  }\n\n  // Calculate position based on current time, from the grid's top edge\n  const minutesSinceMidnight =\n    currentTime.getHours() * 60 + currentTime.getMinutes();\n  const visibleStartMinutes = dayStartHour * 60;\n  if (\n    minutesSinceMidnight < visibleStartMinutes ||\n    minutesSinceMidnight >= dayEndHour * 60\n  ) {\n    return null;\n  }\n  const topPosition =\n    ((minutesSinceMidnight - visibleStartMinutes) / 60) * hourHeight;\n\n  // \"5:48PM\" on a 12-hour clock, \"17:48\" on a 24-hour clock\n  const formattedTime = formatNowLineTime(\n    minutesSinceMidnight,\n    hourCycle,\n    locale,\n  );\n\n  const lineDays = scrollDays ?? days;\n  const lineTodayIndex = lineDays.findIndex((d) => d.isToday);\n\n  const linesContent = (\n    <div className=\"flex items-center\">\n      {lineDays.map((day, index) => (\n        <React.Fragment key={day.date.toISOString()}>\n          {index === lineTodayIndex && (\n            <div className=\"relative flex-shrink-0\">\n              <div className=\"bg-primary h-3 w-[3px] translate-y-[0.5px] rounded-full shadow-[0_0_0_1px_white] dark:shadow-[0_0_0_1px_black]\" />\n              <div className=\"absolute top-[6.5px] left-[2px] bg-primary h-[1px] w-[2px] z-10\" />\n              <div className=\"absolute top-[5.5px] left-[2px] bg-primary h-[1px] w-[2px] z-10\" />\n              <div className=\"absolute top-[4.5px] left-[2px] bg-primary h-[1px] w-[2px] z-10\" />\n            </div>\n          )}\n          <div\n            className={cn(\n              \"flex-1 bg-primary\",\n              day.isToday\n                ? \"h-[3px] rounded-r-full shadow-[0_0_0_1px_white] dark:shadow-[0_0_0_1px_black]\"\n                : \"h-[0.5px]\",\n            )}\n          />\n        </React.Fragment>\n      ))}\n    </div>\n  );\n\n  return (\n    <div\n      aria-hidden\n      className={cn(\n        \"pointer-events-none absolute left-0 right-0\",\n        behindSelection ? \"z-10\" : \"z-20\",\n        className,\n      )}\n      style={{ top: topPosition }}\n    >\n      <div className=\"flex -translate-y-1/2 items-center\">\n        {/* Room for a second time zone's column, which has no badge */}\n        {timeAxisWidth > BADGE_COLUMN_WIDTH && (\n          <div\n            className=\"flex-shrink-0\"\n            style={{ width: timeAxisWidth - BADGE_COLUMN_WIDTH }}\n          />\n        )}\n        {/* Time badge - positioned in the viewer's column of the time axis */}\n        <div className=\"flex w-16 flex-shrink-0 items-center justify-end pr-1\">\n          <span className=\"bg-primary text-primary-foreground rounded-xs px-1 py-0.5 text-xxs font-medium\">\n            {formattedTime}\n          </span>\n        </div>\n\n        {/* Horizontal lines across day columns */}\n        {scrollStyle ? (\n          <div className=\"min-w-0 flex-1 overflow-clip\">\n            <div style={scrollStyle}>{linesContent}</div>\n          </div>\n        ) : (\n          linesContent\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/hooks/use-all-day-resize.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { addDays } from \"date-fns\";\n\nimport {\n  isPrimaryPress,\n  suppressNextClick,\n  usePointerGesture,\n} from \"@/hooks/use-pointer-gesture\";\nimport type {\n  AllDayResizeState,\n  CalendarEvent,\n  PointerGestureStart,\n} from \"@/components/week-view-types\";\n\ninterface UseAllDayResizeOptions {\n  days: Date[];\n  dayColumnWidth: number;\n  allDayContainerRef: React.RefObject<HTMLDivElement | null>;\n  events: CalendarEvent[];\n  onEventChange?: (event: CalendarEvent) => void;\n  onEventClick?: (event: CalendarEvent) => void;\n}\n\ninterface UseAllDayResizeReturn {\n  allDayResizeState: AllDayResizeState | null;\n  handleAllDayResizePointerDown: (\n    e: React.PointerEvent<HTMLElement>,\n    event: CalendarEvent,\n    edge: \"left\" | \"right\" | \"move\",\n    startColumn: number,\n    endColumn: number,\n  ) => void;\n}\n\nconst DRAG_THRESHOLD_PX = 4;\n\nfunction clamp(value: number, min: number, max: number): number {\n  if (value < min) return min;\n  if (value > max) return max;\n  return value;\n}\n\n/** `day` at the time of day of `time` */\nfunction atTimeOf(day: Date, time: Date): Date {\n  const result = new Date(day);\n  result.setHours(\n    time.getHours(),\n    time.getMinutes(),\n    time.getSeconds(),\n    time.getMilliseconds(),\n  );\n  return result;\n}\n\ninterface ResizeInfo {\n  eventId: string;\n  event: CalendarEvent;\n  /** Pointer driving the gesture; moves from other pointers are ignored */\n  pointerId: number;\n  /** \"mouse\", \"pen\" or \"touch\" */\n  pointerType: string;\n  edge: \"left\" | \"right\" | \"move\";\n  startClientX: number;\n  isResizing: boolean;\n  originalStartColumn: number;\n  originalEndColumn: number;\n  /** Column index where the gesture started (used for move delta) */\n  startColumnIndex: number;\n  /** Offset from cursor to event left edge when the gesture started (px) */\n  cursorOffsetX: number;\n  /** Offset from cursor to event top edge when the gesture started (px) */\n  cursorOffsetY: number;\n  /** Latest start column, committed to the parent on pointerup */\n  currentStartColumn: number;\n  /** Latest end column, committed to the parent on pointerup */\n  currentEndColumn: number;\n}\n\nexport function useAllDayResize({\n  days,\n  dayColumnWidth,\n  allDayContainerRef,\n  events,\n  onEventChange,\n  onEventClick,\n}: UseAllDayResizeOptions): UseAllDayResizeReturn {\n  const [allDayResizeState, setAllDayResizeState] =\n    useState<AllDayResizeState | null>(null);\n  const { startGesture } = usePointerGesture({\n    containerRef: allDayContainerRef,\n  });\n\n  const resizeRef = useRef<ResizeInfo | null>(null);\n  const onEventChangeRef = useRef(onEventChange);\n  const onEventClickRef = useRef(onEventClick);\n  const eventsRef = useRef(events);\n  const daysRef = useRef(days);\n  const dayColumnWidthRef = useRef(dayColumnWidth);\n\n  useEffect(() => {\n    onEventChangeRef.current = onEventChange;\n  }, [onEventChange]);\n  useEffect(() => {\n    onEventClickRef.current = onEventClick;\n  }, [onEventClick]);\n  useEffect(() => {\n    eventsRef.current = events;\n  }, [events]);\n  useEffect(() => {\n    daysRef.current = days;\n  }, [days]);\n  useEffect(() => {\n    dayColumnWidthRef.current = dayColumnWidth;\n  }, [dayColumnWidth]);\n\n  const handlePointerMoveRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerUpRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerCancelRef = useRef<((e: PointerEvent) => void) | null>(\n    null,\n  );\n\n  const cleanup = useCallback(() => {\n    if (handlePointerMoveRef.current) {\n      window.removeEventListener(\"pointermove\", handlePointerMoveRef.current);\n    }\n    if (handlePointerUpRef.current) {\n      window.removeEventListener(\"pointerup\", handlePointerUpRef.current);\n    }\n    if (handlePointerCancelRef.current) {\n      window.removeEventListener(\n        \"pointercancel\",\n        handlePointerCancelRef.current,\n      );\n    }\n    document.body.style.removeProperty(\"--cursor\");\n  }, []);\n\n  useEffect(() => {\n    handlePointerMoveRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      const deltaX = Math.abs(e.clientX - resize.startClientX);\n      if (!resize.isResizing && deltaX < DRAG_THRESHOLD_PX) return;\n\n      if (!resize.isResizing) {\n        resize.isResizing = true;\n        document.body.style.setProperty(\n          \"--cursor\",\n          resize.edge === \"move\" ? \"grabbing\" : \"col-resize\",\n        );\n      }\n\n      const container = allDayContainerRef.current;\n      if (!container) return;\n\n      const rect = container.getBoundingClientRect();\n      const colWidth = dayColumnWidthRef.current;\n      const currentDays = daysRef.current;\n      const columnIndex = clamp(\n        Math.floor((e.clientX - rect.left) / colWidth),\n        0,\n        currentDays.length - 1,\n      );\n\n      let newStartColumn = resize.originalStartColumn;\n      let newEndColumn = resize.originalEndColumn;\n\n      if (resize.edge === \"move\") {\n        const span = resize.originalEndColumn - resize.originalStartColumn;\n        const delta = columnIndex - resize.startColumnIndex;\n        newStartColumn = clamp(\n          resize.originalStartColumn + delta,\n          0,\n          currentDays.length - 1 - span,\n        );\n        newEndColumn = newStartColumn + span;\n      } else if (resize.edge === \"right\") {\n        newEndColumn = Math.max(columnIndex, resize.originalStartColumn);\n      } else {\n        newStartColumn = Math.min(columnIndex, resize.originalEndColumn);\n      }\n\n      resize.currentStartColumn = newStartColumn;\n      resize.currentEndColumn = newEndColumn;\n\n      setAllDayResizeState({\n        eventId: resize.eventId,\n        event: resize.event,\n        originalStartColumn: resize.originalStartColumn,\n        originalEndColumn: resize.originalEndColumn,\n        currentStartColumn: newStartColumn,\n        currentEndColumn: newEndColumn,\n        edge: resize.edge,\n        isResizing: true,\n        ...(resize.edge === \"move\"\n          ? {\n              clientX: e.clientX,\n              clientY: e.clientY,\n              cursorOffsetX: resize.cursorOffsetX,\n              cursorOffsetY: resize.cursorOffsetY,\n            }\n          : {}),\n      });\n    };\n\n    handlePointerUpRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      cleanup();\n      resizeRef.current = null;\n      setAllDayResizeState(null);\n\n      // Touch selects on release, after the gesture, rather than on press\n      if (resize.pointerType === \"touch\") {\n        onEventClickRef.current?.(resize.event);\n      }\n      if (!resize.isResizing) return;\n      // A move swaps the pressed bar for a ghost, so the browser's click\n      // lands on the row and would clear the selection\n      suppressNextClick(resize.pointerType);\n\n      // Commit from the handler, never from inside a state updater:\n      // updaters run during render, and calling the parent's setState\n      // there triggers \"Cannot update a component while rendering\".\n      // A repeating event's generated occurrence isn't in `events`: commit\n      // the copy the gesture started with\n      const event =\n        eventsRef.current.find((e) => e.id === resize.eventId) ?? resize.event;\n\n      // The columns are clipped to the rendered days, so they only say\n      // which edge moved and how far. An edge that did not move keeps the\n      // event's own date.\n      const startMoved =\n        resize.currentStartColumn !== resize.originalStartColumn;\n      const endMoved = resize.currentEndColumn !== resize.originalEndColumn;\n      if (!startMoved && !endMoved) return;\n\n      let newStart = event.start;\n      let newEnd = event.end;\n\n      if (resize.edge === \"move\") {\n        const daysMoved =\n          resize.currentStartColumn - resize.originalStartColumn;\n        newStart = addDays(event.start, daysMoved);\n        newEnd = addDays(event.end, daysMoved);\n      } else {\n        const currentDays = daysRef.current;\n        const startDay = currentDays[resize.currentStartColumn];\n        const endDay = currentDays[resize.currentEndColumn];\n        if (!startDay || !endDay) return;\n        if (startMoved) newStart = atTimeOf(startDay, event.start);\n        if (endMoved) newEnd = atTimeOf(endDay, event.end);\n      }\n\n      // A timed event keeps its times of day, so an edge can land on a day\n      // where the end would not be after the start\n      if (!event.isAllDay && newEnd.getTime() <= newStart.getTime()) return;\n\n      // The event keeps its own isAllDay: its length never decides it\n      onEventChangeRef.current?.({ ...event, start: newStart, end: newEnd });\n    };\n\n    // The browser took the pointer over (e.g. for a system gesture): drop\n    // the gesture without committing it\n    handlePointerCancelRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      cleanup();\n      resizeRef.current = null;\n      setAllDayResizeState(null);\n    };\n  }, [allDayContainerRef, cleanup]);\n\n  const beginResize = useCallback(\n    (\n      { clientX, pointerId, pointerType }: PointerGestureStart,\n      event: CalendarEvent,\n      edge: \"left\" | \"right\" | \"move\",\n      startColumn: number,\n      endColumn: number,\n    ) => {\n      // Mouse and pen select the event immediately\n      if (pointerType !== \"touch\") onEventClickRef.current?.(event);\n\n      // Compute the column under the cursor at the start for move delta\n      const container = allDayContainerRef.current;\n      let startColumnIndex = startColumn;\n      let cursorOffsetX = 0;\n      const cursorOffsetY = 0;\n      if (container) {\n        const rect = container.getBoundingClientRect();\n        const colWidth = dayColumnWidthRef.current;\n        startColumnIndex = clamp(\n          Math.floor((clientX - rect.left) / colWidth),\n          0,\n          daysRef.current.length - 1,\n        );\n        // Compute offset from cursor to the event element's top-left\n        const eventLeft = rect.left + startColumn * colWidth;\n        cursorOffsetX = clientX - eventLeft;\n      }\n\n      resizeRef.current = {\n        eventId: event.id,\n        event,\n        pointerId,\n        pointerType,\n        edge,\n        startClientX: clientX,\n        isResizing: false,\n        originalStartColumn: startColumn,\n        originalEndColumn: endColumn,\n        startColumnIndex,\n        cursorOffsetX,\n        cursorOffsetY,\n        currentStartColumn: startColumn,\n        currentEndColumn: endColumn,\n      };\n\n      setAllDayResizeState({\n        eventId: event.id,\n        event,\n        originalStartColumn: startColumn,\n        originalEndColumn: endColumn,\n        currentStartColumn: startColumn,\n        currentEndColumn: endColumn,\n        edge,\n        isResizing: false,\n      });\n\n      if (handlePointerMoveRef.current) {\n        window.addEventListener(\"pointermove\", handlePointerMoveRef.current);\n      }\n      if (handlePointerUpRef.current) {\n        window.addEventListener(\"pointerup\", handlePointerUpRef.current);\n      }\n      if (handlePointerCancelRef.current) {\n        window.addEventListener(\n          \"pointercancel\",\n          handlePointerCancelRef.current,\n        );\n      }\n    },\n    [allDayContainerRef],\n  );\n\n  const handleAllDayResizePointerDown = useCallback(\n    (\n      e: React.PointerEvent<HTMLElement>,\n      event: CalendarEvent,\n      edge: \"left\" | \"right\" | \"move\",\n      startColumn: number,\n      endColumn: number,\n    ) => {\n      if (!isPrimaryPress(e)) return;\n      e.stopPropagation();\n      startGesture(e, (start) =>\n        beginResize(start, event, edge, startColumn, endColumn),\n      );\n    },\n    [startGesture, beginResize],\n  );\n\n  useEffect(() => {\n    return cleanup;\n  }, [cleanup]);\n\n  return { allDayResizeState, handleAllDayResizePointerDown };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-event-drag.ts",
      "content": "\"use client\";\n\nimport { isSameDay } from \"date-fns\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n  usePointerGesture,\n  suppressNextClick,\n} from \"@/hooks/use-pointer-gesture\";\nimport { snapToGrid } from \"@/lib/event-utils\";\nimport type {\n  CalendarEvent,\n  EventDragState,\n  PointerGestureStart,\n} from \"@/components/week-view-types\";\n\ninterface UseEventDragOptions {\n  hourHeight: number;\n  scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n  events: CalendarEvent[];\n  days: Date[];\n  dayColumnWidth: number;\n  timeAxisWidth: number;\n  /** Minute step the dragged start snaps to */\n  snapMinutes: number;\n  /** First visible hour: the top of the grid, and the earliest start */\n  dayStartHour: number;\n  /** Hour the grid ends at: the latest end */\n  dayEndHour: number;\n  /** Days `onDragNavigate` moves when the cursor is held at a side edge */\n  edgeNavigationDays: number;\n  onEventChange?: (event: CalendarEvent) => void;\n  onEventClick?: (event: CalendarEvent) => void;\n  onDragNavigate?: (daysDelta: number) => void;\n}\n\ninterface UseEventDragReturn {\n  dragState: EventDragState | null;\n  handleEventPointerDown: (\n    e: React.PointerEvent<HTMLElement>,\n    event: CalendarEvent,\n  ) => void;\n}\n\nconst DRAG_THRESHOLD_PX = 4;\nconst EDGE_ZONE_PX = 40;\nconst EDGE_NAV_DELAY_MS = 500;\nconst EDGE_NAV_REPEAT_MS = 800;\nconst AUTO_SCROLL_ZONE_PX = 60;\nconst AUTO_SCROLL_MAX_SPEED = 12;\n\nfunction addMinutesToDate(date: Date, minutes: number): Date {\n  const result = new Date(date);\n  result.setHours(0, 0, 0, 0);\n  result.setMinutes(minutes);\n  return result;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n  if (value < min) return min;\n  if (value > max) return max;\n  return value;\n}\n\ninterface DragInfo {\n  eventId: string;\n  event: CalendarEvent;\n  /** Pointer driving the drag; moves from other pointers are ignored */\n  pointerId: number;\n  /** \"mouse\", \"pen\" or \"touch\" */\n  pointerType: string;\n  startClientY: number;\n  startClientX: number;\n  offsetWithinEvent: number;\n  offsetWithinEventX: number;\n  isDragging: boolean;\n  durationMinutes: number;\n  /** Latest snapped start, committed to the parent on pointerup */\n  currentStart: Date;\n  /** Latest snapped end, committed to the parent on pointerup */\n  currentEnd: Date;\n}\n\nexport function useEventDrag({\n  hourHeight,\n  scrollContainerRef,\n  events,\n  days,\n  dayColumnWidth,\n  timeAxisWidth,\n  snapMinutes,\n  dayStartHour,\n  dayEndHour,\n  edgeNavigationDays,\n  onEventChange,\n  onEventClick,\n  onDragNavigate,\n}: UseEventDragOptions): UseEventDragReturn {\n  const [dragState, setDragState] = useState<EventDragState | null>(null);\n  const { startGesture } = usePointerGesture({\n    containerRef: scrollContainerRef,\n  });\n\n  const dragRef = useRef<DragInfo | null>(null);\n  const onEventChangeRef = useRef(onEventChange);\n  const onEventClickRef = useRef(onEventClick);\n  const onDragNavigateRef = useRef(onDragNavigate);\n  const eventsRef = useRef(events);\n  const hourHeightRef = useRef(hourHeight);\n  const daysRef = useRef(days);\n  const dayColumnWidthRef = useRef(dayColumnWidth);\n  const timeAxisWidthRef = useRef(timeAxisWidth);\n  const snapMinutesRef = useRef(snapMinutes);\n  const dayStartHourRef = useRef(dayStartHour);\n  const dayEndHourRef = useRef(dayEndHour);\n  const edgeNavigationDaysRef = useRef(edgeNavigationDays);\n\n  useEffect(() => {\n    onEventChangeRef.current = onEventChange;\n  }, [onEventChange]);\n  useEffect(() => {\n    onEventClickRef.current = onEventClick;\n  }, [onEventClick]);\n  useEffect(() => {\n    onDragNavigateRef.current = onDragNavigate;\n  }, [onDragNavigate]);\n  useEffect(() => {\n    eventsRef.current = events;\n  }, [events]);\n  useEffect(() => {\n    hourHeightRef.current = hourHeight;\n  }, [hourHeight]);\n  useEffect(() => {\n    daysRef.current = days;\n  }, [days]);\n  useEffect(() => {\n    dayColumnWidthRef.current = dayColumnWidth;\n  }, [dayColumnWidth]);\n  useEffect(() => {\n    timeAxisWidthRef.current = timeAxisWidth;\n  }, [timeAxisWidth]);\n  useEffect(() => {\n    snapMinutesRef.current = snapMinutes;\n  }, [snapMinutes]);\n  useEffect(() => {\n    dayStartHourRef.current = dayStartHour;\n  }, [dayStartHour]);\n  useEffect(() => {\n    dayEndHourRef.current = dayEndHour;\n  }, [dayEndHour]);\n  useEffect(() => {\n    edgeNavigationDaysRef.current = edgeNavigationDays;\n  }, [edgeNavigationDays]);\n\n  // Edge navigation timer refs\n  const edgeNavTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const edgeNavDirectionRef = useRef<number | null>(null);\n\n  // Auto-scroll RAF ref\n  const autoScrollRAFRef = useRef<number | null>(null);\n  const autoScrollSpeedRef = useRef(0);\n\n  // Store handlers in refs to break the circular dependency\n  const handlePointerMoveRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerUpRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerCancelRef = useRef<((e: PointerEvent) => void) | null>(\n    null,\n  );\n\n  const cancelEdgeNav = useCallback(() => {\n    if (edgeNavTimerRef.current !== null) {\n      clearTimeout(edgeNavTimerRef.current);\n      edgeNavTimerRef.current = null;\n    }\n    edgeNavDirectionRef.current = null;\n  }, []);\n\n  const cancelAutoScroll = useCallback(() => {\n    if (autoScrollRAFRef.current !== null) {\n      cancelAnimationFrame(autoScrollRAFRef.current);\n      autoScrollRAFRef.current = null;\n    }\n    autoScrollSpeedRef.current = 0;\n  }, []);\n\n  const cleanup = useCallback(() => {\n    if (handlePointerMoveRef.current) {\n      window.removeEventListener(\"pointermove\", handlePointerMoveRef.current);\n    }\n    if (handlePointerUpRef.current) {\n      window.removeEventListener(\"pointerup\", handlePointerUpRef.current);\n    }\n    if (handlePointerCancelRef.current) {\n      window.removeEventListener(\n        \"pointercancel\",\n        handlePointerCancelRef.current,\n      );\n    }\n    cancelEdgeNav();\n    cancelAutoScroll();\n  }, [cancelEdgeNav, cancelAutoScroll]);\n\n  // Auto-scroll loop\n  const startAutoScrollLoop = useCallback(() => {\n    if (autoScrollRAFRef.current !== null) return;\n\n    const tick = () => {\n      const container = scrollContainerRef.current;\n      if (!container) return;\n\n      const speed = autoScrollSpeedRef.current;\n      if (speed === 0) {\n        autoScrollRAFRef.current = null;\n        return;\n      }\n\n      container.scrollTop += speed;\n      autoScrollRAFRef.current = requestAnimationFrame(tick);\n    };\n\n    autoScrollRAFRef.current = requestAnimationFrame(tick);\n  }, [scrollContainerRef]);\n\n  const scheduleEdgeNav = useCallback(\n    (direction: number) => {\n      if (edgeNavDirectionRef.current === direction) return;\n\n      cancelEdgeNav();\n      edgeNavDirectionRef.current = direction;\n\n      const fireNav = () => {\n        onDragNavigateRef.current?.(direction);\n        edgeNavTimerRef.current = setTimeout(fireNav, EDGE_NAV_REPEAT_MS);\n      };\n\n      edgeNavTimerRef.current = setTimeout(fireNav, EDGE_NAV_DELAY_MS);\n    },\n    [cancelEdgeNav],\n  );\n\n  // Initialize the handlers once (stable references via refs)\n  useEffect(() => {\n    handlePointerMoveRef.current = (e: PointerEvent) => {\n      const drag = dragRef.current;\n      if (!drag || e.pointerId !== drag.pointerId) return;\n\n      const deltaY = Math.abs(e.clientY - drag.startClientY);\n      const deltaX = Math.abs(e.clientX - drag.startClientX);\n      if (\n        !drag.isDragging &&\n        deltaY < DRAG_THRESHOLD_PX &&\n        deltaX < DRAG_THRESHOLD_PX\n      )\n        return;\n\n      if (!drag.isDragging) {\n        drag.isDragging = true;\n      }\n\n      const container = scrollContainerRef.current;\n      if (!container) return;\n\n      const containerRect = container.getBoundingClientRect();\n      const scrollTop = container.scrollTop;\n      const absoluteY =\n        e.clientY - containerRect.top + scrollTop - drag.offsetWithinEvent;\n      const absoluteX =\n        e.clientX - containerRect.left - drag.offsetWithinEventX;\n      // The grid's top edge is `dayStartHour`, not midnight\n      const visibleStartMinutes = dayStartHourRef.current * 60;\n      const visibleEndMinutes = dayEndHourRef.current * 60;\n      const rawMinutes =\n        visibleStartMinutes + (absoluteY / hourHeightRef.current) * 60;\n      const snappedStartMinutes = snapToGrid(\n        rawMinutes,\n        snapMinutesRef.current,\n      );\n      const clampedStart = Math.max(\n        visibleStartMinutes,\n        Math.min(snappedStartMinutes, visibleEndMinutes - drag.durationMinutes),\n      );\n\n      // Column detection — based on raw cursor position over the grid\n      const colWidth = dayColumnWidthRef.current;\n      const visibleDays = daysRef.current;\n      const gridLeftEdge = containerRect.left + timeAxisWidthRef.current;\n      const cursorInGrid = e.clientX - gridLeftEdge;\n      const columnIndex = clamp(\n        Math.floor(cursorInGrid / colWidth),\n        0,\n        visibleDays.length - 1,\n      );\n      const targetDay = visibleDays[columnIndex];\n\n      const currentStart = addMinutesToDate(targetDay, clampedStart);\n      const currentEnd = addMinutesToDate(\n        targetDay,\n        clampedStart + drag.durationMinutes,\n      );\n\n      drag.currentStart = currentStart;\n      drag.currentEnd = currentEnd;\n\n      setDragState({\n        eventId: drag.eventId,\n        event: drag.event,\n        originalStart: drag.event.start,\n        originalEnd: drag.event.end,\n        currentStart,\n        currentEnd,\n        currentDate: targetDay,\n        isDragging: true,\n        cursorY: absoluteY,\n        cursorX: absoluteX,\n        clientX: e.clientX - drag.offsetWithinEventX,\n        clientY: e.clientY - drag.offsetWithinEvent,\n      });\n\n      // Edge-of-view week navigation\n      // Trigger when cursor is within EDGE_ZONE_PX of the grid boundary OR past it\n      const cursorXInGrid = e.clientX - gridLeftEdge;\n      const gridWidth = colWidth * visibleDays.length;\n\n      if (cursorXInGrid < EDGE_ZONE_PX) {\n        scheduleEdgeNav(-edgeNavigationDaysRef.current);\n      } else if (cursorXInGrid > gridWidth - EDGE_ZONE_PX) {\n        scheduleEdgeNav(edgeNavigationDaysRef.current);\n      } else {\n        cancelEdgeNav();\n      }\n\n      // Auto-scroll at top/bottom edges\n      const cursorYInContainer = e.clientY - containerRect.top;\n      const containerHeight = containerRect.height;\n\n      if (cursorYInContainer < AUTO_SCROLL_ZONE_PX) {\n        const dist = cursorYInContainer;\n        autoScrollSpeedRef.current =\n          -AUTO_SCROLL_MAX_SPEED * (1 - dist / AUTO_SCROLL_ZONE_PX);\n        startAutoScrollLoop();\n      } else if (cursorYInContainer > containerHeight - AUTO_SCROLL_ZONE_PX) {\n        const dist = containerHeight - cursorYInContainer;\n        autoScrollSpeedRef.current =\n          AUTO_SCROLL_MAX_SPEED * (1 - dist / AUTO_SCROLL_ZONE_PX);\n        startAutoScrollLoop();\n      } else {\n        cancelAutoScroll();\n      }\n    };\n\n    handlePointerUpRef.current = (e: PointerEvent) => {\n      const drag = dragRef.current;\n      if (!drag || e.pointerId !== drag.pointerId) return;\n\n      cleanup();\n      dragRef.current = null;\n      setDragState(null);\n\n      // Touch selects on release, after the drag, rather than on press\n      if (drag.pointerType === \"touch\") onEventClickRef.current?.(drag.event);\n      if (!drag.isDragging) return;\n      suppressNextClick(drag.pointerType);\n\n      // Commit from the handler, never from inside a state updater:\n      // updaters run during render, and calling the parent's setState\n      // there triggers \"Cannot update a component while rendering\".\n      // A repeating event's generated occurrence isn't in `events`: commit\n      // the copy the gesture started with\n      const event =\n        eventsRef.current.find((e) => e.id === drag.eventId) ?? drag.event;\n\n      onEventChangeRef.current?.({\n        ...event,\n        start: drag.currentStart,\n        end: drag.currentEnd,\n      });\n    };\n\n    // The browser took the pointer over (e.g. for a system gesture): drop\n    // the drag without committing it\n    handlePointerCancelRef.current = (e: PointerEvent) => {\n      const drag = dragRef.current;\n      if (!drag || e.pointerId !== drag.pointerId) return;\n\n      cleanup();\n      dragRef.current = null;\n      setDragState(null);\n    };\n  }, [\n    scrollContainerRef,\n    cleanup,\n    scheduleEdgeNav,\n    cancelEdgeNav,\n    cancelAutoScroll,\n    startAutoScrollLoop,\n  ]);\n\n  const beginDrag = useCallback(\n    (\n      {\n        clientX,\n        clientY,\n        pointerId,\n        pointerType,\n        element,\n      }: PointerGestureStart,\n      event: CalendarEvent,\n    ) => {\n      // Mouse and pen select the event immediately\n      if (pointerType !== \"touch\") onEventClickRef.current?.(event);\n\n      const container = scrollContainerRef.current;\n      if (!container) return;\n\n      // Compute offset within the event element\n      const targetRect = element.getBoundingClientRect();\n      const offsetWithinEvent = clientY - targetRect.top;\n      const offsetWithinEventX = clientX - targetRect.left;\n\n      const startMinutes =\n        event.start.getHours() * 60 + event.start.getMinutes();\n      // An end at the next midnight is minute 1440 of the event's day, not 0\n      const endMinutes = isSameDay(event.start, event.end)\n        ? event.end.getHours() * 60 + event.end.getMinutes()\n        : 1440;\n      const durationMinutes = endMinutes - startMinutes;\n\n      dragRef.current = {\n        eventId: event.id,\n        event,\n        pointerId,\n        pointerType,\n        startClientY: clientY,\n        startClientX: clientX,\n        offsetWithinEvent,\n        offsetWithinEventX,\n        isDragging: false,\n        durationMinutes,\n        currentStart: event.start,\n        currentEnd: event.end,\n      };\n\n      setDragState({\n        eventId: event.id,\n        event,\n        originalStart: event.start,\n        originalEnd: event.end,\n        currentStart: event.start,\n        currentEnd: event.end,\n        currentDate: event.start,\n        isDragging: false,\n        cursorY: 0,\n        cursorX: 0,\n        clientX: 0,\n        clientY: 0,\n      });\n\n      if (handlePointerMoveRef.current) {\n        window.addEventListener(\"pointermove\", handlePointerMoveRef.current);\n      }\n      if (handlePointerUpRef.current) {\n        window.addEventListener(\"pointerup\", handlePointerUpRef.current);\n      }\n      if (handlePointerCancelRef.current) {\n        window.addEventListener(\n          \"pointercancel\",\n          handlePointerCancelRef.current,\n        );\n      }\n    },\n    [scrollContainerRef],\n  );\n\n  const handleEventPointerDown = useCallback(\n    (e: React.PointerEvent<HTMLElement>, event: CalendarEvent) => {\n      startGesture(e, (start) => beginDrag(start, event));\n    },\n    [startGesture, beginDrag],\n  );\n\n  // Cleanup on unmount\n  useEffect(() => {\n    return cleanup;\n  }, [cleanup]);\n\n  return { dragState, handleEventPointerDown };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-event-resize.ts",
      "content": "\"use client\";\n\nimport { isSameDay, startOfDay, subDays } from \"date-fns\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n  isPrimaryPress,\n  suppressNextClick,\n  usePointerGesture,\n} from \"@/hooks/use-pointer-gesture\";\nimport { snapToGrid } from \"@/lib/event-utils\";\nimport type {\n  CalendarEvent,\n  EventResizeState,\n  PointerGestureStart,\n} from \"@/components/week-view-types\";\n\ninterface UseEventResizeOptions {\n  hourHeight: number;\n  scrollContainerRef: React.RefObject<HTMLDivElement | null>;\n  events: CalendarEvent[];\n  days: Date[];\n  dayColumnWidth: number;\n  timeAxisWidth: number;\n  /** Minute step the dragged edge snaps to, and the shortest duration */\n  snapMinutes: number;\n  /** First visible hour: the top of the grid, and the earliest start */\n  dayStartHour: number;\n  /** Hour the grid ends at: the latest end */\n  dayEndHour: number;\n  /** Days `onResizeNavigate` moves when the cursor is held at a side edge */\n  edgeNavigationDays: number;\n  onEventChange?: (event: CalendarEvent) => void;\n  onEventClick?: (event: CalendarEvent) => void;\n  onResizeNavigate?: (daysDelta: number) => void;\n}\n\ninterface UseEventResizeReturn {\n  resizeState: EventResizeState | null;\n  handleResizePointerDown: (\n    e: React.PointerEvent<HTMLElement>,\n    event: CalendarEvent,\n    edge: \"top\" | \"bottom\",\n  ) => void;\n}\n\nconst DRAG_THRESHOLD_PX = 4;\nconst AUTO_SCROLL_ZONE_PX = 60;\nconst AUTO_SCROLL_MAX_SPEED = 12;\nconst EDGE_ZONE_PX = 40;\nconst EDGE_NAV_DELAY_MS = 500;\nconst EDGE_NAV_REPEAT_MS = 800;\n\nfunction addMinutesToDate(date: Date, minutes: number): Date {\n  const result = new Date(date);\n  result.setHours(0, 0, 0, 0);\n  result.setMinutes(minutes);\n  return result;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n  if (value < min) return min;\n  if (value > max) return max;\n  return value;\n}\n\ninterface ResizeInfo {\n  eventId: string;\n  event: CalendarEvent;\n  /** Pointer driving the resize; moves from other pointers are ignored */\n  pointerId: number;\n  /** \"mouse\", \"pen\" or \"touch\" */\n  pointerType: string;\n  edge: \"top\" | \"bottom\";\n  startClientY: number;\n  isResizing: boolean;\n  originalStartMinutes: number;\n  originalEndMinutes: number;\n  originalStartDate: Date;\n  originalEndDate: Date;\n  /** Latest snapped start, committed to the parent on pointerup */\n  currentStart: Date;\n  /** Latest snapped end, committed to the parent on pointerup */\n  currentEnd: Date;\n}\n\nexport function useEventResize({\n  hourHeight,\n  scrollContainerRef,\n  events,\n  days,\n  dayColumnWidth,\n  timeAxisWidth,\n  snapMinutes,\n  dayStartHour,\n  dayEndHour,\n  edgeNavigationDays,\n  onEventChange,\n  onEventClick,\n  onResizeNavigate,\n}: UseEventResizeOptions): UseEventResizeReturn {\n  const [resizeState, setResizeState] = useState<EventResizeState | null>(null);\n  const { startGesture } = usePointerGesture({\n    containerRef: scrollContainerRef,\n  });\n\n  const resizeRef = useRef<ResizeInfo | null>(null);\n  const onEventChangeRef = useRef(onEventChange);\n  const onEventClickRef = useRef(onEventClick);\n  const onResizeNavigateRef = useRef(onResizeNavigate);\n  const eventsRef = useRef(events);\n  const hourHeightRef = useRef(hourHeight);\n  const daysRef = useRef(days);\n  const dayColumnWidthRef = useRef(dayColumnWidth);\n  const timeAxisWidthRef = useRef(timeAxisWidth);\n  const snapMinutesRef = useRef(snapMinutes);\n  const dayStartHourRef = useRef(dayStartHour);\n  const dayEndHourRef = useRef(dayEndHour);\n  const edgeNavigationDaysRef = useRef(edgeNavigationDays);\n\n  useEffect(() => {\n    onEventChangeRef.current = onEventChange;\n  }, [onEventChange]);\n  useEffect(() => {\n    onEventClickRef.current = onEventClick;\n  }, [onEventClick]);\n  useEffect(() => {\n    onResizeNavigateRef.current = onResizeNavigate;\n  }, [onResizeNavigate]);\n  useEffect(() => {\n    eventsRef.current = events;\n  }, [events]);\n  useEffect(() => {\n    hourHeightRef.current = hourHeight;\n  }, [hourHeight]);\n  useEffect(() => {\n    daysRef.current = days;\n  }, [days]);\n  useEffect(() => {\n    dayColumnWidthRef.current = dayColumnWidth;\n  }, [dayColumnWidth]);\n  useEffect(() => {\n    timeAxisWidthRef.current = timeAxisWidth;\n  }, [timeAxisWidth]);\n  useEffect(() => {\n    snapMinutesRef.current = snapMinutes;\n  }, [snapMinutes]);\n  useEffect(() => {\n    dayStartHourRef.current = dayStartHour;\n  }, [dayStartHour]);\n  useEffect(() => {\n    dayEndHourRef.current = dayEndHour;\n  }, [dayEndHour]);\n  useEffect(() => {\n    edgeNavigationDaysRef.current = edgeNavigationDays;\n  }, [edgeNavigationDays]);\n\n  const autoScrollRAFRef = useRef<number | null>(null);\n  const autoScrollSpeedRef = useRef(0);\n  const edgeNavTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const edgeNavDirectionRef = useRef<number | null>(null);\n\n  const handlePointerMoveRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerUpRef = useRef<((e: PointerEvent) => void) | null>(null);\n  const handlePointerCancelRef = useRef<((e: PointerEvent) => void) | null>(\n    null,\n  );\n\n  const cancelAutoScroll = useCallback(() => {\n    if (autoScrollRAFRef.current !== null) {\n      cancelAnimationFrame(autoScrollRAFRef.current);\n      autoScrollRAFRef.current = null;\n    }\n    autoScrollSpeedRef.current = 0;\n  }, []);\n\n  const cancelEdgeNav = useCallback(() => {\n    if (edgeNavTimerRef.current !== null) {\n      clearTimeout(edgeNavTimerRef.current);\n      edgeNavTimerRef.current = null;\n    }\n    edgeNavDirectionRef.current = null;\n  }, []);\n\n  const scheduleEdgeNav = useCallback(\n    (direction: number) => {\n      if (edgeNavDirectionRef.current === direction) return;\n\n      cancelEdgeNav();\n      edgeNavDirectionRef.current = direction;\n\n      const fireNav = () => {\n        onResizeNavigateRef.current?.(direction);\n        edgeNavTimerRef.current = setTimeout(fireNav, EDGE_NAV_REPEAT_MS);\n      };\n\n      edgeNavTimerRef.current = setTimeout(fireNav, EDGE_NAV_DELAY_MS);\n    },\n    [cancelEdgeNav],\n  );\n\n  const cleanup = useCallback(() => {\n    if (handlePointerMoveRef.current) {\n      window.removeEventListener(\"pointermove\", handlePointerMoveRef.current);\n    }\n    if (handlePointerUpRef.current) {\n      window.removeEventListener(\"pointerup\", handlePointerUpRef.current);\n    }\n    if (handlePointerCancelRef.current) {\n      window.removeEventListener(\n        \"pointercancel\",\n        handlePointerCancelRef.current,\n      );\n    }\n    cancelAutoScroll();\n    cancelEdgeNav();\n  }, [cancelAutoScroll, cancelEdgeNav]);\n\n  const startAutoScrollLoop = useCallback(() => {\n    if (autoScrollRAFRef.current !== null) return;\n\n    const tick = () => {\n      const container = scrollContainerRef.current;\n      if (!container) return;\n\n      const speed = autoScrollSpeedRef.current;\n      if (speed === 0) {\n        autoScrollRAFRef.current = null;\n        return;\n      }\n\n      container.scrollTop += speed;\n      autoScrollRAFRef.current = requestAnimationFrame(tick);\n    };\n\n    autoScrollRAFRef.current = requestAnimationFrame(tick);\n  }, [scrollContainerRef]);\n\n  useEffect(() => {\n    handlePointerMoveRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      const deltaY = Math.abs(e.clientY - resize.startClientY);\n      if (!resize.isResizing && deltaY < DRAG_THRESHOLD_PX) return;\n\n      if (!resize.isResizing) {\n        resize.isResizing = true;\n      }\n\n      const container = scrollContainerRef.current;\n      if (!container) return;\n\n      const containerRect = container.getBoundingClientRect();\n      const scrollTop = container.scrollTop;\n      const absoluteY = e.clientY - containerRect.top + scrollTop;\n      // The grid's top edge is `dayStartHour`, not midnight\n      const visibleStartMinutes = dayStartHourRef.current * 60;\n      const visibleEndMinutes = dayEndHourRef.current * 60;\n      const rawMinutes =\n        visibleStartMinutes + (absoluteY / hourHeightRef.current) * 60;\n      const snapStep = snapMinutesRef.current;\n      const snappedMinutes = snapToGrid(rawMinutes, snapStep);\n      // Shortest event a resize can make: one snap step\n      const minDurationMinutes = snapStep;\n\n      let newStartMinutes = resize.originalStartMinutes;\n      let newEndMinutes = resize.originalEndMinutes;\n      let startDate = resize.originalStartDate;\n      let endDate = resize.originalEndDate;\n\n      // Column detection (shared for both edges)\n      const colWidth = dayColumnWidthRef.current;\n      const visibleDays = daysRef.current;\n      const gridLeftEdge = containerRect.left + timeAxisWidthRef.current;\n      const cursorInGrid = e.clientX - gridLeftEdge;\n      const columnIndex = clamp(\n        Math.floor(cursorInGrid / colWidth),\n        0,\n        visibleDays.length - 1,\n      );\n      const targetDay = visibleDays[columnIndex];\n\n      // Unified anchor model: anchor is the opposite end of the grabbed edge\n      const anchorDate =\n        resize.edge === \"bottom\"\n          ? resize.originalStartDate\n          : resize.originalEndDate;\n      const anchorMinutes =\n        resize.edge === \"bottom\"\n          ? resize.originalStartMinutes\n          : resize.originalEndMinutes;\n\n      const cursorTimestamp = targetDay.getTime() + snappedMinutes * 60000;\n      const anchorTimestamp = anchorDate.getTime() + anchorMinutes * 60000;\n\n      let effectiveEdge: \"top\" | \"bottom\";\n\n      if (cursorTimestamp > anchorTimestamp) {\n        // Cursor is after anchor → effective bottom\n        effectiveEdge = \"bottom\";\n        startDate = anchorDate;\n        newStartMinutes = anchorMinutes;\n        endDate = targetDay;\n        newEndMinutes = clamp(\n          snappedMinutes,\n          visibleStartMinutes,\n          visibleEndMinutes,\n        );\n\n        // Cross-day edge case: cursor at minute 0 on day right after anchor → treat as end-of-anchor-day\n        if (!isSameDay(targetDay, anchorDate)) {\n          const dayAfterAnchor = new Date(anchorDate);\n          dayAfterAnchor.setDate(dayAfterAnchor.getDate() + 1);\n          dayAfterAnchor.setHours(0, 0, 0, 0);\n\n          if (isSameDay(targetDay, dayAfterAnchor) && snappedMinutes === 0) {\n            newEndMinutes = 1440;\n            endDate = anchorDate;\n          }\n        }\n\n        // Same-day: enforce min duration\n        if (isSameDay(startDate, endDate)) {\n          newEndMinutes = clamp(\n            newEndMinutes,\n            anchorMinutes + minDurationMinutes,\n            1440,\n          );\n        }\n      } else if (cursorTimestamp < anchorTimestamp) {\n        // Cursor is before anchor → effective top\n        effectiveEdge = \"top\";\n        endDate = anchorDate;\n        newEndMinutes = anchorMinutes;\n        startDate = targetDay;\n        newStartMinutes = clamp(\n          snappedMinutes,\n          visibleStartMinutes,\n          visibleEndMinutes,\n        );\n\n        // Cross-day edge case: cursor at minute 1440 on day right before anchor → treat as start-of-anchor-day\n        if (!isSameDay(targetDay, anchorDate)) {\n          const dayBeforeAnchor = new Date(anchorDate);\n          dayBeforeAnchor.setDate(dayBeforeAnchor.getDate() - 1);\n          dayBeforeAnchor.setHours(0, 0, 0, 0);\n\n          if (isSameDay(targetDay, dayBeforeAnchor) && snappedMinutes >= 1440) {\n            newStartMinutes = 0;\n            startDate = anchorDate;\n          }\n        }\n\n        // Same-day: enforce min duration\n        if (isSameDay(startDate, endDate)) {\n          newStartMinutes = clamp(\n            newStartMinutes,\n            0,\n            anchorMinutes - minDurationMinutes,\n          );\n        }\n      } else {\n        // Cursor at anchor → keep minimum duration in original edge direction (no flip)\n        effectiveEdge = resize.edge;\n        if (resize.edge === \"bottom\") {\n          startDate = anchorDate;\n          newStartMinutes = anchorMinutes;\n          endDate = anchorDate;\n          newEndMinutes = anchorMinutes + minDurationMinutes;\n        } else {\n          endDate = anchorDate;\n          newEndMinutes = anchorMinutes;\n          startDate = anchorDate;\n          newStartMinutes = anchorMinutes - minDurationMinutes;\n        }\n      }\n\n      const currentStart = addMinutesToDate(startDate, newStartMinutes);\n      const currentEnd = addMinutesToDate(endDate, newEndMinutes);\n\n      resize.currentStart = currentStart;\n      resize.currentEnd = currentEnd;\n\n      setResizeState({\n        eventId: resize.eventId,\n        event: resize.event,\n        originalStart: resize.event.start,\n        originalEnd: resize.event.end,\n        currentStart,\n        currentEnd,\n        edge: resize.edge,\n        effectiveEdge,\n        isResizing: true,\n        currentEndDate: endDate,\n        currentStartDate: startDate,\n      });\n\n      // Auto-scroll at top/bottom edges\n      const cursorYInContainer = e.clientY - containerRect.top;\n      const containerHeight = containerRect.height;\n\n      if (cursorYInContainer < AUTO_SCROLL_ZONE_PX) {\n        const dist = cursorYInContainer;\n        autoScrollSpeedRef.current =\n          -AUTO_SCROLL_MAX_SPEED * (1 - dist / AUTO_SCROLL_ZONE_PX);\n        startAutoScrollLoop();\n      } else if (cursorYInContainer > containerHeight - AUTO_SCROLL_ZONE_PX) {\n        const dist = containerHeight - cursorYInContainer;\n        autoScrollSpeedRef.current =\n          AUTO_SCROLL_MAX_SPEED * (1 - dist / AUTO_SCROLL_ZONE_PX);\n        startAutoScrollLoop();\n      } else {\n        cancelAutoScroll();\n      }\n\n      // Edge-of-view week navigation\n      const cursorXInGrid = e.clientX - gridLeftEdge;\n      const gridWidth = colWidth * visibleDays.length;\n\n      if (cursorXInGrid < EDGE_ZONE_PX) {\n        scheduleEdgeNav(-edgeNavigationDaysRef.current);\n      } else if (cursorXInGrid > gridWidth - EDGE_ZONE_PX) {\n        scheduleEdgeNav(edgeNavigationDaysRef.current);\n      } else {\n        cancelEdgeNav();\n      }\n    };\n\n    handlePointerUpRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      cleanup();\n      resizeRef.current = null;\n      setResizeState(null);\n\n      // Touch selects on release, after the resize, rather than on press\n      if (resize.pointerType === \"touch\") {\n        onEventClickRef.current?.(resize.event);\n      }\n      if (!resize.isResizing) return;\n      suppressNextClick(resize.pointerType);\n\n      // Commit from the handler, never from inside a state updater:\n      // updaters run during render, and calling the parent's setState\n      // there triggers \"Cannot update a component while rendering\".\n      // A repeating event's generated occurrence isn't in `events`: commit\n      // the copy the gesture started with\n      const event =\n        eventsRef.current.find((e) => e.id === resize.eventId) ?? resize.event;\n\n      const MS_IN_24H = 24 * 60 * 60 * 1000;\n      const isLongerThan24h =\n        resize.currentEnd.getTime() - resize.currentStart.getTime() > MS_IN_24H;\n\n      onEventChangeRef.current?.({\n        ...event,\n        start: resize.currentStart,\n        end: resize.currentEnd,\n        isAllDay: isLongerThan24h,\n      });\n    };\n\n    // The browser took the pointer over (e.g. for a system gesture): drop\n    // the resize without committing it\n    handlePointerCancelRef.current = (e: PointerEvent) => {\n      const resize = resizeRef.current;\n      if (!resize || e.pointerId !== resize.pointerId) return;\n\n      cleanup();\n      resizeRef.current = null;\n      setResizeState(null);\n    };\n  }, [\n    scrollContainerRef,\n    cleanup,\n    cancelAutoScroll,\n    startAutoScrollLoop,\n    scheduleEdgeNav,\n    cancelEdgeNav,\n  ]);\n\n  const beginResize = useCallback(\n    (\n      { clientY, pointerId, pointerType }: PointerGestureStart,\n      event: CalendarEvent,\n      edge: \"top\" | \"bottom\",\n    ) => {\n      // Mouse and pen select the event immediately\n      if (pointerType !== \"touch\") onEventClickRef.current?.(event);\n\n      const originalStartMinutes =\n        event.start.getHours() * 60 + event.start.getMinutes();\n      let originalEndMinutes =\n        event.end.getHours() * 60 + event.end.getMinutes();\n\n      const originalStartDate = startOfDay(event.start);\n      let originalEndDate = startOfDay(event.end);\n\n      // An end at the next midnight is minute 1440 of the day before, so the\n      // resize starts within one day\n      if (originalEndMinutes === 0 && !isSameDay(event.start, event.end)) {\n        originalEndMinutes = 1440;\n        originalEndDate = subDays(originalEndDate, 1);\n      }\n\n      resizeRef.current = {\n        eventId: event.id,\n        event,\n        pointerId,\n        pointerType,\n        edge,\n        startClientY: clientY,\n        isResizing: false,\n        originalStartMinutes,\n        originalEndMinutes,\n        originalStartDate,\n        originalEndDate,\n        currentStart: event.start,\n        currentEnd: event.end,\n      };\n\n      setResizeState({\n        eventId: event.id,\n        event,\n        originalStart: event.start,\n        originalEnd: event.end,\n        currentStart: event.start,\n        currentEnd: event.end,\n        edge,\n        effectiveEdge: edge,\n        isResizing: false,\n        currentEndDate: originalEndDate,\n        currentStartDate: originalStartDate,\n      });\n\n      if (handlePointerMoveRef.current) {\n        window.addEventListener(\"pointermove\", handlePointerMoveRef.current);\n      }\n      if (handlePointerUpRef.current) {\n        window.addEventListener(\"pointerup\", handlePointerUpRef.current);\n      }\n      if (handlePointerCancelRef.current) {\n        window.addEventListener(\n          \"pointercancel\",\n          handlePointerCancelRef.current,\n        );\n      }\n    },\n    [],\n  );\n\n  const handleResizePointerDown = useCallback(\n    (\n      e: React.PointerEvent<HTMLElement>,\n      event: CalendarEvent,\n      edge: \"top\" | \"bottom\",\n    ) => {\n      if (!isPrimaryPress(e)) return;\n      e.stopPropagation();\n      startGesture(e, (start) => beginResize(start, event, edge));\n    },\n    [startGesture, beginResize],\n  );\n\n  useEffect(() => {\n    return cleanup;\n  }, [cleanup]);\n\n  return { resizeState, handleResizePointerDown };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-horizontal-scroll.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { usePrefersReducedMotion } from \"@/hooks/use-media-query\";\n\ninterface UseHorizontalScrollOptions {\n  containerRef: React.RefObject<HTMLDivElement | null>;\n  dayColumnWidth: number;\n  onNavigate: (daysDelta: number) => void;\n  disabled?: boolean;\n}\n\ninterface UseHorizontalScrollReturn {\n  scrollOffset: number;\n  slideOffset: number;\n  isScrolling: boolean;\n  isAnimating: boolean;\n  triggerSlideAnimation: (daysDelta: number) => void;\n}\n\nconst SCROLL_END_DEBOUNCE_MS = 150;\nconst SNAP_ANIMATION_MS = 200;\n\nexport function useHorizontalScroll({\n  containerRef,\n  dayColumnWidth,\n  onNavigate,\n  disabled,\n}: UseHorizontalScrollOptions): UseHorizontalScrollReturn {\n  const [scrollOffset, setScrollOffset] = useState(0);\n  const [slideOffset, setSlideOffset] = useState(0);\n  const [isScrolling, setIsScrolling] = useState(false);\n  const [isAnimating, setIsAnimating] = useState(false);\n  // Snaps and slides jump straight to their end instead of animating\n  const prefersReducedMotion = usePrefersReducedMotion();\n\n  const scrollEndTimer = useRef<ReturnType<typeof setTimeout>>(null);\n  const accumulatedDelta = useRef(0);\n  const onNavigateRef = useRef(onNavigate);\n  useEffect(() => {\n    onNavigateRef.current = onNavigate;\n  }, [onNavigate]);\n\n  const snapAndNavigate = useCallback(\n    (offset: number) => {\n      if (dayColumnWidth <= 0) return;\n\n      const daysDelta = Math.round(offset / dayColumnWidth);\n\n      if (prefersReducedMotion) {\n        if (daysDelta !== 0) onNavigateRef.current(-daysDelta);\n        setScrollOffset(0);\n        setIsScrolling(false);\n        accumulatedDelta.current = 0;\n        return;\n      }\n\n      // If scroll distance < half a day-column width, snap back\n      if (daysDelta === 0) {\n        setIsAnimating(true);\n        setScrollOffset(0);\n        setTimeout(() => {\n          setIsAnimating(false);\n          setIsScrolling(false);\n        }, SNAP_ANIMATION_MS);\n        return;\n      }\n\n      // Snap to exact day boundary then navigate\n      const targetOffset = daysDelta * dayColumnWidth;\n      setIsAnimating(true);\n      setScrollOffset(targetOffset);\n\n      setTimeout(() => {\n        onNavigateRef.current(-daysDelta);\n        setScrollOffset(0);\n        setIsAnimating(false);\n        setIsScrolling(false);\n        accumulatedDelta.current = 0;\n      }, SNAP_ANIMATION_MS);\n    },\n    [dayColumnWidth, prefersReducedMotion],\n  );\n\n  // Programmatic slide animation for button/keyboard navigation\n  // Uses slideOffset (not scrollOffset) so dynamicBuffer isn't affected\n  // Does NOT call onNavigate — caller is responsible for having already changed the date\n  const triggerSlideAnimation = useCallback(\n    (daysDelta: number) => {\n      if (dayColumnWidth <= 0 || isAnimating || isScrolling) return;\n      if (prefersReducedMotion) return;\n\n      // Start from the opposite direction to create slide effect\n      const startOffset = daysDelta * dayColumnWidth;\n      setSlideOffset(startOffset);\n\n      // Force a reflow then animate to 0\n      requestAnimationFrame(() => {\n        requestAnimationFrame(() => {\n          setIsAnimating(true);\n          setSlideOffset(0);\n          setTimeout(() => {\n            setIsAnimating(false);\n          }, SNAP_ANIMATION_MS);\n        });\n      });\n    },\n    [dayColumnWidth, isAnimating, isScrolling, prefersReducedMotion],\n  );\n\n  useEffect(() => {\n    const container = containerRef.current;\n    if (!container) return;\n\n    const handleWheel = (e: WheelEvent) => {\n      if (disabled) return;\n\n      // Only handle horizontal-dominant scrolls\n      if (Math.abs(e.deltaX) <= Math.abs(e.deltaY)) return;\n\n      e.preventDefault();\n\n      setIsScrolling(true);\n\n      // Negate deltaX: scroll right (positive deltaX) = move calendar left = navigate forward\n      accumulatedDelta.current += -e.deltaX;\n      setScrollOffset(accumulatedDelta.current);\n\n      // Reset debounce timer\n      if (scrollEndTimer.current) {\n        clearTimeout(scrollEndTimer.current);\n      }\n\n      scrollEndTimer.current = setTimeout(() => {\n        snapAndNavigate(accumulatedDelta.current);\n        accumulatedDelta.current = 0;\n      }, SCROLL_END_DEBOUNCE_MS);\n    };\n\n    container.addEventListener(\"wheel\", handleWheel, { passive: false });\n\n    return () => {\n      container.removeEventListener(\"wheel\", handleWheel);\n      if (scrollEndTimer.current) {\n        clearTimeout(scrollEndTimer.current);\n      }\n    };\n  }, [containerRef, snapAndNavigate, disabled]);\n\n  return {\n    scrollOffset,\n    slideOffset,\n    isScrolling,\n    isAnimating,\n    triggerSlideAnimation,\n  };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-media-query.ts",
      "content": "import * as React from \"react\";\n\n/** Matches when the viewer asked the system to minimize animation */\nconst REDUCED_MOTION_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction getServerSnapshot(): boolean {\n  return false;\n}\n\n/**\n * Subscribes to a CSS media query and returns whether it currently matches.\n *\n * Returns `false` during server rendering and hydration, then the live value.\n */\nexport function useMediaQuery(query: string): boolean {\n  const subscribe = React.useCallback(\n    (onChange: () => void) => {\n      const mql = window.matchMedia(query);\n      mql.addEventListener(\"change\", onChange);\n      return () => mql.removeEventListener(\"change\", onChange);\n    },\n    [query],\n  );\n\n  const getSnapshot = React.useCallback(\n    () => window.matchMedia(query).matches,\n    [query],\n  );\n\n  return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\n/**\n * Whether the viewer prefers reduced motion. `false` during server\n * rendering and hydration, then the live value.\n */\nexport function usePrefersReducedMotion(): boolean {\n  return useMediaQuery(REDUCED_MOTION_QUERY);\n}\n",
      "type": "registry:hook"
    }
  ],
  "type": "registry:component"
}