{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "event-details",
  "title": "Event Details",
  "description": "Event chips, the detail panel, the details popover and the right-click menu.",
  "dependencies": [
    "@floating-ui/react-dom",
    "date-fns",
    "lucide-react",
    "react-day-picker@^9"
  ],
  "registryDependencies": [
    "@calendarcn/calendar-core",
    "avatar",
    "button",
    "calendar",
    "command",
    "dialog",
    "dropdown-menu",
    "popover",
    "switch"
  ],
  "files": [
    {
      "path": "src/components/calendar-event-item.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { useIsPast } from \"@/hooks/use-now\";\nimport { EventDetailPopover } from \"./event-detail-popover\";\nimport { useCalendarPopoverBoundary } from \"./calendar-popover-context\";\nimport { EventContentSlot, useCalendarConfig } from \"./calendar-provider\";\nimport {\n  formatTime,\n  formatTimeRange,\n  getEventLabel,\n  resolveEventColor,\n} from \"@/lib/event-utils\";\nimport type {\n  CalendarEvent,\n  CalendarEventItemProps,\n  EventColor,\n  EventContentProps,\n  EventDetailsTriggerProps,\n  EventItemPopoverProps,\n  PopoverAnchorRect,\n} from \"./week-view-types\";\nimport { EventContextMenu } from \"./event-context-menu\";\n\nexport const eventColorStyles: Record<\n  EventColor,\n  {\n    bg: string;\n    bgHover: string;\n    border: string;\n    borderLine: string;\n    text: string;\n  }\n> = {\n  red: {\n    bg: \"bg-event-red-bg\",\n    bgHover: \"hover:bg-event-red-bg/70\",\n    border: \"bg-event-red-border\",\n    borderLine: \"border-event-red-border\",\n    text: \"text-event-red\",\n  },\n  orange: {\n    bg: \"bg-event-orange-bg\",\n    bgHover: \"hover:bg-event-orange-bg/70\",\n    border: \"bg-event-orange-border\",\n    borderLine: \"border-event-orange-border\",\n    text: \"text-event-orange\",\n  },\n  yellow: {\n    bg: \"bg-event-yellow-bg\",\n    bgHover: \"hover:bg-event-yellow-bg/70\",\n    border: \"bg-event-yellow-border\",\n    borderLine: \"border-event-yellow-border\",\n    text: \"text-event-yellow\",\n  },\n  green: {\n    bg: \"bg-event-green-bg\",\n    bgHover: \"hover:bg-event-green-bg/70\",\n    border: \"bg-event-green-border\",\n    borderLine: \"border-event-green-border\",\n    text: \"text-event-green\",\n  },\n  blue: {\n    bg: \"bg-event-blue-bg\",\n    bgHover: \"hover:bg-event-blue-bg/70\",\n    border: \"bg-event-blue-border\",\n    borderLine: \"border-event-blue-border\",\n    text: \"text-event-blue\",\n  },\n  purple: {\n    bg: \"bg-event-purple-bg\",\n    bgHover: \"hover:bg-event-purple-bg/70\",\n    border: \"bg-event-purple-border\",\n    borderLine: \"border-event-purple-border\",\n    text: \"text-event-purple\",\n  },\n  gray: {\n    bg: \"bg-event-gray-bg\",\n    bgHover: \"hover:bg-event-gray-bg/70\",\n    border: \"bg-event-gray-border\",\n    borderLine: \"border-event-gray-border\",\n    text: \"text-event-gray\",\n  },\n};\n\n/**\n * Positions a block from explicit start/end times (drag and resize\n * previews), clipped to the visible hours and measured from the grid's top\n * edge (`dayStartHour`)\n */\nfunction computeOverrideStyle(\n  positionedEvent: CalendarEventItemProps[\"positionedEvent\"],\n  hourHeight: number,\n  overrideStart: Date,\n  overrideEnd: Date,\n  dayStartHour: number,\n  dayEndHour: number,\n) {\n  const startMinutes =\n    overrideStart.getHours() * 60 + overrideStart.getMinutes();\n  let endMinutes = overrideEnd.getHours() * 60 + overrideEnd.getMinutes();\n  // If end is midnight and on a different day than start, treat as 1440 (end of day)\n  if (endMinutes === 0 && overrideEnd.getDate() !== overrideStart.getDate()) {\n    endMinutes = 1440;\n  }\n  const visibleStart = dayStartHour * 60;\n  const visibleEnd = dayEndHour * 60;\n  const topMinutes =\n    Math.min(Math.max(startMinutes, visibleStart), visibleEnd) - visibleStart;\n  const bottomMinutes =\n    Math.min(Math.max(endMinutes, visibleStart), visibleEnd) - visibleStart;\n  const topPx = (topMinutes / 60) * hourHeight;\n  const heightPx = ((bottomMinutes - topMinutes) / 60) * hourHeight;\n\n  return {\n    top: `${topPx}px`,\n    height: `${heightPx}px`,\n    left: `${positionedEvent.left}%`,\n    width: `${positionedEvent.width}%`,\n    minHeight: \"20px\",\n  };\n}\n\nconst RESIZE_HOTZONE_PX = 8;\n\n/**\n * Keyboard focus ring for events: a border on an `::after` overlay, painted\n * above the event's absolutely positioned background layers (which cover an\n * outline) and inside its box (so clipping and neighbors don't hide it).\n * Shown only for keyboard focus (`focus-visible`), never on click. The\n * event must be positioned.\n */\nexport const EVENT_FOCUS_RING_CLASS =\n  \"focus-visible:after:pointer-events-none focus-visible:after:absolute focus-visible:after:inset-0 focus-visible:after:rounded-[inherit] focus-visible:after:border-2 focus-visible:after:border-ring\";\n\n/**\n * Box for custom `renderEventContent` output in a time-grid block: above the\n * background layers, filling the block, inset like the default text\n */\nconst TIME_GRID_SLOT_CLASS = \"relative h-full min-w-0 overflow-hidden pl-1\";\n\ninterface EventDetailsTriggerOptions {\n  /** Whether the event opens its details in a popover at all */\n  showEventPopover: boolean;\n  /** Whether the event's details popover is open */\n  showPopover: boolean;\n  /** The popover panel's id */\n  detailsId: string;\n}\n\n/**\n * ARIA for an event element that opens the event's details in a popover:\n * what it opens, whether that is open now, and the panel it controls.\n */\nexport function getEventDetailsTriggerProps({\n  showEventPopover,\n  showPopover,\n  detailsId,\n}: EventDetailsTriggerOptions): EventDetailsTriggerProps {\n  if (!showEventPopover) return {};\n  return {\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": showPopover,\n    \"aria-controls\": showPopover ? detailsId : undefined,\n  };\n}\n\ninterface EventDetailsToggleOptions {\n  /** Whether the event's details popover is open */\n  showPopover: boolean;\n  /** Whether the event opens its details in a popover at all */\n  showEventPopover: boolean;\n  close: () => void;\n}\n\n/**\n * An event opens and closes its details popover. Gives the event element the\n * popup's ARIA and keeps its click a toggle: a mouse press selects the event,\n * and so opens the details, before its click arrives, so the click closes\n * them only when they were already open at the press.\n */\nfunction useEventDetailsToggle({\n  showPopover,\n  showEventPopover,\n  close,\n}: EventDetailsToggleOptions) {\n  const detailsId = React.useId();\n  /** Whether the details were open when the current press began */\n  const openOnPressRef = React.useRef<boolean | null>(null);\n\n  return {\n    detailsId,\n    /** For the event element, which opens the details, a dialog */\n    triggerProps: getEventDetailsTriggerProps({\n      showEventPopover,\n      showPopover,\n      detailsId,\n    }),\n    /** Call when a press on the event begins */\n    notePress() {\n      openOnPressRef.current = showPopover;\n    },\n    /** Call from the event's click, after it selected the event */\n    closeIfToggled() {\n      // A click with no press before it (assistive technology) toggles too\n      const wasOpen = openOnPressRef.current ?? showPopover;\n      openOnPressRef.current = null;\n      if (wasOpen && showPopover) close();\n    },\n  };\n}\n\nexport function CalendarEventItem({\n  positionedEvent,\n  hourHeight,\n  isPast: isPastProp,\n  isSelected,\n  onClick,\n  dragVariant = \"default\",\n  isResizing = false,\n  overrideStart,\n  overrideEnd,\n  onDragPointerDown,\n  onResizePointerDown,\n  onEventChange,\n  cursorY,\n  cursorX,\n  fixedWidth,\n  fixedHeight,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  className,\n}: CalendarEventItemProps) {\n  const { event, segmentPosition = \"full\" } = positionedEvent;\n  const { calendars, dayStartHour, dayEndHour, hourCycle, locale } =\n    useCalendarConfig();\n  const color = resolveEventColor(event, calendars);\n  const styles = eventColorStyles[color];\n  // `false` on the server and during hydration, so the markup matches\n  const endIsPast = useIsPast(event.end);\n  const eventIsPast = isPastProp ?? endIsPast;\n  const { view, boundaryRight, headerBottom } = useCalendarPopoverBoundary();\n  const isDayView = view === \"day\";\n\n  /** Ref to the event button element, used to measure its viewport rect. */\n  const eventRef = React.useRef<HTMLDivElement>(null);\n\n  /**\n   * Viewport-relative top & height of the event element.\n   * Used to vertically align the day-view popover anchor with the event\n   * so the popover appears beside the event rather than at a fixed position.\n   */\n  const [anchorRect, setAnchorRect] = React.useState<{\n    top: number;\n    height: number;\n  } | null>(null);\n\n  const showPopover = isSelected && showEventPopover;\n  const detailsToggle = useEventDetailsToggle({\n    showPopover: showPopover ?? false,\n    showEventPopover: showEventPopover ?? false,\n    close: () => onEventPopoverClose?.(event.id),\n  });\n\n  // Measure the event element's viewport position when the popover opens in\n  // day view. useLayoutEffect ensures the measurement happens before paint so\n  // the popover anchor is positioned correctly on first frame.\n  React.useLayoutEffect(() => {\n    if (!showPopover || !isDayView || !eventRef.current) {\n      setAnchorRect(null);\n      return;\n    }\n    const rect = eventRef.current.getBoundingClientRect();\n    setAnchorRect({ top: rect.top, height: rect.height });\n  }, [showPopover, isDayView]);\n\n  /**\n   * In day view the event spans the full grid width, so there is no room for\n   * the popover beside it. Anchor it to a zero-width line at the RIGHT edge\n   * of the calendar boundary, level with the event, and open it leftward\n   * (side=\"left\") — matching Notion Calendar.\n   */\n  const dayViewAnchor = React.useMemo<PopoverAnchorRect>(\n    () => ({\n      getBoundingClientRect: () =>\n        new DOMRect(\n          boundaryRight,\n          anchorRect?.top ?? 0,\n          0,\n          anchorRect?.height ?? 0,\n        ),\n    }),\n    [boundaryRight, anchorRect],\n  );\n\n  const hasTopRounding =\n    segmentPosition === \"start\" || segmentPosition === \"full\";\n  const hasBottomRounding =\n    segmentPosition === \"end\" || segmentPosition === \"full\";\n  const showTopResize =\n    segmentPosition === \"start\" || segmentPosition === \"full\";\n  const showBottomResize =\n    segmentPosition === \"end\" || segmentPosition === \"full\";\n\n  const [contextMenu, setContextMenu] = React.useState<{\n    x: number;\n    y: number;\n  } | null>(null);\n\n  const closeContextMenu = React.useCallback(() => {\n    setContextMenu(null);\n    onContextMenuOpenChange?.(false);\n  }, [onContextMenuOpenChange]);\n\n  const displayStart = overrideStart ?? event.start;\n  const displayEnd = overrideEnd ?? event.end;\n\n  const displayEvent: CalendarEvent =\n    overrideStart && overrideEnd\n      ? { ...event, start: displayStart, end: displayEnd }\n      : event;\n\n  const defaultStyle = {\n    top: `${positionedEvent.top}%`,\n    height: `${positionedEvent.height}%`,\n    left: `${positionedEvent.left}%`,\n    width: `${positionedEvent.width}%`,\n    minHeight: \"20px\",\n    zIndex: isSelected ? 20 : positionedEvent.column,\n  };\n\n  const posStyle =\n    overrideStart && overrideEnd\n      ? computeOverrideStyle(\n          positionedEvent,\n          hourHeight,\n          overrideStart,\n          overrideEnd,\n          dayStartHour,\n          dayEndHour,\n        )\n      : defaultStyle;\n\n  const heightInPixels =\n    overrideStart && overrideEnd\n      ? Number.parseFloat(String(posStyle.height))\n      : (positionedEvent.height / 100) *\n        (dayEndHour - dayStartHour) *\n        hourHeight;\n  const isCompact = heightInPixels < 40;\n  /**\n   * A resize preview drawn next to the real event (its anchor or another\n   * day's segment), not an event the user can focus\n   */\n  const isPreview = isResizing || Boolean(overrideStart && overrideEnd);\n  const timeRangeLabel = formatTimeRange(\n    displayEvent.start,\n    displayEvent.end,\n    hourCycle,\n    locale,\n  );\n\n  const contentProps: EventContentProps = {\n    event: displayEvent,\n    view,\n    placement: \"time-grid\",\n    isSelected: isSelected ?? false,\n    isPast: eventIsPast,\n    isDragging: dragVariant === \"dragging\",\n    isResizing,\n    isCompact,\n    timeLabel: timeRangeLabel,\n  };\n\n  if (dragVariant === \"ghost\") {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          \"absolute rounded-sm px-2 py-1 pointer-events-none opacity-30 overflow-hidden\",\n          className,\n        )}\n        style={{\n          top: `${positionedEvent.top}%`,\n          height: `${positionedEvent.height}%`,\n          left: `${positionedEvent.left}%`,\n          width: `${positionedEvent.width}%`,\n          minHeight: \"20px\",\n          zIndex: 15,\n        }}\n      >\n        <div className=\"absolute inset-0 rounded-sm bg-white dark:bg-[#191919]\" />\n        <div className={cn(\"absolute inset-0 rounded-sm\", styles.bg)} />\n        <div\n          className={cn(\n            \"absolute left-0 top-0 bottom-0 w-[4px] rounded-l-md dark:bg-white dark:mix-blend-overlay\",\n            styles.border,\n          )}\n        />\n        <EventContentSlot\n          {...contentProps}\n          className={TIME_GRID_SLOT_CLASS}\n          fallback={\n            <div\n              className={cn(\n                \"relative flex flex-col h-full pl-1 overflow-hidden\",\n                isCompact && \"flex-row items-center gap-1\",\n              )}\n            >\n              <span\n                className={cn(\n                  \"font-medium text-[0.625rem] leading-tight break-words\",\n                  styles.text,\n                  \"dark:text-white/80\",\n                )}\n              >\n                {event.title}\n              </span>\n              {!isCompact && (\n                <span\n                  className={cn(\n                    \"text-[0.625rem] whitespace-nowrap\",\n                    styles.text,\n                    \"dark:text-white dark:mix-blend-overlay\",\n                  )}\n                >\n                  {formatTimeRange(event.start, event.end, hourCycle, locale)}\n                </span>\n              )}\n            </div>\n          }\n        />\n      </div>\n    );\n  }\n\n  if (dragVariant === \"placeholder\") {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          \"absolute rounded-sm pointer-events-none border-2\",\n          styles.borderLine,\n          className,\n        )}\n        style={{\n          ...posStyle,\n          left: \"0%\",\n          width: \"100%\",\n          zIndex: 25,\n        }}\n      />\n    );\n  }\n\n  const isDraggingCopy = dragVariant === \"dragging\";\n\n  if (isDraggingCopy) {\n    const durationMinutes =\n      (displayEnd.getTime() - displayStart.getTime()) / 60000;\n    const heightPx = fixedHeight ?? (durationMinutes / 60) * hourHeight;\n\n    const useFixed = cursorX != null && cursorY != null;\n\n    const draggingStyle: React.CSSProperties = useFixed\n      ? {\n          position: \"fixed\",\n          top: `${cursorY}px`,\n          left: `${cursorX}px`,\n          height: `${heightPx}px`,\n          width: fixedWidth != null ? `${fixedWidth}px` : \"200px\",\n          minHeight: \"20px\",\n          zIndex: 30,\n        }\n      : {\n          top: posStyle.top,\n          height: `${heightPx}px`,\n          left: `${positionedEvent.left}%`,\n          width: `${positionedEvent.width}%`,\n          minHeight: \"20px\",\n          zIndex: 30,\n        };\n\n    return (\n      <div\n        tabIndex={-1}\n        aria-hidden\n        className={cn(\n          \"absolute rounded-sm px-2 py-1\",\n          \"pointer-events-none cursor-grabbing\",\n          \"overflow-hidden select-none opacity-80 shadow-lg\",\n          className,\n        )}\n        style={draggingStyle}\n      >\n        <div className=\"absolute inset-0 rounded-sm bg-white dark:bg-[#191919]\" />\n        <div className={cn(\"absolute inset-0 rounded-sm\", styles.bg)} />\n        <div\n          className={cn(\n            \"absolute left-0 top-0 bottom-0 w-[4px] rounded-l-md dark:bg-white dark:mix-blend-overlay\",\n            styles.border,\n          )}\n        />\n        <EventContentSlot\n          {...contentProps}\n          isCompact={heightPx < 40}\n          className={TIME_GRID_SLOT_CLASS}\n          fallback={\n            <div\n              className={cn(\n                \"relative flex flex-col h-full pl-1 overflow-hidden\",\n                heightPx < 40 && \"flex-row items-center gap-1\",\n              )}\n            >\n              <span className=\"font-medium text-[0.625rem] leading-tight break-words text-white dark:text-white flex items-center gap-0.5\">\n                {event.title}\n              </span>\n              {heightPx >= 40 && (\n                <span className=\"text-[0.625rem] whitespace-nowrap text-white dark:text-white\">\n                  {timeRangeLabel}\n                </span>\n              )}\n            </div>\n          }\n        />\n      </div>\n    );\n  }\n\n  function handleMouseMove(e: React.MouseEvent) {\n    const target = e.currentTarget as HTMLElement;\n    const rect = target.getBoundingClientRect();\n    const offsetY = e.clientY - rect.top;\n    const height = rect.height;\n\n    if (showTopResize && showBottomResize && height < RESIZE_HOTZONE_PX * 2) {\n      target.style.setProperty(\"--cursor\", \"row-resize\");\n      return;\n    }\n\n    if (showTopResize && offsetY <= RESIZE_HOTZONE_PX) {\n      target.style.setProperty(\"--cursor\", \"row-resize\");\n      return;\n    }\n\n    if (showBottomResize && offsetY >= height - RESIZE_HOTZONE_PX) {\n      target.style.setProperty(\"--cursor\", \"row-resize\");\n      return;\n    }\n\n    target.style.removeProperty(\"--cursor\");\n  }\n\n  function handlePointerDown(e: React.PointerEvent<HTMLElement>) {\n    e.stopPropagation();\n    detailsToggle.notePress();\n\n    const rect = e.currentTarget.getBoundingClientRect();\n    const offsetY = e.clientY - rect.top;\n    const height = rect.height;\n\n    if (showTopResize && showBottomResize && height < RESIZE_HOTZONE_PX * 2) {\n      const edge = offsetY < height / 2 ? \"top\" : \"bottom\";\n      onResizePointerDown?.(e, event, edge);\n      return;\n    }\n\n    if (showTopResize && offsetY <= RESIZE_HOTZONE_PX) {\n      onResizePointerDown?.(e, event, \"top\");\n      return;\n    }\n\n    if (showBottomResize && offsetY >= height - RESIZE_HOTZONE_PX) {\n      onResizePointerDown?.(e, event, \"bottom\");\n      return;\n    }\n\n    onDragPointerDown?.(e, event);\n  }\n\n  function handleClick(e: React.MouseEvent) {\n    e.stopPropagation();\n    onClick?.(event);\n    detailsToggle.closeIfToggled();\n  }\n\n  function handleKeyDown(e: React.KeyboardEvent) {\n    if (e.key !== \"Enter\" && e.key !== \" \") return;\n    e.preventDefault();\n    onClick?.(event);\n  }\n\n  function handleContextMenu(e: React.MouseEvent) {\n    e.preventDefault();\n    e.stopPropagation();\n    setContextMenu({ x: e.clientX, y: e.clientY });\n    onContextMenuOpenChange?.(true);\n  }\n\n  const eventElement = (\n    <div\n      ref={eventRef}\n      role=\"button\"\n      tabIndex={isPreview ? -1 : 0}\n      aria-hidden={isPreview || undefined}\n      aria-label={getEventLabel(event, hourCycle, locale)}\n      aria-pressed={isSelected ?? false}\n      {...(!isPreview && detailsToggle.triggerProps)}\n      data-event-id={isPreview ? undefined : event.id}\n      onPointerDown={handlePointerDown}\n      onMouseMove={handleMouseMove}\n      onClick={handleClick}\n      onKeyDown={handleKeyDown}\n      onContextMenu={handleContextMenu}\n      className={cn(\n        \"absolute px-2 py-1\",\n        hasTopRounding && \"rounded-t-md\",\n        hasBottomRounding && \"rounded-b-md\",\n        \"cursor-default hover:z-10 focus:outline-none\",\n        EVENT_FOCUS_RING_CLASS,\n        \"overflow-hidden select-none\",\n        isSelected && \"z-20\",\n        className,\n      )}\n      style={{\n        ...posStyle,\n        zIndex: isSelected ? 20 : positionedEvent.column,\n      }}\n    >\n      {/* Solid background layer to prevent transparency bleed-through */}\n      <div\n        className={cn(\n          \"absolute inset-0 bg-white dark:bg-[#191919]\",\n          hasTopRounding && \"rounded-t-md\",\n          hasBottomRounding && \"rounded-b-md\",\n        )}\n      />\n\n      {/* Colored background layer - uses border color when selected */}\n      <div\n        className={cn(\n          \"absolute inset-0\",\n          hasTopRounding && \"rounded-t-md\",\n          hasBottomRounding && \"rounded-b-md\",\n          isSelected ? styles.border : styles.bg,\n          eventIsPast && !isSelected && \"opacity-60\",\n        )}\n      />\n\n      {/* Left border - hidden when selected (merges with bg) */}\n      {!isSelected && (\n        <div\n          className={cn(\n            \"absolute left-0 top-0 bottom-0 w-[4px] dark:bg-white dark:mix-blend-overlay\",\n            hasTopRounding && \"rounded-tl-md\",\n            hasBottomRounding && \"rounded-bl-md\",\n            styles.border,\n            eventIsPast && \"opacity-60\",\n          )}\n        />\n      )}\n      <EventContentSlot\n        {...contentProps}\n        className={TIME_GRID_SLOT_CLASS}\n        fallback={\n          <div\n            className={cn(\n              \"relative flex flex-col h-full pl-1 overflow-hidden\",\n              isCompact && \"flex-row items-center gap-1\",\n            )}\n          >\n            <span\n              className={cn(\n                \"font-medium text-[0.625rem] leading-tight break-words flex items-center gap-0.5\",\n                isSelected\n                  ? \"text-white dark:text-white\"\n                  : cn(\n                      styles.text,\n                      \"dark:text-white/80\",\n                      eventIsPast && \"opacity-60\",\n                    ),\n              )}\n            >\n              {event.title}\n            </span>\n            {!isCompact && (\n              <span\n                className={cn(\n                  \"text-[0.625rem] whitespace-nowrap\",\n                  isSelected\n                    ? \"text-white dark:text-white\"\n                    : cn(\n                        styles.text,\n                        \"dark:text-white dark:mix-blend-overlay\",\n                        eventIsPast && \"opacity-60 dark:opacity-100\",\n                      ),\n                )}\n              >\n                {timeRangeLabel}\n              </span>\n            )}\n          </div>\n        }\n      />\n    </div>\n  );\n\n  return (\n    <>\n      {eventElement}\n      {showPopover && (\n        <EventDetailPopover\n          event={event}\n          id={detailsToggle.detailsId}\n          anchor={isDayView ? dayViewAnchor : eventRef}\n          triggerRef={eventRef}\n          onEventChange={onEventChange}\n          onClose={() => onEventPopoverClose?.(event.id)}\n          onExpand={onEventPopoverExpand}\n          side={isDayView ? \"left\" : \"right\"}\n          collisionPaddingTop={isDayView ? headerBottom : undefined}\n        />\n      )}\n      {contextMenu && (\n        <EventContextMenu\n          event={event}\n          position={contextMenu}\n          onClose={closeContextMenu}\n          onEventChange={onEventChange}\n        />\n      )}\n    </>\n  );\n}\n\n/** Drag visual variant for all-day events */\nexport type AllDayDragVariant = \"ghost\" | \"placeholder\" | \"dragging\";\n\nexport interface AllDayEventItemProps extends EventItemPopoverProps {\n  event: CalendarEvent;\n  /** Overrides whether the event renders as past (defaults to `useIsPast`) */\n  isPast?: boolean;\n  isSelected?: boolean;\n  onClick?: (event: CalendarEvent) => void;\n  className?: string;\n  /** For multi-day events: position info */\n  spanStart?: boolean;\n  spanEnd?: boolean;\n  /** Pointerdown handler to initiate horizontal resize or drag */\n  onResizePointerDown?: (\n    e: React.PointerEvent<HTMLElement>,\n    event: CalendarEvent,\n    edge: \"left\" | \"right\" | \"move\",\n  ) => void;\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  /**\n   * Percentage of the event's width that is hidden off-screen to the left.\n   * Used in day view to offset the title into the visible area so multi-day\n   * events always show their title \\u2014 \\u201csticky title\\u201d effect.\n   */\n  titleOffsetPercent?: number;\n  /** Visual variant during drag operations */\n  dragVariant?: AllDayDragVariant;\n  /** Whether the event's edges are being dragged (passed to `renderEventContent`) */\n  isResizing?: boolean;\n}\n\nconst ALL_DAY_RESIZE_HOTZONE_PX = 6;\n\n/**\n * Box for custom `renderEventContent` output in an all-day bar: above the\n * background layers, filling the bar (`pl-1` is added beside the left accent)\n */\nconst ALL_DAY_SLOT_CLASS =\n  \"relative flex h-full min-w-0 flex-1 items-center overflow-hidden\";\n\nexport function AllDayEventItem({\n  event,\n  isPast: isPastProp,\n  isSelected,\n  onClick,\n  className,\n  spanStart = true,\n  spanEnd = true,\n  onResizePointerDown,\n  onEventChange,\n  onContextMenuOpenChange,\n  showEventPopover,\n  onEventPopoverExpand,\n  onEventPopoverClose,\n  titleOffsetPercent = 0,\n  dragVariant,\n  isResizing = false,\n}: AllDayEventItemProps) {\n  const { calendars, hourCycle, locale } = useCalendarConfig();\n  const color = resolveEventColor(event, calendars);\n  const styles = eventColorStyles[color];\n  const { view, boundaryRight, headerBottom } = useCalendarPopoverBoundary();\n  const isDayView = view === \"day\";\n  // `false` on the server and during hydration, so the markup matches\n  const endIsPast = useIsPast(event.end);\n  const eventIsPast = isPastProp ?? endIsPast;\n\n  /** The event element: anchors and toggles its details popover */\n  const eventRef = React.useRef<HTMLDivElement>(null);\n  const showPopover = isSelected && showEventPopover;\n  const detailsToggle = useEventDetailsToggle({\n    showPopover: showPopover ?? false,\n    showEventPopover: showEventPopover ?? false,\n    close: () => onEventPopoverClose?.(event.id),\n  });\n\n  /**\n   * In day view, all-day events span the full width. Anchor the popover to\n   * the calendar boundary's right edge (a zero-width line the height of the\n   * viewport) so it always appears at the visible right edge — even when the\n   * event wrapper extends into off-screen buffer days.\n   */\n  const dayViewAnchor = React.useMemo<PopoverAnchorRect>(\n    () => ({\n      getBoundingClientRect: () =>\n        new DOMRect(boundaryRight, 0, 0, window.innerHeight),\n    }),\n    [boundaryRight],\n  );\n\n  const [contextMenu, setContextMenu] = React.useState<{\n    x: number;\n    y: number;\n  } | null>(null);\n\n  const closeContextMenu = React.useCallback(() => {\n    setContextMenu(null);\n    onContextMenuOpenChange?.(false);\n  }, [onContextMenuOpenChange]);\n\n  // Check if event has a specific start time (not midnight)\n  const hasStartTime =\n    event.start.getHours() !== 0 || event.start.getMinutes() !== 0;\n  // \"8:45 AM\" / \"4 PM\", or \"08:45\" / \"16:00\" on a 24-hour clock\n  const startTimeLabel = hasStartTime\n    ? formatTime(event.start, hourCycle, locale)\n    : \"\";\n\n  const contentProps: EventContentProps = {\n    event,\n    view,\n    placement: \"all-day\",\n    isSelected: isSelected ?? false,\n    isPast: eventIsPast,\n    isDragging: dragVariant === \"dragging\",\n    isResizing,\n    isCompact: true,\n    timeLabel: startTimeLabel,\n  };\n  const slotClassName = cn(ALL_DAY_SLOT_CLASS, spanStart && \"pl-1\");\n\n  // Ghost: faded version at original position during move\n  if (dragVariant === \"ghost\") {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          \"relative h-6 px-2 py-0.5 pointer-events-none opacity-30\",\n          \"overflow-hidden select-none flex items-center gap-1\",\n          spanStart && \"rounded-l-md\",\n          spanEnd && \"rounded-r-md\",\n          className,\n        )}\n      >\n        <div\n          className={cn(\n            \"absolute inset-0 bg-white dark:bg-[#191919]\",\n            spanStart && \"rounded-l-md\",\n            spanEnd && \"rounded-r-md\",\n          )}\n        />\n        <div\n          className={cn(\n            \"absolute inset-0\",\n            styles.bg,\n            spanStart && \"rounded-l-md\",\n            spanEnd && \"rounded-r-md\",\n          )}\n        />\n        {spanStart && (\n          <div\n            className={cn(\n              \"absolute left-0 top-0 bottom-0 w-[4px] dark:bg-white dark:mix-blend-overlay\",\n              spanStart && \"rounded-l-md\",\n              styles.border,\n            )}\n          />\n        )}\n        <EventContentSlot\n          {...contentProps}\n          className={slotClassName}\n          fallback={\n            <span\n              className={cn(\n                \"relative font-medium text-[0.625rem] leading-tight whitespace-nowrap\",\n                spanStart && \"pl-1\",\n                styles.text,\n                \"dark:text-white/80\",\n              )}\n            >\n              {event.title}\n            </span>\n          }\n        />\n      </div>\n    );\n  }\n\n  // Placeholder: border-only outline at target position\n  if (dragVariant === \"placeholder\") {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          \"relative h-6 pointer-events-none border-2 rounded-sm\",\n          styles.borderLine,\n          className,\n        )}\n      />\n    );\n  }\n\n  // Dragging copy: floating replica following cursor\n  if (dragVariant === \"dragging\") {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          \"h-6 px-2 py-0.5 pointer-events-none cursor-grabbing\",\n          \"overflow-hidden select-none flex items-center gap-1\",\n          \"rounded-sm opacity-80 shadow-lg\",\n          className,\n        )}\n      >\n        <div className=\"absolute inset-0 rounded-sm bg-white dark:bg-[#191919]\" />\n        <div className={cn(\"absolute inset-0 rounded-sm\", styles.bg)} />\n        <div\n          className={cn(\n            \"absolute left-0 top-0 bottom-0 w-[4px] rounded-l-md dark:bg-white dark:mix-blend-overlay\",\n            styles.border,\n          )}\n        />\n        <EventContentSlot\n          {...contentProps}\n          className={slotClassName}\n          fallback={\n            <span\n              className={cn(\n                \"relative font-medium text-[0.625rem] leading-tight whitespace-nowrap pl-1\",\n                styles.text,\n                \"dark:text-white/80\",\n              )}\n            >\n              {event.title}\n            </span>\n          }\n        />\n      </div>\n    );\n  }\n\n  function handleClick(e: React.MouseEvent) {\n    e.stopPropagation();\n    onClick?.(event);\n    detailsToggle.closeIfToggled();\n  }\n\n  function handleKeyDown(e: React.KeyboardEvent) {\n    if (e.key !== \"Enter\" && e.key !== \" \") {\n      return;\n    }\n    e.preventDefault();\n    onClick?.(event);\n  }\n\n  function handleAllDayMouseMove(e: React.MouseEvent) {\n    const target = e.currentTarget as HTMLElement;\n    const rect = target.getBoundingClientRect();\n    const offsetX = e.clientX - rect.left;\n    const width = rect.width;\n\n    if (spanStart && offsetX <= ALL_DAY_RESIZE_HOTZONE_PX) {\n      target.style.setProperty(\"--cursor\", \"col-resize\");\n      return;\n    }\n\n    if (spanEnd && offsetX >= width - ALL_DAY_RESIZE_HOTZONE_PX) {\n      target.style.setProperty(\"--cursor\", \"col-resize\");\n      return;\n    }\n\n    target.style.removeProperty(\"--cursor\");\n  }\n\n  function handleAllDayPointerDown(e: React.PointerEvent<HTMLElement>) {\n    detailsToggle.notePress();\n    if (!onResizePointerDown) return;\n\n    const rect = e.currentTarget.getBoundingClientRect();\n    const offsetX = e.clientX - rect.left;\n    const width = rect.width;\n\n    if (spanStart && offsetX <= ALL_DAY_RESIZE_HOTZONE_PX) {\n      e.stopPropagation();\n      onResizePointerDown(e, event, \"left\");\n      return;\n    }\n\n    if (spanEnd && offsetX >= width - ALL_DAY_RESIZE_HOTZONE_PX) {\n      e.stopPropagation();\n      onResizePointerDown(e, event, \"right\");\n      return;\n    }\n\n    // Middle area: initiate drag (move)\n    e.stopPropagation();\n    onResizePointerDown(e, event, \"move\");\n  }\n\n  function handleContextMenu(e: React.MouseEvent) {\n    e.preventDefault();\n    e.stopPropagation();\n    setContextMenu({ x: e.clientX, y: e.clientY });\n    onContextMenuOpenChange?.(true);\n  }\n\n  const eventElement = (\n    <div\n      ref={eventRef}\n      role=\"button\"\n      tabIndex={0}\n      aria-label={getEventLabel(event, hourCycle, locale)}\n      aria-pressed={isSelected ?? false}\n      {...detailsToggle.triggerProps}\n      data-event-id={event.id}\n      onClick={handleClick}\n      onKeyDown={handleKeyDown}\n      onContextMenu={handleContextMenu}\n      onMouseMove={handleAllDayMouseMove}\n      onPointerDown={handleAllDayPointerDown}\n      className={cn(\n        \"relative h-6 px-2 py-0.5 cursor-default\",\n        \"hover:z-10 focus:outline-none\",\n        EVENT_FOCUS_RING_CLASS,\n        \"overflow-hidden select-none flex items-center gap-1\",\n        spanStart && \"rounded-l-md\",\n        spanEnd && \"rounded-r-md\",\n        isSelected && \"z-20\",\n        className,\n      )}\n      style={\n        titleOffsetPercent > 0\n          ? { paddingLeft: `${titleOffsetPercent}%` }\n          : undefined\n      }\n    >\n      {/* Solid background layer to prevent transparency bleed-through */}\n      <div\n        className={cn(\n          \"absolute inset-0 bg-white dark:bg-[#191919]\",\n          spanStart && \"rounded-l-md\",\n          spanEnd && \"rounded-r-md\",\n        )}\n      />\n\n      {/* Colored background layer - uses border color when selected */}\n      <div\n        className={cn(\n          \"absolute inset-0\",\n          isSelected ? styles.border : styles.bg,\n          spanStart && \"rounded-l-md\",\n          spanEnd && \"rounded-r-md\",\n          eventIsPast && !isSelected && \"opacity-60\",\n        )}\n      />\n\n      {/* Left border - hidden when selected (merges with bg) */}\n      {spanStart && !isSelected && (\n        <div\n          className={cn(\n            \"absolute left-0 top-0 bottom-0 w-[4px] dark:bg-white dark:mix-blend-overlay\",\n            spanStart && \"rounded-l-md\",\n            styles.border,\n            eventIsPast && \"opacity-60\",\n          )}\n        />\n      )}\n      <EventContentSlot\n        {...contentProps}\n        className={slotClassName}\n        fallback={\n          <>\n            <span\n              className={cn(\n                \"relative font-medium text-[0.625rem] leading-tight whitespace-nowrap\",\n                spanStart && \"pl-1\",\n                isSelected\n                  ? \"text-white dark:text-white\"\n                  : cn(\n                      styles.text,\n                      \"dark:text-white/80\",\n                      eventIsPast && \"opacity-60\",\n                    ),\n              )}\n            >\n              {event.title}\n            </span>\n            {hasStartTime && (\n              <span\n                className={cn(\n                  \"relative text-[0.625rem] leading-tight whitespace-nowrap shrink-0\",\n                  isSelected\n                    ? \"text-white dark:text-white\"\n                    : cn(\n                        styles.text,\n                        \"dark:text-white dark:mix-blend-overlay\",\n                        eventIsPast && \"opacity-60\",\n                      ),\n                )}\n              >\n                {startTimeLabel}\n              </span>\n            )}\n          </>\n        }\n      />\n    </div>\n  );\n\n  return (\n    <>\n      {eventElement}\n      {showPopover && (\n        <EventDetailPopover\n          event={event}\n          id={detailsToggle.detailsId}\n          anchor={isDayView ? dayViewAnchor : eventRef}\n          triggerRef={eventRef}\n          onEventChange={onEventChange}\n          onClose={() => onEventPopoverClose?.(event.id)}\n          onExpand={onEventPopoverExpand}\n          side={isDayView ? \"left\" : \"right\"}\n          align=\"start\"\n          collisionPaddingTop={isDayView ? headerBottom : undefined}\n        />\n      )}\n      {contextMenu && (\n        <EventContextMenu\n          event={event}\n          position={contextMenu}\n          onClose={closeContextMenu}\n          onEventChange={onEventChange}\n        />\n      )}\n    </>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-panel.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport {\n  Check,\n  ChevronDown,\n  CircleHelp,\n  Copy,\n  MoreHorizontal,\n  SquareDashed,\n  TabletSmartphone,\n  Trash2,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useInlineEdit } from \"@/hooks/use-inline-edit\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuShortcut,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { EventDetailAiNotes } from \"./event-detail-ai-notes\";\nimport { EventDetailAvailability } from \"./event-detail-availability\";\nimport { EventDetailCalendar } from \"./event-detail-calendar\";\nimport { EventDetailConferencing } from \"./event-detail-conferencing\";\nimport { EventDetailDescription } from \"./event-detail-description\";\nimport { EventDetailLinks } from \"./event-detail-links\";\nimport { EventDetailLocation } from \"./event-detail-location\";\nimport {\n  EVENT_ACTION_KEYS,\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_BUTTON_CLASS,\n  EVENT_DETAIL_INPUT_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MENU_ITEM_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailDivider,\n  EventDetailGroup,\n  closeMenuOnEscape,\n  stopEscapePropagation,\n} from \"./event-detail-parts\";\nimport { EventDetailParticipants } from \"./event-detail-participants\";\nimport { EventDetailRecurrence } from \"./event-detail-recurrence\";\nimport { EventDetailReminders } from \"./event-detail-reminders\";\nimport { EventDetailAllDay, EventDetailTime } from \"./event-detail-time\";\nimport { EventDetailTimezone } from \"./event-detail-timezone\";\nimport type { DetailedCalendarEvent, EventKind } from \"./week-view-types\";\n\n/**\n * Props for EventDetailPanel. `TEvent` is the app's event type; detail fields\n * it doesn't set show placeholders, and edits keep its other fields.\n */\ninterface EventDetailPanelProps<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n> {\n  event: TEvent;\n  onEventChange?: (event: TEvent) => void;\n  /**\n   * Shows the previous event of a repeating series (the repeat row's left\n   * arrow). Leave it out at the series' start: the arrow is disabled then.\n   */\n  onPrevWeek?: () => void;\n  /**\n   * Shows the next event of a repeating series (the right arrow). Leave it\n   * out at the series' end: the arrow is disabled then.\n   */\n  onNextWeek?: () => void;\n  /** The \"...\" menu's Cut: keeps a copy for pasting and deletes the event. Disabled without it */\n  onCut?: () => void;\n  /** The \"...\" menu's Copy: keeps a copy of the event for pasting. Disabled without it */\n  onCopy?: () => void;\n  /** The \"...\" menu's Duplicate: adds a copy at the same time. Disabled without it */\n  onDuplicate?: () => void;\n  /** The \"...\" menu's Delete. Disabled without it */\n  onDelete?: () => void;\n  /** Extra action buttons rendered in the header row (after the \"...\" menu). */\n  headerActions?: React.ReactNode;\n  /** When true, focuses and selects the title input once (e.g. for a just-created event). */\n  autoFocusTitle?: boolean;\n  /** Called after the title input was auto-focused, so the request is not repeated. */\n  onTitleAutoFocused?: () => void;\n}\n\n/** Event kinds in the header menu's order */\nconst EVENT_KINDS: EventKind[] = [\n  \"event\",\n  \"focus-time\",\n  \"out-of-office\",\n  \"birthday\",\n];\n\n/** Name of each event kind in the header menu */\nconst EVENT_KIND_LABELS: Record<EventKind, string> = {\n  event: \"Event\",\n  \"focus-time\": \"Focus time\",\n  \"out-of-office\": \"Out of office\",\n  birthday: \"Birthday\",\n};\n\n/** Help shown beside a kind in the header menu */\nconst EVENT_KIND_TOOLTIPS: Partial<Record<EventKind, string>> = {\n  \"focus-time\":\n    \"Create a focus time event with the option to automatically decline meetings during this time. Available for work and school accounts.\",\n  \"out-of-office\":\n    \"Create an out of office (OOO) event with the option to automatically decline meetings during this time. Available for work and school accounts.\",\n  birthday:\n    \"Create a birthday event to keep track of a person's upcoming birthdays. Birthdays from your Google Contacts may appear on a separate Birthday calendar.\",\n};\n\nfunction EventKindHelpIcon({ tooltip }: { tooltip?: string }) {\n  const [tooltipPos, setTooltipPos] = React.useState<{\n    top: number;\n    left: number;\n  } | null>(null);\n\n  if (!tooltip) {\n    return null;\n  }\n\n  function handleMouseEnter(e: React.MouseEvent<HTMLSpanElement>) {\n    const rect = e.currentTarget.getBoundingClientRect();\n    setTooltipPos({ top: rect.top + rect.height / 2, left: rect.left });\n  }\n\n  function handleMouseLeave() {\n    setTooltipPos(null);\n  }\n\n  return (\n    <span\n      className=\"ml-auto shrink-0 opacity-0 group-hover/item:opacity-100 transition-opacity\"\n      onClick={(e) => e.stopPropagation()}\n      onPointerDown={(e) => e.stopPropagation()}\n      onMouseEnter={handleMouseEnter}\n      onMouseLeave={handleMouseLeave}\n    >\n      <CircleHelp className=\"size-3.5 text-white\" />\n      {tooltipPos &&\n        ReactDOM.createPortal(\n          <div\n            className=\"pointer-events-none fixed z-[100] max-w-[240px] rounded-sm bg-[#252525] border border-[#303030] px-2 py-1 text-xs text-white shadow-md\"\n            style={{\n              top: tooltipPos.top,\n              left: tooltipPos.left - 8,\n              transform: \"translate(-100%, -50%)\",\n            }}\n          >\n            {tooltip}\n          </div>,\n          document.body,\n        )}\n    </span>\n  );\n}\n\n/**\n * The muted \"All-day  Time zone  Repeat\" line a plain timed event shows\n * under its date. Clicking it opens the three rows.\n */\nfunction EventDetailOptionsRow({ onExpand }: { onExpand: () => void }) {\n  const labelClass = cn(\n    EVENT_DETAIL_PLACEHOLDER_CLASS,\n    \"group-hover/options:text-[#A5A5A5] dark:group-hover/options:text-[#636363]\",\n  );\n\n  return (\n    <div\n      className={cn(\n        \"flex items-center pl-[36px]\",\n        EVENT_DETAIL_ROW_HEIGHT_CLASS,\n      )}\n    >\n      <div\n        className=\"group/options flex h-[31px] cursor-default items-center gap-[18px] rounded-md px-[9px] hover:bg-[#F5F5F5] dark:hover:bg-[#242424]\"\n        onClick={onExpand}\n      >\n        <span className={labelClass}>All-day</span>\n        <span className={labelClass}>Time zone</span>\n        <span className={labelClass}>Repeat</span>\n      </div>\n    </div>\n  );\n}\n\n/**\n * Notion Calendar-style event details: the kind menu, the title, then one\n * section per field (time, time zone, repeat, participants, conferencing,\n * AI notes, location, links, description, calendar, availability,\n * reminders) in Notion's order and groups. Each section edits its own\n * fields through `onEventChange`.\n */\nexport function EventDetailPanel<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({\n  event,\n  onEventChange,\n  onPrevWeek,\n  onNextWeek,\n  onCut,\n  onCopy,\n  onDuplicate,\n  onDelete,\n  headerActions,\n  autoFocusTitle,\n  onTitleAutoFocused,\n}: EventDetailPanelProps<TEvent>) {\n  const kind = event.kind ?? \"event\";\n  const [kindMenuOpen, setKindMenuOpen] = React.useState(false);\n  const [hoveredOther, setHoveredOther] = React.useState(false);\n  /** Whether the compact \"All-day / Time zone / Repeat\" row is expanded into individual rows. */\n  const [optionsExpanded, setOptionsExpanded] = React.useState(false);\n\n  const titleRef = React.useRef<HTMLInputElement>(null);\n  const title = useInlineEdit({\n    inputRef: titleRef,\n    value: event.title,\n    onInput: (text) => onEventChange?.({ ...event, title: text }),\n    onRestore: (text) => onEventChange?.({ ...event, title: text }),\n    onCommit: (text) => {\n      const trimmed = text.trim();\n      // Only spaces: back to the title from before editing. Deleting the\n      // whole title still clears it.\n      if (text && !trimmed) return null;\n      if (trimmed !== text) onEventChange?.({ ...event, title: trimmed });\n      return trimmed;\n    },\n  });\n\n  // Reset expanded options when switching to a different event\n  React.useEffect(() => {\n    setOptionsExpanded(false);\n  }, [event.id]);\n\n  // Focus + select the title on request so a new event can be named right away.\n  // Deferred a frame so a popover host has been positioned before focusing.\n  React.useEffect(() => {\n    if (!autoFocusTitle) return;\n    const frame = requestAnimationFrame(() => {\n      titleRef.current?.focus({ preventScroll: true });\n      titleRef.current?.select();\n      onTitleAutoFocused?.();\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [autoFocusTitle, onTitleAutoFocused, titleRef]);\n\n  const selectKind = (next: EventKind) => {\n    if (next === kind) return;\n    onEventChange?.({ ...event, kind: next });\n  };\n\n  const otherKinds = EVENT_KINDS.filter((k) => k !== kind);\n  const showOptionRows =\n    optionsExpanded ||\n    event.isAllDay ||\n    Boolean(\n      event.recurrenceRule ??\n      event.recurrence ??\n      event.timeZone ??\n      event.timezone,\n    );\n\n  const conferencingSection = (\n    <EventDetailConferencing\n      key=\"conferencing\"\n      event={event}\n      onEventChange={onEventChange}\n    />\n  );\n  const aiNotesSection = (\n    <EventDetailAiNotes\n      key=\"ai-notes\"\n      event={event}\n      onEventChange={onEventChange}\n    />\n  );\n\n  return (\n    <div\n      className={cn(\n        \"flex flex-col pt-3 text-sm font-medium\",\n        EVENT_DETAIL_TEXT_CLASS,\n      )}\n    >\n      {/* Header: kind menu, \"...\" menu and the host's actions */}\n      <div\n        className={cn(\n          \"flex items-center justify-between pr-3 pl-2\",\n          EVENT_DETAIL_ROW_HEIGHT_CLASS,\n        )}\n      >\n        <DropdownMenu\n          open={kindMenuOpen}\n          onOpenChange={(open) => {\n            setKindMenuOpen(open);\n            if (open) setHoveredOther(false);\n          }}\n        >\n          <DropdownMenuTrigger asChild>\n            <button\n              type=\"button\"\n              // Read-only details show the kind without its menu\n              disabled={!onEventChange}\n              className={cn(\n                \"flex h-7 items-center gap-[7px] px-[7px]\",\n                EVENT_DETAIL_HOVER_BORDER_CLASS,\n                !onEventChange &&\n                  \"hover:border-transparent dark:hover:border-transparent\",\n                kindMenuOpen && \"bg-[#252525] text-white\",\n              )}\n            >\n              {EVENT_KIND_LABELS[kind]}\n              <ChevronDown\n                className={cn(\n                  \"size-4\",\n                  kindMenuOpen ? \"text-[#595959]\" : EVENT_DETAIL_MUTED_CLASS,\n                )}\n              />\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent\n            align=\"start\"\n            side=\"left\"\n            sideOffset={12}\n            alignOffset={-4}\n            className={cn(\"min-w-[180px]\", EVENT_DETAIL_MENU_CLASS)}\n            onMouseLeave={() => setHoveredOther(false)}\n            onKeyDown={closeMenuOnEscape(() => setKindMenuOpen(false))}\n          >\n            <DropdownMenuItem\n              className={cn(\n                \"group/item text-xs text-white focus:bg-[#303030] focus:text-white\",\n                !hoveredOther && \"bg-[#303030]\",\n              )}\n              onClick={() => selectKind(kind)}\n              onMouseEnter={() => setHoveredOther(false)}\n            >\n              <Check className=\"size-3.5\" />\n              <span className=\"flex-1\">{EVENT_KIND_LABELS[kind]}</span>\n              <EventKindHelpIcon tooltip={EVENT_KIND_TOOLTIPS[kind]} />\n            </DropdownMenuItem>\n            <DropdownMenuSeparator className=\"bg-[#303030]\" />\n            {otherKinds.map((other) => (\n              <DropdownMenuItem\n                key={other}\n                className=\"group/item text-xs text-white focus:bg-[#303030] focus:text-white pl-8\"\n                onClick={() => selectKind(other)}\n                onMouseEnter={() => setHoveredOther(true)}\n              >\n                <span className=\"flex-1\">{EVENT_KIND_LABELS[other]}</span>\n                <EventKindHelpIcon tooltip={EVENT_KIND_TOOLTIPS[other]} />\n              </DropdownMenuItem>\n            ))}\n          </DropdownMenuContent>\n        </DropdownMenu>\n        <div className=\"flex items-center gap-0.5\">\n          <DropdownMenu>\n            <DropdownMenuTrigger asChild>\n              <Button\n                variant=\"ghost\"\n                size=\"icon\"\n                aria-label=\"More actions\"\n                className={cn(\n                  \"size-7\",\n                  EVENT_DETAIL_ICON_BUTTON_CLASS,\n                  EVENT_DETAIL_SECONDARY_CLASS,\n                )}\n              >\n                <MoreHorizontal className=\"size-[18px]\" />\n              </Button>\n            </DropdownMenuTrigger>\n            <DropdownMenuContent\n              align=\"start\"\n              side=\"left\"\n              className={cn(\"min-w-[180px]\", EVENT_DETAIL_MENU_CLASS)}\n              onKeyDown={stopEscapePropagation}\n            >\n              <DropdownMenuItem\n                disabled={!onCut}\n                aria-keyshortcuts={EVENT_ACTION_KEYS.cut.aria}\n                className={EVENT_DETAIL_MENU_ITEM_CLASS}\n                onClick={onCut}\n              >\n                <SquareDashed className=\"size-3.5\" />\n                Cut\n                <DropdownMenuShortcut aria-hidden className=\"text-white/40\">\n                  {EVENT_ACTION_KEYS.cut.label}\n                </DropdownMenuShortcut>\n              </DropdownMenuItem>\n              <DropdownMenuItem\n                disabled={!onCopy}\n                aria-keyshortcuts={EVENT_ACTION_KEYS.copy.aria}\n                className={EVENT_DETAIL_MENU_ITEM_CLASS}\n                onClick={onCopy}\n              >\n                <TabletSmartphone className=\"size-3.5\" />\n                Copy\n                <DropdownMenuShortcut aria-hidden className=\"text-white/40\">\n                  {EVENT_ACTION_KEYS.copy.label}\n                </DropdownMenuShortcut>\n              </DropdownMenuItem>\n              <DropdownMenuItem\n                disabled={!onDuplicate}\n                aria-keyshortcuts={EVENT_ACTION_KEYS.duplicate.aria}\n                className={EVENT_DETAIL_MENU_ITEM_CLASS}\n                onClick={onDuplicate}\n              >\n                <Copy className=\"size-3.5\" />\n                Duplicate\n                <DropdownMenuShortcut aria-hidden className=\"text-white/40\">\n                  {EVENT_ACTION_KEYS.duplicate.label}\n                </DropdownMenuShortcut>\n              </DropdownMenuItem>\n              <DropdownMenuSeparator className=\"bg-[#303030]\" />\n              <DropdownMenuItem\n                disabled={!onDelete}\n                aria-keyshortcuts={EVENT_ACTION_KEYS.delete.aria}\n                className=\"text-xs text-[#E56458] focus:!bg-[#DE5551] focus:!text-white focus:[&>svg]:!text-white focus:[&>[data-slot=dropdown-menu-shortcut]]:!text-white\"\n                onClick={onDelete}\n              >\n                <Trash2 className=\"size-3.5 text-[#E56458]\" />\n                Delete\n                <DropdownMenuShortcut\n                  aria-hidden\n                  className=\"text-white/40 tracking-normal\"\n                >\n                  {EVENT_ACTION_KEYS.delete.label}\n                </DropdownMenuShortcut>\n              </DropdownMenuItem>\n            </DropdownMenuContent>\n          </DropdownMenu>\n          {headerActions}\n        </div>\n      </div>\n\n      {/* Title */}\n      <div className=\"mt-1.5 flex flex-col px-2 pb-2\">\n        <input\n          ref={titleRef}\n          {...title.inputProps}\n          type=\"text\"\n          placeholder=\"Title\"\n          readOnly={!onEventChange}\n          className={cn(\n            \"h-[35px] px-[7px] placeholder:text-[#ABABA9] dark:placeholder:text-[#595959]\",\n            EVENT_DETAIL_INPUT_CLASS,\n          )}\n        />\n      </div>\n\n      <EventDetailDivider />\n\n      {/* When: time and date, then all-day, time zone and repeat */}\n      <EventDetailGroup name=\"when\">\n        <EventDetailTime event={event} onEventChange={onEventChange} />\n        {showOptionRows ? (\n          <>\n            <div\n              className={cn(\n                \"flex flex-col justify-center\",\n                EVENT_DETAIL_ROW_HEIGHT_CLASS,\n              )}\n            >\n              <EventDetailAllDay event={event} onEventChange={onEventChange} />\n            </div>\n            <EventDetailTimezone event={event} onEventChange={onEventChange} />\n            <EventDetailRecurrence\n              event={event}\n              onEventChange={onEventChange}\n              onPrevious={onPrevWeek}\n              onNext={onNextWeek}\n            />\n          </>\n        ) : (\n          <EventDetailOptionsRow onExpand={() => setOptionsExpanded(true)} />\n        )}\n      </EventDetailGroup>\n\n      <EventDetailDivider />\n\n      {/* Who and where */}\n      <EventDetailGroup name=\"who\">\n        <EventDetailParticipants event={event} onEventChange={onEventChange} />\n        {/* With a call, Notion moves the meeting-note button above it; the\n            keys keep both mounted (and focused) when they swap */}\n        {event.conference\n          ? [aiNotesSection, conferencingSection]\n          : [conferencingSection, aiNotesSection]}\n        <EventDetailLocation event={event} onEventChange={onEventChange} />\n      </EventDetailGroup>\n\n      <EventDetailDivider />\n\n      <EventDetailGroup name=\"links\">\n        <EventDetailLinks event={event} onEventChange={onEventChange} />\n      </EventDetailGroup>\n\n      <EventDetailDivider />\n\n      {/* At least one 35px row, empty or not */}\n      <EventDetailGroup name=\"description\" className=\"min-h-[51px]\">\n        <EventDetailDescription event={event} onEventChange={onEventChange} />\n      </EventDetailGroup>\n\n      <EventDetailDivider />\n\n      {/* Calendar, availability and reminders */}\n      <EventDetailGroup name=\"calendar\">\n        <EventDetailCalendar event={event} onEventChange={onEventChange} />\n        <EventDetailAvailability event={event} onEventChange={onEventChange} />\n        <EventDetailReminders event={event} onEventChange={onEventChange} />\n      </EventDetailGroup>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-parts.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\n\nimport { cn } from \"@/lib/utils\";\n\n/** Main text: values, the title, the header's kind (Notion: #D4D4D4 dark) */\nexport const EVENT_DETAIL_TEXT_CLASS = \"text-[#32302C] dark:text-[#D4D4D4]\";\n\n/** Secondary text: a duration, an offset (\"GMT-3\"), a rule's \" on Thu\", \"before\" */\nexport const EVENT_DETAIL_SECONDARY_CLASS =\n  \"text-[#787774] dark:text-[#7F7F7F]\";\n\n/** Muted icons: a row's leading icon, the arrow between times, chevrons */\nexport const EVENT_DETAIL_MUTED_CLASS = \"text-[#C7C5C1] dark:text-[#595959]\";\n\n/** Placeholder text of an empty field (\"Location\", \"Description\") */\nexport const EVENT_DETAIL_PLACEHOLDER_CLASS =\n  \"text-[#ABABA9] dark:text-[#595959]\";\n\n/** Height of one row of the panel (Notion: 35px, at 14px medium text) */\nexport const EVENT_DETAIL_ROW_HEIGHT_CLASS = \"min-h-[35px]\";\n\n/** Size and color of a row's leading icon */\nexport const EVENT_DETAIL_ICON_CLASS = cn(\n  \"size-4 shrink-0\",\n  EVENT_DETAIL_MUTED_CLASS,\n);\n\n/** Border that shows on hover, for dropdown triggers and clickable rows */\nexport const EVENT_DETAIL_HOVER_BORDER_CLASS =\n  \"rounded-sm border border-transparent hover:border-[#E8E8E4] dark:hover:border-[#373737]\";\n\n/** A standalone inline-editable input (the title): hover border, filled on focus */\nexport const EVENT_DETAIL_INPUT_CLASS = cn(\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  \"bg-transparent outline-none focus:border-[#F5F5F5] focus:bg-[#F5F5F5] dark:focus:border-[#242424] dark:focus:bg-[#242424]\",\n);\n\n/**\n * Wrapper of a grouped inline-editable input (icon + input, or arrow +\n * input + label): it draws the border and fill, the input inside gets\n * `EVENT_DETAIL_GROUPED_INPUT_CLASS`\n */\nexport const EVENT_DETAIL_INPUT_GROUP_CLASS = cn(\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  \"cursor-text has-[:focus]:border-[#F5F5F5] has-[:focus]:bg-[#F5F5F5] dark:has-[:focus]:border-[#242424] dark:has-[:focus]:bg-[#242424]\",\n);\n\n/** The input inside an `EVENT_DETAIL_INPUT_GROUP_CLASS` wrapper */\nexport const EVENT_DETAIL_GROUPED_INPUT_CLASS =\n  \"border-none bg-transparent p-0 outline-none\";\n\n/** An icon button (the \"...\" menu): its hover border blends into its fill */\nexport const EVENT_DETAIL_ICON_BUTTON_CLASS =\n  \"border border-transparent hover:border-[#F5F5F5] hover:bg-[#F5F5F5] dark:hover:border-[#242424] dark:hover:bg-[#242424]\";\n\n/** Menu surface: menus are dark in both themes */\nexport const EVENT_DETAIL_MENU_CLASS = \"bg-[#252525] border-[#303030]\";\n\n/** A menu item on `EVENT_DETAIL_MENU_CLASS` */\nexport const EVENT_DETAIL_MENU_ITEM_CLASS =\n  \"text-xs text-white focus:!bg-[#303030] focus:!text-white\";\n\n/** \"Soon\" badge of a menu item that isn't built yet, on `EVENT_DETAIL_MENU_CLASS` */\nexport const EVENT_DETAIL_MENU_SOON_CLASS =\n  \"ml-auto rounded bg-white/10 px-1.5 py-0.5 text-[10px] leading-none font-medium text-white/60\";\n\n/**\n * Keys of the event actions: shown beside them in the right-click menu and\n * the details' \"...\" menu (`label`), and given to assistive tech as\n * `aria-keyshortcuts` (`aria`). `useCalendarShortcuts` handles them.\n */\nexport const EVENT_ACTION_KEYS = {\n  cut: { label: \"⌘X\", aria: \"Meta+X Control+X\" },\n  copy: { label: \"⌘C\", aria: \"Meta+C Control+C\" },\n  duplicate: { label: \"⌘D\", aria: \"Meta+D Control+D\" },\n  delete: { label: \"delete\", aria: \"Delete Backspace\" },\n} as const;\n\n/** Main text of a menu item */\nexport const EVENT_DETAIL_MENU_TEXT_CLASS = \"text-[#E0E0E0]\";\n\n/** Secondary text in a menu: an email under a name, an address, a hint */\nexport const EVENT_DETAIL_MENU_SECONDARY_CLASS = \"text-[#8B8B8B]\";\n\n/** Surface of a menu opened from the bottom of the panel (with `EVENT_DETAIL_MENU_CLASS`) */\nexport const PANEL_MENU_SURFACE_CLASS = \"rounded-lg p-1.5 shadow-lg\";\n\n/** An item of a `PANEL_MENU_SURFACE_CLASS` menu: 32px tall, highlight inset */\nexport const PANEL_MENU_ITEM_CLASS =\n  \"group/item h-8 gap-0 rounded-md px-2 py-0 text-xs text-[#CCCCCC] focus:!bg-[#303030] focus:!text-[#F0F0F0]\";\n\n/**\n * The current item of a `PANEL_MENU_SURFACE_CLASS` menu while nothing else\n * is highlighted: Notion opens its menus with the current value highlighted\n */\nexport const PANEL_MENU_ITEM_CURRENT_CLASS = \"bg-[#303030] text-[#F0F0F0]\";\n\n/** A muted heading in a `PANEL_MENU_SURFACE_CLASS` menu (an account, \"Event color\") */\nexport const PANEL_MENU_LABEL_CLASS =\n  \"flex h-8 items-center pr-2 pl-[31px] text-xs text-[#848484] select-none\";\n\n/** A panel dropdown trigger while its menu is open: filled, border blended in */\nexport const PANEL_TRIGGER_OPEN_CLASS =\n  \"border-[#F5F5F5] bg-[#F5F5F5] hover:border-[#F5F5F5] dark:border-[#252525] dark:bg-[#252525] dark:hover:border-[#252525]\";\n\n/** A row's 32px box, from 8px off the panel's edges, with the icon column at 26px */\nexport const ROW_BOX_CLASS =\n  \"flex h-8 min-w-0 flex-1 items-center gap-[11px] pr-2 pl-[9px]\";\n\n/**\n * Link text in the details panel: a faint underline that takes the text\n * color on hover, as Notion's links do\n */\nexport const EVENT_DETAIL_LINK_CLASS =\n  \"underline decoration-[#EEEEEE] decoration-1 underline-offset-2 hover:decoration-current dark:decoration-[#242424]\";\n\n/** Gap in px between a menu opened from the panel and the panel's left edge */\nconst PANEL_MENU_GAP = 4;\n\n/** Gap in px between a tooltip and the element it describes */\nconst TOOLTIP_GAP = 12;\n\n/**\n * Containers a floating layer of the details mounts in: a dialog, sheet or\n * drawer, but not the details popover (also a dialog), which is transformed\n * and would clip and misplace a layer beside it\n */\nconst PORTAL_CONTAINER_SELECTOR =\n  '[role=\"dialog\"]:not([data-calendar-popover]), [role=\"alertdialog\"]';\n\n/**\n * Keydown handler for a panel menu whose library closes it on Escape: the\n * key stops there, instead of also reaching the calendar's shortcut that\n * deselects the event\n */\nexport function stopEscapePropagation(e: React.KeyboardEvent) {\n  if (e.key === \"Escape\") e.stopPropagation();\n}\n\n/**\n * `onKeyDown` for a details menu's content: Escape closes only the menu.\n * The calendar's global Escape would also deselect the event, so the key\n * stops here, and the menu is closed through its `open` state, which works\n * whichever library's own Escape handling runs.\n */\nexport function closeMenuOnEscape(close: () => void) {\n  return (e: React.KeyboardEvent) => {\n    if (e.key !== \"Escape\") return;\n    e.stopPropagation();\n    close();\n  };\n}\n\n/**\n * `sideOffset` that puts a `side=\"left\"` menu just outside the panel's left\n * edge, whichever column its trigger sits in, as Notion lines up its menus\n */\nexport function getPanelMenuSideOffset(\n  triggerRef: React.RefObject<HTMLElement | null>,\n  sectionRef: React.RefObject<HTMLElement | null>,\n): number {\n  const trigger = triggerRef.current;\n  const section = sectionRef.current;\n  if (!trigger || !section) return PANEL_MENU_GAP;\n  return (\n    trigger.getBoundingClientRect().left -\n    section.getBoundingClientRect().left +\n    PANEL_MENU_GAP\n  );\n}\n\n/**\n * Where a floating layer opened from the details (a suggestion list, a\n * menu) mounts: inside the dialog, sheet or drawer that holds `node`, since\n * a modal dialog turns off pointer events on the rest of the page, else the\n * body. The same rule the details popover follows for itself.\n */\nexport function getEventDetailPortalContainer(\n  node: Element | null | undefined,\n): HTMLElement {\n  return node?.closest<HTMLElement>(PORTAL_CONTAINER_SELECTOR) ?? document.body;\n}\n\n/**\n * A tooltip centered above a rectangle (from `getBoundingClientRect()`),\n * shown while `rect` is set. It ignores the pointer, so hovering it never\n * keeps it open.\n */\nexport function EventDetailTooltip({\n  rect,\n  children,\n}: {\n  rect: DOMRect | null;\n  children: React.ReactNode;\n}) {\n  if (!rect) return null;\n\n  return ReactDOM.createPortal(\n    <div\n      role=\"tooltip\"\n      className=\"pointer-events-none fixed z-[100] w-max max-w-[232px] -translate-x-1/2 -translate-y-full rounded-md border border-transparent bg-[#252525] px-2.5 py-1.5 text-xs leading-[18px] text-[#F0F0F0] shadow-md dark:border-[#303030]\"\n      style={{\n        left: rect.left + rect.width / 2,\n        top: rect.top - TOOLTIP_GAP,\n      }}\n    >\n      {children}\n    </div>,\n    document.body,\n  );\n}\n\n/**\n * Props for EventDetailSection (the container; a section's own props are\n * `EventDetailSectionProps` from `week-view-types`)\n */\ninterface EventDetailSectionContainerProps extends React.ComponentProps<\"div\"> {\n  /** Names the section in `data-section`, e.g. \"time\" or \"location\" */\n  name: string;\n}\n\n/**\n * One section of the details panel. Sections stack their rows; the panel\n * draws the dividers between groups of sections.\n */\nexport function EventDetailSection({\n  name,\n  className,\n  ...props\n}: EventDetailSectionContainerProps) {\n  return (\n    <div\n      data-section={name}\n      className={cn(\"flex flex-col\", className)}\n      {...props}\n    />\n  );\n}\n\n/**\n * Line between groups of sections, edge to edge\n */\nexport function EventDetailDivider({ className }: { className?: string }) {\n  return (\n    <div\n      role=\"separator\"\n      className={cn(\n        \"border-t border-[#EEEEEE] dark:border-[#262626]\",\n        className,\n      )}\n    />\n  );\n}\n\n/**\n * Props for EventDetailGroup\n */\ninterface EventDetailGroupProps extends React.ComponentProps<\"div\"> {\n  /** Names the group in `data-group`, e.g. \"when\" or \"calendar\" */\n  name: string;\n}\n\n/**\n * Sections between two dividers, with Notion's 8px above the first row and\n * below the last\n */\nexport function EventDetailGroup({\n  name,\n  className,\n  ...props\n}: EventDetailGroupProps) {\n  return (\n    <div\n      data-group={name}\n      className={cn(\"flex flex-col py-2\", className)}\n      {...props}\n    />\n  );\n}\n\n/**\n * Props for EventDetailRow\n */\ninterface EventDetailRowProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\"\n> {\n  /** Leading icon, drawn muted in the icon column. Leave out to indent only */\n  icon?: React.ComponentType<{ className?: string }>;\n  /** Replaces `icon` with any element (a switch, a color swatch) */\n  leading?: React.ReactNode;\n  /** Controls at the end of the row, e.g. previous/next buttons */\n  actions?: React.ReactNode;\n  children?: React.ReactNode;\n}\n\n/**\n * A row with the icon column: a 16px icon (or `leading`) centered 26px from\n * the panel's left edge, the content from 45px, and optional `actions` at\n * the end. Every row of the panel lines its content up on the same column.\n * Text size and weight come from the panel (14px medium).\n */\nexport function EventDetailRow({\n  icon: Icon,\n  leading,\n  actions,\n  className,\n  children,\n  ...props\n}: EventDetailRowProps) {\n  return (\n    <div\n      className={cn(\n        \"flex items-center gap-[11px] pr-4 pl-[18px]\",\n        EVENT_DETAIL_ROW_HEIGHT_CLASS,\n        className,\n      )}\n      {...props}\n    >\n      <span className=\"flex w-4 shrink-0 items-center justify-center\">\n        {leading ?? (Icon && <Icon className={EVENT_DETAIL_ICON_CLASS} />)}\n      </span>\n      <div className=\"flex min-w-0 flex-1 items-center gap-1.5\">{children}</div>\n      {actions && <div className=\"flex shrink-0 items-center\">{actions}</div>}\n    </div>\n  );\n}\n\n/**\n * Props for EventDetailPlaceholderRow\n */\ninterface EventDetailPlaceholderRowProps {\n  /** Muted leading icon */\n  icon?: React.ComponentType<{ className?: string }>;\n  /** Muted label, e.g. \"Location\" */\n  label: string;\n  /** Called when the row is clicked; the row is a button when set */\n  onClick?: () => void;\n  className?: string;\n}\n\n/**\n * Notion's empty field: muted icon and placeholder label. A section shows it\n * until its field is set.\n */\nexport function EventDetailPlaceholderRow({\n  icon,\n  label,\n  onClick,\n  className,\n}: EventDetailPlaceholderRowProps) {\n  const content = (\n    <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>{label}</span>\n  );\n\n  if (!onClick) {\n    return (\n      <EventDetailRow icon={icon} className={className}>\n        {content}\n      </EventDetailRow>\n    );\n  }\n\n  return (\n    <EventDetailRow icon={icon} className={className}>\n      <button\n        type=\"button\"\n        onClick={onClick}\n        className={cn(\n          \"-mx-2 px-2 py-1.5 text-left\",\n          EVENT_DETAIL_HOVER_BORDER_CLASS,\n        )}\n      >\n        {content}\n      </button>\n    </EventDetailRow>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-time.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { addDays, differenceInCalendarDays } from \"date-fns\";\nimport { Clock9 } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { Switch } from \"@/components/ui/switch\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport { EventDetailDateField } from \"./event-detail-date-field\";\nimport {\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailRow,\n  EventDetailSection,\n} from \"./event-detail-parts\";\nimport { EventDetailTimeField } from \"./event-detail-time-field\";\nimport { formatTime } from \"@/lib/event-utils\";\nimport {\n  applyTimeToDate,\n  endsOnLaterDay,\n  formatDuration,\n  getEndTimeOptions,\n  getStartTimeOptions,\n  hasTimeOfDay,\n  matchEndTimes,\n  matchStartTimes,\n} from \"@/lib/time-input\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** Start hour given to an all-day event switched to timed when it has no times */\nconst DEFAULT_START_HOUR = 9;\n\n/** End hour given to an all-day event switched to timed when it has no times */\nconst DEFAULT_END_HOUR = 10;\n\n/** The clock and arrow of an all-day event, fainter than its times */\nconst ALL_DAY_ICON_CLASS = \"text-[#EEEEEE] dark:text-[#303030]\";\n\n/** The duration of an all-day event, between its icons and its times */\nconst ALL_DAY_DURATION_CLASS = \"text-[#D2D2D2] dark:text-[#373737]\";\n\n/**\n * The arrow between the times: Notion Calendar's is 13px wide and 10.5px\n * tall with 1.25px strokes, flatter than lucide's ArrowRight\n */\nfunction TimeArrow({ className }: { className?: string }) {\n  return (\n    <svg\n      aria-hidden\n      width=\"14\"\n      height=\"12\"\n      viewBox=\"0 0 14 12\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.25}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={cn(\"shrink-0\", className)}\n    >\n      <path d=\"M0.75 6h12.5M8.5 1.5 13.25 6 8.5 10.5\" />\n    </svg>\n  );\n}\n\n/**\n * Start and end time with the duration, then the date, laid out on Notion\n * Calendar's columns: the times' text at 45px and 156px from the panel's\n * edge, the dates' under them. An all-day event shows its times muted and\n * inert (or none, when it has none) and its end date; so does a timed event\n * that ends on a later day. Without `onEventChange`, the fields only show\n * the event.\n */\nexport function EventDetailTime<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const { hourCycle, locale } = useCalendarConfig();\n  const sectionRef = React.useRef<HTMLDivElement>(null);\n  const allDay = event.isAllDay ?? false;\n  const showTimes = !allDay || hasTimeOfDay(event);\n  const showEndDate = allDay || endsOnLaterDay(event.start, event.end);\n  const readOnly = !onEventChange;\n\n  /** \"3 PM\" / \"3:30 PM\", or \"15:00\" / \"15:30\" on a 24-hour clock */\n  const formatTimeValue = React.useCallback(\n    (date: Date) => formatTime(date, hourCycle, locale),\n    [hourCycle, locale],\n  );\n\n  const startMs = event.start.getTime();\n  const endMs = event.end.getTime();\n\n  const getStartOptions = React.useCallback(\n    () => getStartTimeOptions(new Date(startMs), formatTimeValue),\n    [startMs, formatTimeValue],\n  );\n\n  const getEndOptions = React.useCallback(\n    () =>\n      getEndTimeOptions(new Date(startMs), new Date(endMs), formatTimeValue),\n    [startMs, endMs, formatTimeValue],\n  );\n\n  const getStartMatches = React.useCallback(\n    (typed: string) =>\n      matchStartTimes(typed, new Date(startMs), hourCycle, formatTimeValue),\n    [startMs, hourCycle, formatTimeValue],\n  );\n\n  const getEndMatches = React.useCallback(\n    (typed: string) =>\n      matchEndTimes(\n        typed,\n        new Date(startMs),\n        new Date(endMs),\n        hourCycle,\n        formatTimeValue,\n      ),\n    [startMs, endMs, hourCycle, formatTimeValue],\n  );\n\n  /** A new start keeps the duration, as in Notion Calendar */\n  const commitStart = (date: Date) => {\n    onEventChange?.({\n      ...event,\n      start: date,\n      end: new Date(date.getTime() + (endMs - startMs)),\n    });\n    return true;\n  };\n\n  const commitEnd = (date: Date) => {\n    if (date.getTime() <= startMs) return false;\n    onEventChange?.({ ...event, end: date });\n    return true;\n  };\n\n  /** A new start date moves the whole event */\n  const commitStartDate = (day: Date) => {\n    const dayDiff = differenceInCalendarDays(day, event.start);\n    onEventChange?.({\n      ...event,\n      start: addDays(event.start, dayDiff),\n      end: addDays(event.end, dayDiff),\n    });\n    return true;\n  };\n\n  /** A new end date keeps the end time; it can't come before the start */\n  const commitEndDate = (day: Date) => {\n    const end = addDays(event.end, differenceInCalendarDays(day, event.end));\n    const isBeforeStart = allDay\n      ? differenceInCalendarDays(end, event.start) < 0\n      : end.getTime() <= startMs;\n    if (isBeforeStart) return false;\n    onEventChange?.({ ...event, end });\n    return true;\n  };\n\n  const iconClass = allDay ? ALL_DAY_ICON_CLASS : EVENT_DETAIL_MUTED_CLASS;\n\n  return (\n    <EventDetailSection ref={sectionRef} name=\"time\">\n      {showTimes && (\n        <div className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}>\n          {/* Clock ink at 18.5-34px, text at 45px */}\n          <EventDetailTimeField\n            value={event.start}\n            getOptions={getStartOptions}\n            getMatches={getStartMatches}\n            onCommit={commitStart}\n            formatValue={formatTimeValue}\n            label=\"Start time\"\n            testId=\"event-start-time\"\n            panelRef={sectionRef}\n            disabled={allDay}\n            readOnly={readOnly}\n            className=\"ml-[7px] w-[105px] shrink-0 gap-[10px] pl-[10px]\"\n            leading={\n              <Clock9\n                absoluteStrokeWidth\n                strokeWidth={1.25}\n                className={cn(\"size-[17px] shrink-0\", iconClass)}\n              />\n            }\n          />\n          {/* Arrow ink at 129.5px, text at 156px; the box runs to 10px from the edge */}\n          <EventDetailTimeField\n            value={event.end}\n            getOptions={getEndOptions}\n            getMatches={getEndMatches}\n            onCommit={commitEnd}\n            formatValue={formatTimeValue}\n            label=\"End time\"\n            testId=\"event-end-time\"\n            panelRef={sectionRef}\n            disabled={allDay}\n            readOnly={readOnly}\n            fitText\n            className=\"mr-[10px] ml-[5px] flex-1 gap-[12.5px] pl-[11.5px]\"\n            leading={<TimeArrow className={iconClass} />}\n            trailing={\n              // Truncates before the end time does, in a row too narrow for both\n              <span\n                className={cn(\n                  \"ml-1 min-w-0 shrink-[1000] truncate\",\n                  allDay\n                    ? ALL_DAY_DURATION_CLASS\n                    : EVENT_DETAIL_SECONDARY_CLASS,\n                )}\n              >\n                {formatDuration(event.start, event.end)}\n              </span>\n            }\n          />\n        </div>\n      )}\n\n      <div className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}>\n        {/* Text at 45px, under the start time */}\n        <EventDetailDateField\n          value={event.start}\n          onCommit={commitStartDate}\n          label=\"Start date\"\n          testId=\"event-start-date\"\n          panelRef={sectionRef}\n          readOnly={readOnly}\n          className=\"ml-[36px] w-[105px] shrink-0\"\n        />\n        {/* The end date's text at 156px, under the end time */}\n        {showEndDate && (\n          <EventDetailDateField\n            value={event.end}\n            onCommit={commitEndDate}\n            minDate={event.start}\n            label=\"End date\"\n            testId=\"event-end-date\"\n            panelRef={sectionRef}\n            readOnly={readOnly}\n            className=\"mr-[10px] ml-[6px] flex-1\"\n          />\n        )}\n      </div>\n    </EventDetailSection>\n  );\n}\n\n/**\n * The all-day switch. The event keeps its times while it's all-day, and\n * switching off brings them back (9–10 AM for an event that has none).\n */\nexport function EventDetailAllDay<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const allDay = event.isAllDay ?? false;\n\n  const handleAllDayToggle = (checked: boolean) => {\n    if (checked) {\n      onEventChange?.({ ...event, isAllDay: true });\n      return;\n    }\n\n    if (hasTimeOfDay(event)) {\n      onEventChange?.({ ...event, isAllDay: false });\n      return;\n    }\n\n    onEventChange?.({\n      ...event,\n      isAllDay: false,\n      start: applyTimeToDate(event.start, DEFAULT_START_HOUR, 0),\n      end: applyTimeToDate(event.end, DEFAULT_END_HOUR, 0),\n    });\n  };\n\n  return (\n    <EventDetailSection name=\"all-day\">\n      {/* Clicking the label or the row toggles too */}\n      <EventDetailRow\n        className=\"cursor-default\"\n        onClick={onEventChange ? () => handleAllDayToggle(!allDay) : undefined}\n        leading={\n          <Switch\n            size=\"sm\"\n            checked={allDay}\n            disabled={!onEventChange}\n            onCheckedChange={handleAllDayToggle}\n            onClick={(e) => e.stopPropagation()}\n            aria-label=\"All-day\"\n            // data-[state=*] is the Radix switch, data-checked/data-unchecked\n            // Base UI's. Notion's is 18x11 with a 9px white thumb\n            className=\"data-[size=sm]:h-[11px] data-[size=sm]:w-[18px] **:data-[slot=switch-thumb]:!size-[9px] **:data-[slot=switch-thumb]:!bg-white data-[state=unchecked]:!bg-[#C7C5C1] data-unchecked:!bg-[#C7C5C1] dark:data-[state=unchecked]:!bg-[#595959] dark:data-unchecked:!bg-[#595959] data-[state=checked]:!bg-[#3A85D3] data-checked:!bg-[#3A85D3]\"\n          />\n        }\n      >\n        <span className={EVENT_DETAIL_TEXT_CLASS}>All-day</span>\n      </EventDetailRow>\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-time-field.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { selectInputSoon, useFieldPopover } from \"@/hooks/use-field-popover\";\nimport {\n  EVENT_DETAIL_FIELD_BOX_CLASS,\n  EventDetailFieldPopover,\n} from \"./event-detail-field-popover\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n} from \"./event-detail-parts\";\nimport type { EventDetailTimeFieldProps, TimeOption } from \"./week-view-types\";\n\n/** The menu's options while it's closed: none are built */\nconst NO_OPTIONS: TimeOption[] = [];\n\n/** Times of an all-day event: muted and inert (Notion: #B9B9B9 / #595959) */\nconst ALL_DAY_TIME_CLASS = \"text-[#B9B9B9] dark:text-[#595959]\";\n\n/**\n * A time's text (\"7:45 AM\"): Notion Calendar sets a narrow no-break space\n * before AM/PM, about 1px narrower than the space our labels keep\n */\nconst TIME_TEXT_CLASS = \"[word-spacing:-1px]\";\n\n/**\n * Scrolls a list so `row` shows, the nearest way, without scrolling the\n * page or the panel the way `scrollIntoView` would\n */\nfunction scrollRowIntoList(list: HTMLElement, row: HTMLElement) {\n  const top = row.offsetTop;\n  const bottom = top + row.offsetHeight;\n  if (top < list.scrollTop) {\n    list.scrollTop = top;\n    return;\n  }\n  if (bottom > list.scrollTop + list.clientHeight) {\n    list.scrollTop = bottom - list.clientHeight;\n  }\n}\n\n/** Index of the menu row an event happened in, or null outside the rows */\nfunction rowIndexOf(target: EventTarget | null): number | null {\n  if (!(target instanceof Element)) return null;\n  const row = target.closest<HTMLElement>(\"[data-index]\");\n  if (!row) return null;\n  return Number(row.dataset.index);\n}\n\n/**\n * Props for TimeOptionRow\n */\ninterface TimeOptionRowProps {\n  option: TimeOption;\n  index: number;\n  id: string;\n  /** Under the pointer, or chosen with the keyboard */\n  highlighted: boolean;\n}\n\n/** One row of the time menu: only the rows whose highlight changes render again */\nconst TimeOptionRow = React.memo(function TimeOptionRow({\n  option,\n  index,\n  id,\n  highlighted,\n}: TimeOptionRowProps) {\n  return (\n    <div\n      id={id}\n      role=\"option\"\n      aria-selected={highlighted}\n      data-index={index}\n      className={cn(\n        \"h-[30.5px] cursor-default truncate rounded-[6px] px-1.5 leading-[30.5px] select-none\",\n        highlighted && \"bg-[#303030]\",\n      )}\n    >\n      <span className={TIME_TEXT_CLASS}>{option.label}</span>\n      {option.hint && (\n        <>\n          {\" \"}\n          <span className=\"text-white/40\">{option.hint}</span>\n        </>\n      )}\n    </div>\n  );\n});\n\n/**\n * A time field with Notion Calendar's floating time menu: every 15 minutes,\n * opened beside the panel with the current time in view. Typing lists the\n * times the text can mean; the arrow keys move through the options. The\n * field shows the option under the pointer or the keyboard's, but only sets\n * one on Enter, on a click, or on blur after typing or the arrow keys (the\n * field keeps focus after Enter and a click). Escape puts the time back.\n */\nexport function EventDetailTimeField({\n  value,\n  getOptions,\n  getMatches,\n  onCommit,\n  formatValue,\n  label,\n  testId,\n  panelRef,\n  leading,\n  trailing,\n  disabled = false,\n  readOnly = false,\n  fitText = false,\n  className,\n}: EventDetailTimeFieldProps) {\n  const listId = React.useId();\n  const optionIdPrefix = React.useId();\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  /** Last pointer position over the menu */\n  const pointerRef = React.useRef<{ x: number; y: number } | null>(null);\n\n  const [open, setOpen] = React.useState(false);\n  /** Typed text the menu lists matches for, or null for every option */\n  const [query, setQuery] = React.useState<string | null>(null);\n  /** The option typing or the arrow keys reached, or null for the current time's */\n  const [activeIndex, setActiveIndex] = React.useState<number | null>(null);\n  /** Whether typing or the arrow keys chose the active option, which blur then sets */\n  const [chosen, setChosen] = React.useState(false);\n  /** The option under the pointer, shown in the field but never set by blur */\n  const [hoverIndex, setHoverIndex] = React.useState<number | null>(null);\n  const [list, setList] = React.useState<HTMLDivElement | null>(null);\n\n  const formatted = formatValue(value);\n  const [text, setText] = React.useState(formatted);\n\n  // Follow the event: a commit, a drag on the calendar, another field\n  React.useEffect(() => {\n    setText(formatted);\n  }, [formatted]);\n\n  const interactive = !disabled && !readOnly;\n  const isOpen = open && interactive;\n  // Built as the menu opens, not on every change of the event (a drag)\n  const options = React.useMemo(\n    () => (isOpen ? getOptions() : NO_OPTIONS),\n    [isOpen, getOptions],\n  );\n  const shown = React.useMemo(\n    () => (query === null ? options : getMatches(query)),\n    [query, options, getMatches],\n  );\n  const active =\n    activeIndex ??\n    shown.findIndex((option) => option.date.getTime() === value.getTime());\n  const highlighted = hoverIndex ?? active;\n  const hovered = hoverIndex === null ? undefined : shown[hoverIndex];\n  const fieldText = hovered ? hovered.label : text;\n\n  // Keep the active option in view: the current time when the menu opens,\n  // then wherever the arrow keys move (the pointer's is in view already)\n  React.useLayoutEffect(() => {\n    if (!isOpen || !list || active < 0) return;\n    const row = list.querySelector<HTMLElement>(`[data-index=\"${active}\"]`);\n    if (row) scrollRowIntoList(list, row);\n  }, [isOpen, list, active, shown]);\n\n  const openMenu = () => {\n    setQuery(null);\n    setActiveIndex(null);\n    setChosen(false);\n    setHoverIndex(null);\n    setOpen(true);\n  };\n\n  const closeMenu = () => {\n    setOpen(false);\n    setQuery(null);\n    setActiveIndex(null);\n    setChosen(false);\n    setHoverIndex(null);\n    pointerRef.current = null;\n  };\n\n  /** Sets an option, or puts the time back for none or one the event can't take */\n  const setOption = (option: TimeOption | undefined) => {\n    if (!option || option.date.getTime() === value.getTime()) {\n      setText(formatted);\n      return;\n    }\n    setText(onCommit(option.date) ? formatValue(option.date) : formatted);\n  };\n\n  const { inputProps, notePress, noteReturnFocus, escape } = useFieldPopover({\n    inputRef,\n    open: isOpen,\n    onEnter: () => {\n      openMenu();\n      selectInputSoon(inputRef);\n    },\n    onCommit: () => {\n      if (!chosen) {\n        setText(formatted);\n        return;\n      }\n      setOption(shown[active]);\n    },\n    onRestore: () => setText(formatted),\n    onClose: closeMenu,\n  });\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const typed = e.target.value;\n    const isEmpty = typed.trim().length === 0;\n    setText(typed);\n    setQuery(isEmpty ? null : typed);\n    setActiveIndex(isEmpty ? null : 0);\n    setChosen(!isEmpty);\n    setHoverIndex(null);\n    setOpen(true);\n  };\n\n  /** Moves the keyboard's option from the highlighted one and shows it */\n  const moveActive = (step: number) => {\n    if (shown.length === 0) return;\n    const from = highlighted >= 0 ? highlighted : step > 0 ? -1 : shown.length;\n    const index = Math.min(Math.max(from + step, 0), shown.length - 1);\n    setActiveIndex(index);\n    setChosen(true);\n    setHoverIndex(null);\n    setText(shown[index].label);\n    selectInputSoon(inputRef);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n      e.preventDefault();\n      if (!open) {\n        openMenu();\n        return;\n      }\n      moveActive(e.key === \"ArrowDown\" ? 1 : -1);\n      return;\n    }\n    if (e.key === \"Enter\") {\n      e.preventDefault();\n      setOption(shown[highlighted]);\n      closeMenu();\n      selectInputSoon(inputRef);\n      return;\n    }\n    if (e.key !== \"Escape\") return;\n    // With the menu closed (after Enter); before the calendar's global\n    // Escape, which would deselect the event\n    e.preventDefault();\n    e.stopPropagation();\n    escape();\n  };\n\n  /** A press on the focused field reopens a menu Enter closed */\n  const handleClick = () => {\n    if (!interactive || open) return;\n    openMenu();\n  };\n\n  const handleListPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.pointerType === \"touch\") return;\n    // The list scrolling under a still pointer isn't a hover\n    const last = pointerRef.current;\n    if (last && last.x === e.clientX && last.y === e.clientY) return;\n    pointerRef.current = { x: e.clientX, y: e.clientY };\n    const index = rowIndexOf(e.target);\n    if (index === null || index === hoverIndex) return;\n    setHoverIndex(index);\n    selectInputSoon(inputRef);\n  };\n\n  const handleListPointerLeave = () => {\n    pointerRef.current = null;\n    if (hoverIndex === null) return;\n    setHoverIndex(null);\n    selectInputSoon(inputRef);\n  };\n\n  const handleListClick = (e: React.MouseEvent<HTMLDivElement>) => {\n    const index = rowIndexOf(e.target);\n    if (index === null) return;\n    setOption(shown[index]);\n    closeMenu();\n    selectInputSoon(inputRef);\n  };\n\n  const highlightedId =\n    isOpen && shown[highlighted]\n      ? `${optionIdPrefix}-${highlighted}`\n      : undefined;\n\n  const input = (\n    <input\n      ref={inputRef}\n      data-testid={testId}\n      type=\"text\"\n      role=\"combobox\"\n      aria-label={label}\n      aria-expanded={isOpen}\n      aria-controls={isOpen ? listId : undefined}\n      aria-autocomplete=\"list\"\n      aria-activedescendant={highlightedId}\n      autoComplete=\"off\"\n      spellCheck={false}\n      value={fieldText}\n      readOnly={!interactive}\n      tabIndex={disabled ? -1 : undefined}\n      onFocus={interactive ? inputProps.onFocus : undefined}\n      onBlur={interactive ? inputProps.onBlur : undefined}\n      onChange={handleChange}\n      onKeyDown={interactive ? handleKeyDown : undefined}\n      onClick={handleClick}\n      // With `fitText`, the hidden copy of the text sizes the input instead\n      size={fitText ? 1 : undefined}\n      className={cn(\n        \"col-start-1 row-start-1 w-full min-w-0\",\n        TIME_TEXT_CLASS,\n        EVENT_DETAIL_GROUPED_INPUT_CLASS,\n        disabled\n          ? cn(ALL_DAY_TIME_CLASS, \"pointer-events-none\")\n          : EVENT_DETAIL_TEXT_CLASS,\n        readOnly && \"cursor-default\",\n      )}\n    />\n  );\n\n  const field = (\n    <>\n      {leading}\n      {fitText ? (\n        <span className=\"flex min-w-0 items-center\">\n          {/* The hidden copy of the text sizes the input, so the duration follows it */}\n          <span className=\"inline-grid min-w-0\">\n            <span\n              aria-hidden\n              className={cn(\n                \"invisible col-start-1 row-start-1 overflow-hidden whitespace-pre\",\n                TIME_TEXT_CLASS,\n              )}\n            >\n              {fieldText || \" \"}\n            </span>\n            {input}\n          </span>\n          {trailing}\n        </span>\n      ) : (\n        <>\n          <span className=\"grid min-w-0 flex-1\">{input}</span>\n          {trailing}\n        </>\n      )}\n    </>\n  );\n\n  return (\n    <EventDetailFieldPopover\n      open={isOpen}\n      panelRef={panelRef}\n      boxClassName={cn(\n        EVENT_DETAIL_FIELD_BOX_CLASS,\n        disabled && \"pointer-events-none hover:border-transparent\",\n        readOnly && \"cursor-default hover:border-transparent\",\n        className,\n      )}\n      onBoxClick={interactive ? () => inputRef.current?.focus() : undefined}\n      onBoxPointerDown={notePress}\n      field={field}\n      inputRef={inputRef}\n      onReturnFocus={noteReturnFocus}\n      className=\"w-[219px]\"\n    >\n      <div\n        ref={setList}\n        id={listId}\n        role=\"listbox\"\n        aria-label={label}\n        onPointerMove={handleListPointerMove}\n        onPointerLeave={handleListPointerLeave}\n        onClick={handleListClick}\n        className=\"relative max-h-[236px] overflow-y-auto overscroll-contain p-1\"\n      >\n        {shown.map((option, index) => (\n          <TimeOptionRow\n            key={option.date.getTime()}\n            option={option}\n            index={index}\n            id={`${optionIdPrefix}-${index}`}\n            highlighted={index === highlighted}\n          />\n        ))}\n      </div>\n    </EventDetailFieldPopover>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-date-field.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  addDays,\n  addMonths,\n  format,\n  isBefore,\n  isSameDay,\n  startOfDay,\n  startOfMonth,\n} from \"date-fns\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { useDayPicker } from \"react-day-picker\";\nimport type { DayButtonProps, MonthCaptionProps } from \"react-day-picker\";\n\nimport { cn } from \"@/lib/utils\";\nimport { selectInputSoon, useFieldPopover } from \"@/hooks/use-field-popover\";\nimport { Calendar } from \"@/components/ui/calendar\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_FIELD_BOX_CLASS,\n  EventDetailFieldPopover,\n} from \"./event-detail-field-popover\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n} from \"./event-detail-parts\";\nimport { formatDateDisplay, parseDateInput } from \"@/lib/time-input\";\nimport type { EventDetailDateFieldProps } from \"./week-view-types\";\n\n/** A day of the date picker: today, the event's day and hover fill a box */\nconst PICKER_DAY_CLASS =\n  \"relative isolate flex h-[30.5px] w-full items-center justify-center text-[13px] text-[#D4D4D4] outline-none before:absolute before:top-1/2 before:left-1/2 before:-z-10 before:h-[25px] before:w-[30px] before:-translate-1/2 before:rounded-[6px] hover:before:bg-[#303030]\";\n\n/** The date picker's previous and next month buttons */\nconst PICKER_CHEVRON_CLASS =\n  \"flex size-[24px] items-center justify-center justify-self-center rounded-[6px] text-[#848484] outline-none hover:bg-[#303030] disabled:opacity-40\";\n\n/**\n * Keys that move the marked day from the date field, the picker staying in\n * the field's hands: the arrows a day, Page Up and Page Down a month\n */\nconst DAY_STEPS: Partial<Record<string, (day: Date) => Date>> = {\n  ArrowUp: (day) => addDays(day, -1),\n  ArrowDown: (day) => addDays(day, 1),\n  PageUp: (day) => addMonths(day, -1),\n  PageDown: (day) => addMonths(day, 1),\n};\n\n/**\n * The date picker's header: \"November 2026\" with the previous and next\n * month chevrons over the last two columns\n */\nfunction DatePickerCaption({ calendarMonth }: MonthCaptionProps) {\n  const { locale } = useCalendarConfig();\n  const { goToMonth, previousMonth, nextMonth } = useDayPicker();\n\n  return (\n    <div className=\"grid h-[33px] grid-cols-7 items-center\">\n      <span className=\"col-span-5 pl-[11px] text-[#D4D4D4]\">\n        {format(calendarMonth.date, \"LLLL yyyy\", { locale })}\n      </span>\n      <button\n        type=\"button\"\n        aria-label=\"Previous month\"\n        disabled={!previousMonth}\n        onClick={() => previousMonth && goToMonth(previousMonth)}\n        className={PICKER_CHEVRON_CLASS}\n      >\n        <ChevronLeft className=\"size-4\" />\n      </button>\n      <button\n        type=\"button\"\n        aria-label=\"Next month\"\n        disabled={!nextMonth}\n        onClick={() => nextMonth && goToMonth(nextMonth)}\n        className={PICKER_CHEVRON_CLASS}\n      >\n        <ChevronRight className=\"size-4\" />\n      </button>\n    </div>\n  );\n}\n\n/**\n * A day of the date picker: today red, the event's day filled, days the\n * event can't take dimmed. Focus stays in the field, whose arrow keys move\n * the marked day.\n */\nfunction DatePickerDayButton({\n  // Kept off the button; DayPicker labels it\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  day,\n  modifiers,\n  className,\n  ...props\n}: DayButtonProps) {\n  return (\n    <button\n      {...props}\n      tabIndex={-1}\n      className={cn(\n        PICKER_DAY_CLASS,\n        (modifiers.outside || modifiers.disabled) && \"text-[#5F5F5F]\",\n        modifiers.disabled && \"hover:before:bg-transparent\",\n        modifiers.selected && \"before:bg-[#303030]\",\n        modifiers.today &&\n          \"text-white before:bg-[#F15550] hover:before:bg-[#F15550]\",\n        className,\n      )}\n    />\n  );\n}\n\n/** Custom parts of the date picker, built once */\nconst DATE_PICKER_COMPONENTS = {\n  MonthCaption: DatePickerCaption,\n  DayButton: DatePickerDayButton,\n};\n\n/**\n * Class names of the date picker. They replace the shadcn/ui Calendar's own,\n * which differ between projects (and the repo's sidebar calendar)\n */\nconst DATE_PICKER_CLASS_NAMES = {\n  root: \"relative w-full\",\n  months: \"flex flex-col\",\n  month: \"flex flex-col\",\n  month_caption: \"\",\n  caption_label: \"\",\n  month_grid: \"w-full border-collapse\",\n  weekdays: \"flex\",\n  weekday:\n    \"flex h-[22px] flex-1 items-center justify-center text-[11px] font-medium text-[#898989] select-none\",\n  week: \"flex\",\n  day: \"flex-1 p-0\",\n  today: \"\",\n  selected: \"\",\n  outside: \"\",\n  disabled: \"\",\n  hidden: \"invisible\",\n};\n\n/**\n * A date field with Notion Calendar's date picker beside the panel. Typing\n * a date (\"Nov 12\") or the arrow keys mark a day in the picker; Enter or\n * blur sets it, as does a click on a day (which closes the picker and leaves\n * the field). Escape puts the date back. A day the event can't take (an end\n * before the start) puts the date back too.\n */\nexport function EventDetailDateField({\n  value,\n  onCommit,\n  minDate,\n  label,\n  testId,\n  panelRef,\n  readOnly = false,\n  className,\n}: EventDetailDateFieldProps) {\n  const { locale, weekStartsOn } = useCalendarConfig();\n  const pickerId = React.useId();\n  const inputRef = React.useRef<HTMLInputElement>(null);\n\n  const formatted = formatDateDisplay(value, locale);\n  const [text, setText] = React.useState(formatted);\n  const [open, setOpen] = React.useState(false);\n  /** The day typing or the arrow keys marked in the picker, before it's set */\n  const [markedDay, setMarkedDay] = React.useState<Date | null>(null);\n  const [month, setMonth] = React.useState(() => startOfMonth(value));\n\n  React.useEffect(() => {\n    setText(formatted);\n  }, [formatted]);\n\n  const isOpen = open && !readOnly;\n\n  /** Sets a day, or puts the date back when it's the same or the event can't take it */\n  const setDay = (day: Date) => {\n    if (isSameDay(day, value) || !onCommit(day)) {\n      setText(formatted);\n      return;\n    }\n    setText(formatDateDisplay(day, locale));\n  };\n\n  /** Sets the marked or typed day, or puts the date back when the text isn't one */\n  const commitMarked = () => {\n    const day = markedDay ?? parseDateInput(text, value, locale);\n    if (!day) {\n      setText(formatted);\n      return;\n    }\n    setDay(day);\n  };\n\n  const close = () => {\n    setOpen(false);\n    setMarkedDay(null);\n  };\n\n  const openPicker = () => {\n    setMarkedDay(null);\n    setMonth(startOfMonth(value));\n    setOpen(true);\n    selectInputSoon(inputRef);\n  };\n\n  const { inputProps, notePress, noteReturnFocus, escape, leave } =\n    useFieldPopover({\n      inputRef,\n      open: isOpen,\n      onEnter: openPicker,\n      onCommit: commitMarked,\n      onRestore: () => setText(formatted),\n      onClose: close,\n    });\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setText(e.target.value);\n    const day = parseDateInput(e.target.value, value, locale);\n    setMarkedDay(day);\n    if (day) setMonth(startOfMonth(day));\n    setOpen(true);\n  };\n\n  /** Marks a day and shows it, unless it's before `minDate` */\n  const markDay = (day: Date) => {\n    if (minDate && isBefore(day, startOfDay(minDate))) return;\n    setMarkedDay(day);\n    setText(formatDateDisplay(day, locale));\n    setMonth(startOfMonth(day));\n    setOpen(true);\n    selectInputSoon(inputRef);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    const step = DAY_STEPS[e.key];\n    if (step) {\n      e.preventDefault();\n      markDay(step(markedDay ?? value));\n      return;\n    }\n    if (e.key === \"Enter\") {\n      e.preventDefault();\n      commitMarked();\n      close();\n      selectInputSoon(inputRef);\n      return;\n    }\n    if (e.key !== \"Escape\") return;\n    // With the picker closed (after Enter); before the calendar's global\n    // Escape, which would deselect the event\n    e.preventDefault();\n    e.stopPropagation();\n    escape();\n  };\n\n  const handleDayClick = (day: Date) => {\n    setDay(day);\n    leave();\n  };\n\n  const field = (\n    <input\n      ref={inputRef}\n      data-testid={testId}\n      type=\"text\"\n      role=\"combobox\"\n      aria-label={label}\n      aria-haspopup=\"dialog\"\n      aria-expanded={isOpen}\n      aria-controls={isOpen ? pickerId : undefined}\n      autoComplete=\"off\"\n      spellCheck={false}\n      value={text}\n      readOnly={readOnly}\n      onFocus={readOnly ? undefined : inputProps.onFocus}\n      onBlur={readOnly ? undefined : inputProps.onBlur}\n      onChange={handleChange}\n      onKeyDown={readOnly ? undefined : handleKeyDown}\n      onClick={() => !readOnly && !open && openPicker()}\n      className={cn(\n        \"w-full min-w-0\",\n        EVENT_DETAIL_GROUPED_INPUT_CLASS,\n        EVENT_DETAIL_TEXT_CLASS,\n        readOnly && \"cursor-default\",\n      )}\n    />\n  );\n\n  return (\n    <EventDetailFieldPopover\n      open={isOpen}\n      panelRef={panelRef}\n      boxClassName={cn(\n        EVENT_DETAIL_FIELD_BOX_CLASS,\n        \"pl-[8px]\",\n        readOnly && \"cursor-default hover:border-transparent\",\n        className,\n      )}\n      onBoxClick={readOnly ? undefined : () => inputRef.current?.focus()}\n      onBoxPointerDown={notePress}\n      field={field}\n      inputRef={inputRef}\n      onReturnFocus={noteReturnFocus}\n      className=\"w-[272px] p-2\"\n    >\n      <Calendar\n        id={pickerId}\n        // With onSelect, DayPicker follows `selected` (the marked day) as it changes\n        mode=\"single\"\n        required\n        selected={markedDay ?? value}\n        onSelect={handleDayClick}\n        disabled={minDate ? { before: minDate } : undefined}\n        month={month}\n        onMonthChange={setMonth}\n        showOutsideDays\n        fixedWeeks\n        hideNavigation\n        locale={locale}\n        // The calendar's first day; the locale's outside a provider\n        weekStartsOn={weekStartsOn ?? locale.options?.weekStartsOn ?? 0}\n        formatters={{\n          formatWeekdayName: (date) => format(date, \"EEEEEE\", { locale }),\n        }}\n        components={DATE_PICKER_COMPONENTS}\n        classNames={DATE_PICKER_CLASS_NAMES}\n        className=\"bg-transparent p-0\"\n      />\n    </EventDetailFieldPopover>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-field-popover.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { FIELD_POPOVER_ATTRIBUTE } from \"@/hooks/use-field-popover\";\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\";\nimport {\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n} from \"./event-detail-parts\";\nimport type { EventDetailFieldPopoverProps } from \"./week-view-types\";\n\n/**\n * Gap between the panel's left edge and the time menu or date picker, which\n * open beside the panel, top-aligned with their field (Notion: 6px)\n */\nconst POPOVER_PANEL_GAP = 6;\n\n/** Marks the popover for `useFieldPopover`, whose focus goes back to the field */\nconst FIELD_POPOVER_DATA = { [FIELD_POPOVER_ATTRIBUTE]: \"\" };\n\n/**\n * The time menu and the date picker: dark in both themes like the panel's\n * other menus, and shown at once, without the enter or exit animation of\n * Radix (`data-state`) or Base UI (`data-open`, `data-closed`)\n */\nconst FIELD_POPOVER_CLASS = cn(\n  EVENT_DETAIL_MENU_CLASS,\n  \"rounded-[10px] border p-0 text-sm font-medium text-white shadow-[0_8px_24px_rgb(0_0_0/0.24)] ring-0 outline-none\",\n  \"data-[state=open]:animate-none data-[state=closed]:animate-none data-open:animate-none data-closed:animate-none\",\n);\n\n/** A field's box: 31px tall in its 35px row, bordered on hover, filled on focus */\nexport const EVENT_DETAIL_FIELD_BOX_CLASS = cn(\n  \"relative flex h-[31px] min-w-0 items-center\",\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n);\n\n/**\n * Distance from a field's box to the panel's left edge plus the gap, the\n * side offset that opens its popover beside the panel\n */\nfunction getPopoverOffset(\n  box: HTMLElement | null,\n  panel: HTMLElement | null,\n): number {\n  if (!box || !panel) return POPOVER_PANEL_GAP;\n  return (\n    box.getBoundingClientRect().left -\n    panel.getBoundingClientRect().left +\n    POPOVER_PANEL_GAP\n  );\n}\n\n/**\n * A field's box, and its menu or picker in the shadcn/ui Popover, opened\n * left of the panel and top-aligned with the box, as in Notion Calendar.\n * The input keeps focus while it's open: the popover moves focus into itself\n * as it opens (Radix and Base UI both do), and hands it straight back, and\n * presses inside it never take focus. The trigger is a disabled, hidden\n * button over the box, there only to place the popover, so closing never\n * returns focus to it. The field opens and closes the popover itself, on\n * focus, blur, Enter and Escape (`useFieldPopover`).\n */\nexport function EventDetailFieldPopover({\n  open,\n  panelRef,\n  boxClassName,\n  onBoxClick,\n  onBoxPointerDown,\n  field,\n  inputRef,\n  onReturnFocus,\n  className,\n  children,\n}: EventDetailFieldPopoverProps) {\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const [sideOffset, setSideOffset] = React.useState(POPOVER_PANEL_GAP);\n\n  // Measured as it opens, before it's painted\n  React.useLayoutEffect(() => {\n    if (!open) return;\n    setSideOffset(getPopoverOffset(boxRef.current, panelRef.current));\n  }, [open, panelRef]);\n\n  const handleFocusCapture = () => {\n    const input = inputRef.current;\n    if (!input || document.activeElement === input) return;\n    onReturnFocus();\n    input.focus({ preventScroll: true });\n  };\n\n  return (\n    <Popover open={open}>\n      <div\n        ref={boxRef}\n        className={boxClassName}\n        onClick={onBoxClick}\n        onPointerDown={onBoxPointerDown}\n      >\n        <PopoverTrigger asChild disabled>\n          <button\n            type=\"button\"\n            tabIndex={-1}\n            aria-hidden\n            className=\"pointer-events-none absolute -inset-px opacity-0\"\n          />\n        </PopoverTrigger>\n        {field}\n      </div>\n      <PopoverContent\n        side=\"left\"\n        align=\"start\"\n        sideOffset={sideOffset}\n        {...FIELD_POPOVER_DATA}\n        onFocusCapture={handleFocusCapture}\n        onMouseDown={(e) => e.preventDefault()}\n        className={cn(FIELD_POPOVER_CLASS, className)}\n      >\n        {children}\n      </PopoverContent>\n    </Popover>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-timezone.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  autoUpdate,\n  flip,\n  offset,\n  shift,\n  size,\n  useFloating,\n} from \"@floating-ui/react-dom\";\nimport { Globe, History } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  Command,\n  CommandEmpty,\n  CommandGroup,\n  CommandItem,\n  CommandList,\n  CommandSeparator,\n} from \"@/components/ui/command\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EventDetailRow,\n  EventDetailSection,\n  getEventDetailPortalContainer,\n} from \"./event-detail-parts\";\nimport {\n  POPULAR_TIME_ZONES,\n  changeTimeZoneKeepingWallClock,\n  getEventTimeZone,\n  getTimeZoneOption,\n  getTimeZoneOptions,\n  getTimeZoneRowLabel,\n  getViewerTimeZone,\n  searchTimeZones,\n  splitSearchMatch,\n} from \"@/lib/time-zones\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n  TimeZoneOption,\n} from \"./week-view-types\";\n\n/** How many picked zones the picker remembers at its top */\nconst MAX_RECENT_TIME_ZONES = 5;\n\n/**\n * Gap between the row's hover box and the zone list beside the details, in\n * px: the list ends 7px left of the panel, as in Notion Calendar\n */\nconst LIST_OFFSET = 12;\n\n/** Keeps the zone list this far from the viewport's edges, in px */\nconst LIST_VIEWPORT_PADDING = 8;\n\n/** Tallest the zone list grows, in px (Notion Calendar: 345) */\nconst LIST_MAX_HEIGHT = 345;\n\n/**\n * The row's 31px box, which draws the hover border and the editing fill: it\n * starts 5px from the panel's edge, so the icon stays on the panel's 26px\n * icon column, and ends 10px before the other edge\n */\nconst ROW_BOX_CLASS =\n  \"-mr-1.5 -ml-[13px] flex h-[31px] min-w-0 flex-1 items-center gap-[11px] rounded-sm pr-2 pl-3\";\n\n/** Zone text in the list, which is dark in both themes */\nconst LIST_TEXT_CLASS = \"text-[#D4D4D4]\";\n\n/** Offsets and unmatched text in the list */\nconst LIST_MUTED_TEXT_CLASS = \"text-[#7F7F7F]\";\n\n/** The row while it holds the search input: filled like a focused input */\nconst EDITING_ROW_CLASS =\n  \"border-[#F5F5F5] bg-[#F5F5F5] dark:border-[#242424] dark:bg-[#242424]\";\n\n/** Rendered on the server and during hydration, where the viewer's zone is unknown */\nconst SERVER_TIME_ZONE = \"\";\n\n/**\n * A group of the zone list\n */\ninterface TimeZoneSection {\n  /** Prefixes each item's value, so a zone listed twice stays two items */\n  key: \"recent\" | \"popular\" | \"all\" | \"search\";\n  options: TimeZoneOption[];\n}\n\n/** Zones picked during this page's life, most recent first */\nlet recentTimeZones: string[] = [];\n\n/** Pickers showing the recent zones, told when they change */\nconst recentTimeZoneListeners = new Set<() => void>();\n\nfunction subscribeToRecentTimeZones(listener: () => void): () => void {\n  recentTimeZoneListeners.add(listener);\n  return () => recentTimeZoneListeners.delete(listener);\n}\n\nfunction getRecentTimeZones(): string[] {\n  return recentTimeZones;\n}\n\n/** Puts `timeZone` first among the recent zones */\nfunction rememberTimeZone(timeZone: string): void {\n  recentTimeZones = [\n    timeZone,\n    ...recentTimeZones.filter((zone) => zone !== timeZone),\n  ].slice(0, MAX_RECENT_TIME_ZONES);\n  for (const listener of recentTimeZoneListeners) listener();\n}\n\n/** No-op subscription: the viewer's zone doesn't change while the page is open */\nfunction subscribeToViewerTimeZone(): () => void {\n  return () => {};\n}\n\nfunction getServerTimeZone(): string {\n  return SERVER_TIME_ZONE;\n}\n\n/** Value of a zone's list item, e.g. \"recent:America/Sao_Paulo\" */\nfunction getItemValue(section: TimeZoneSection[\"key\"], timeZone: string) {\n  return `${section}:${timeZone}`;\n}\n\n/** The zone of a list item's value */\nfunction getItemTimeZone(value: string): string {\n  return value.slice(value.indexOf(\":\") + 1);\n}\n\n/**\n * Index of the item an arrow key moves the highlight to: one step from\n * `index`, kept inside the list; the first or last item when nothing is\n * highlighted\n */\nfunction getSteppedIndex(index: number, step: 1 | -1, count: number): number {\n  if (index === -1) return step === 1 ? 0 : count - 1;\n  return Math.min(Math.max(index + step, 0), count - 1);\n}\n\n/**\n * \"Brasilia Standard Time – Sao Paulo\", with the part matching the search in\n * bold white and the rest dimmed while searching\n */\nfunction ZoneText({ text, query }: { text: string; query: string | null }) {\n  if (query === null) return <>{text}</>;\n\n  const { before, match, after } = splitSearchMatch(text, query);\n  return (\n    <span className={LIST_MUTED_TEXT_CLASS}>\n      {before}\n      {match && <span className=\"font-semibold text-white\">{match}</span>}\n      {after}\n    </span>\n  );\n}\n\n/**\n * The event's time zone, \"GMT−3 Sao Paulo\". Clicking it turns the row into a\n * search field with the zone list beside the details: recent zones, popular\n * ones, then every zone by offset. Arrow keys and the pointer move through\n * the list and preview the city in the field, typing filters it by name or\n * city, Enter or a click picks a zone, Escape restores the zone from before\n * the list opened (the highlight only previews). Picking a\n * zone keeps the event's wall-clock times, so 8 AM in São Paulo becomes 8 AM\n * in New York. All-day events have no zone.\n */\nexport function EventDetailTimezone<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const listId = React.useId();\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n  /** Scrolls the highlighted item into view once the list has rendered it */\n  const scrollToActiveRef = React.useRef(false);\n\n  const [editing, setEditing] = React.useState(false);\n  const [listOpen, setListOpen] = React.useState(false);\n  /** The typed search, or null while the field shows a city */\n  const [query, setQuery] = React.useState<string | null>(null);\n  const [activeValue, setActiveValue] = React.useState(\"\");\n  const [inputText, setInputText] = React.useState(\"\");\n  const [rowElement, setRowElement] = React.useState<HTMLElement | null>(null);\n  /** Id of the highlighted option, for the field's `aria-activedescendant` */\n  const [activeOptionId, setActiveOptionId] = React.useState<string>();\n  const [listElement, setListElement] = React.useState<HTMLElement | null>(\n    null,\n  );\n\n  const viewerTimeZone = React.useSyncExternalStore(\n    subscribeToViewerTimeZone,\n    getViewerTimeZone,\n    getServerTimeZone,\n  );\n  const recent = React.useSyncExternalStore(\n    subscribeToRecentTimeZones,\n    getRecentTimeZones,\n    getRecentTimeZones,\n  );\n\n  const { floatingStyles, isPositioned } = useFloating({\n    open: listOpen,\n    placement: \"left-start\",\n    strategy: \"fixed\",\n    elements: { reference: rowElement, floating: listElement },\n    whileElementsMounted: autoUpdate,\n    middleware: [\n      offset(LIST_OFFSET),\n      flip({ fallbackPlacements: [\"bottom-start\", \"right-start\"] }),\n      shift({ padding: LIST_VIEWPORT_PADDING }),\n      size({\n        padding: LIST_VIEWPORT_PADDING,\n        apply({ availableHeight, elements }) {\n          elements.floating.style.maxHeight = `${Math.min(availableHeight, LIST_MAX_HEIGHT)}px`;\n        },\n      }),\n    ],\n  });\n\n  const eventTimeZone = React.useMemo(\n    () =>\n      getEventTimeZone({ timeZone: event.timeZone, timezone: event.timezone }),\n    [event.timeZone, event.timezone],\n  );\n  const timeZone = eventTimeZone ?? viewerTimeZone;\n\n  // Every zone, listed once per edit: typing searches this list\n  const startTime = event.start.getTime();\n  const options = React.useMemo(\n    () => (editing ? getTimeZoneOptions(new Date(startTime)) : []),\n    [editing, startTime],\n  );\n\n  const sections = React.useMemo<TimeZoneSection[]>(() => {\n    if (!listOpen) return [];\n    if (query !== null) {\n      return [{ key: \"search\", options: searchTimeZones(options, query) }];\n    }\n    const byId = new Map(options.map((option) => [option.id, option]));\n    const pick = (ids: string[]) =>\n      ids.flatMap((id) => {\n        const option = byId.get(id) ?? getTimeZoneOption(event.start, id);\n        return option ? [option] : [];\n      });\n    const groups: TimeZoneSection[] = [\n      { key: \"recent\", options: pick(recent) },\n      { key: \"popular\", options: pick(POPULAR_TIME_ZONES) },\n      { key: \"all\", options },\n    ];\n    return groups.filter((group) => group.options.length > 0);\n  }, [listOpen, query, options, recent, event.start]);\n\n  const itemValues = React.useMemo(\n    () =>\n      sections.flatMap((section) =>\n        section.options.map((option) => getItemValue(section.key, option.id)),\n      ),\n    [sections],\n  );\n\n  const cityOf = React.useCallback(\n    (zone: string) => getTimeZoneRowLabel(event.start, zone).city,\n    [event.start],\n  );\n\n  // Keep the highlighted item in view after the keyboard moved it or the\n  // list opened on it, once the list is placed and its height capped\n  React.useEffect(() => {\n    if (!isPositioned || !scrollToActiveRef.current || !listRef.current) {\n      return;\n    }\n    scrollToActiveRef.current = false;\n    const item = Array.from(\n      listRef.current.querySelectorAll<HTMLElement>(\"[cmdk-item]\"),\n    ).find((element) => element.dataset.value === activeValue);\n    item?.scrollIntoView({ block: \"nearest\" });\n  }, [activeValue, sections, isPositioned]);\n\n  // cmdk ids its options itself: read the highlighted one's from the list\n  React.useEffect(() => {\n    const item = listOpen\n      ? Array.from(\n          listRef.current?.querySelectorAll<HTMLElement>(\"[cmdk-item]\") ?? [],\n        ).find((element) => element.dataset.value === activeValue)\n      : undefined;\n    setActiveOptionId(item?.id || undefined);\n  }, [activeValue, sections, listOpen, listElement]);\n\n  // Select the city once the field has rendered it\n  React.useEffect(() => {\n    if (!editing || query !== null) return;\n    inputRef.current?.select();\n  }, [editing, query, inputText]);\n\n  const close = () => {\n    setEditing(false);\n    setListOpen(false);\n    setQuery(null);\n  };\n\n  const open = () => {\n    if (!onEventChange || !timeZone) return;\n    setEditing(true);\n    setListOpen(true);\n    setQuery(null);\n    setInputText(cityOf(timeZone));\n    setActiveValue(\n      getItemValue(recent.includes(timeZone) ? \"recent\" : \"all\", timeZone),\n    );\n    scrollToActiveRef.current = true;\n    requestAnimationFrame(() => {\n      inputRef.current?.focus();\n      inputRef.current?.select();\n    });\n  };\n\n  const pick = (zone: string) => {\n    rememberTimeZone(zone);\n    setListOpen(false);\n    setQuery(null);\n    setInputText(cityOf(zone));\n    if (zone === timeZone) return;\n    onEventChange?.({\n      ...event,\n      timeZone: zone,\n      start: changeTimeZoneKeepingWallClock(event.start, timeZone, zone),\n      end: changeTimeZoneKeepingWallClock(event.end, timeZone, zone),\n    });\n  };\n\n  /** Highlights a list item; outside a search the field previews its city */\n  const highlight = (value: string) => {\n    setActiveValue(value);\n    if (query === null) setInputText(cityOf(getItemTimeZone(value)));\n  };\n\n  const moveHighlight = (step: 1 | -1) => {\n    if (itemValues.length === 0) return;\n    const index = itemValues.indexOf(activeValue);\n    scrollToActiveRef.current = true;\n    highlight(itemValues[getSteppedIndex(index, step, itemValues.length)]);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n      e.preventDefault();\n      if (!listOpen) {\n        open();\n        return;\n      }\n      moveHighlight(e.key === \"ArrowDown\" ? 1 : -1);\n      return;\n    }\n    if (e.key === \"Enter\") {\n      e.preventDefault();\n      if (listOpen && activeValue) {\n        pick(getItemTimeZone(activeValue));\n        return;\n      }\n      inputRef.current?.blur();\n      return;\n    }\n    if (e.key === \"Escape\") {\n      // Keep the calendar's global Escape from deselecting the event\n      e.stopPropagation();\n      e.preventDefault();\n      inputRef.current?.blur();\n    }\n  };\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const text = e.target.value;\n    setInputText(text);\n    // An emptied field lists the sections again\n    setQuery(text.trim() ? text : null);\n    setListOpen(true);\n    const results = searchTimeZones(options, text);\n    setActiveValue(results[0] ? getItemValue(\"search\", results[0].id) : \"\");\n    scrollToActiveRef.current = true;\n  };\n\n  if (event.isAllDay) return null;\n\n  // Before hydration the viewer's zone is unknown: show the legacy label\n  if (!timeZone) {\n    return (\n      <EventDetailSection name=\"timezone\">\n        <EventDetailRow icon={Globe}>\n          <span className={EVENT_DETAIL_SECONDARY_CLASS}>{event.timezone}</span>\n        </EventDetailRow>\n      </EventDetailSection>\n    );\n  }\n\n  const label = getTimeZoneRowLabel(event.start, timeZone);\n  // Inside a modal sheet (the panel on phones), which dismisses on presses\n  // outside its own DOM; the body anywhere else\n  const portalContainer = listOpen\n    ? getEventDetailPortalContainer(rowElement)\n    : null;\n\n  return (\n    <EventDetailSection name=\"timezone\">\n      <div\n        className={cn(\n          \"flex items-center pr-4 pl-[18px]\",\n          EVENT_DETAIL_ROW_HEIGHT_CLASS,\n        )}\n      >\n        {editing ? (\n          <div\n            ref={setRowElement}\n            className={cn(\n              ROW_BOX_CLASS,\n              \"cursor-text border\",\n              EDITING_ROW_CLASS,\n            )}\n            onClick={() => inputRef.current?.focus()}\n          >\n            <Globe className={EVENT_DETAIL_ICON_CLASS} />\n            <input\n              ref={inputRef}\n              type=\"text\"\n              role=\"combobox\"\n              aria-label=\"Time zone\"\n              aria-expanded={listOpen}\n              aria-controls={listOpen ? listId : undefined}\n              aria-activedescendant={activeOptionId}\n              aria-autocomplete=\"list\"\n              value={inputText}\n              onChange={handleChange}\n              onKeyDown={handleKeyDown}\n              onBlur={close}\n              className=\"min-w-0 flex-1 border-none bg-transparent p-0 outline-none\"\n            />\n          </div>\n        ) : (\n          <button\n            ref={setRowElement}\n            type=\"button\"\n            aria-label={`Time zone: ${label.offset} ${label.city}`}\n            disabled={!onEventChange}\n            onClick={open}\n            className={cn(\n              EVENT_DETAIL_HOVER_BORDER_CLASS,\n              ROW_BOX_CLASS,\n              \"text-left outline-none disabled:cursor-default disabled:hover:border-transparent\",\n              \"focus-visible:border-[#3A85D3] dark:focus-visible:border-[#3A85D3]\",\n            )}\n          >\n            <Globe className={EVENT_DETAIL_ICON_CLASS} />\n            <span className=\"flex min-w-0 items-center gap-[5px]\">\n              <span className={cn(\"shrink-0\", EVENT_DETAIL_SECONDARY_CLASS)}>\n                {label.offset}\n              </span>\n              <span className=\"truncate\">{label.city}</span>\n            </span>\n          </button>\n        )}\n      </div>\n\n      {listOpen &&\n        portalContainer &&\n        createPortal(\n          <div\n            ref={setListElement}\n            id={listId}\n            style={floatingStyles}\n            className={cn(\n              \"pointer-events-auto z-50 flex w-[413px] max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-lg border font-medium shadow-lg\",\n              EVENT_DETAIL_MENU_CLASS,\n            )}\n            // The field keeps focus while the pointer uses the list\n            onMouseDown={(e) => e.preventDefault()}\n          >\n            <Command\n              shouldFilter={false}\n              value={activeValue}\n              onValueChange={highlight}\n              className=\"min-h-0 flex-1 rounded-none bg-transparent text-sm\"\n            >\n              <CommandList\n                ref={listRef}\n                // cmdk names the listbox from `label`, and ids it itself\n                label=\"Time zones\"\n                className=\"max-h-none min-h-0 flex-1 overflow-y-auto\"\n              >\n                {/* Keeps the list, and so Escape's restore, while nothing matches */}\n                <CommandEmpty\n                  className={cn(\n                    \"px-2.5 py-[7px] text-sm\",\n                    LIST_MUTED_TEXT_CLASS,\n                  )}\n                >\n                  No results\n                </CommandEmpty>\n                {sections.map((section, index) => (\n                  <React.Fragment key={section.key}>\n                    {index > 0 && (\n                      <CommandSeparator className=\"mx-0 bg-[#303030]\" />\n                    )}\n                    <CommandGroup className=\"p-1\">\n                      {section.options.map((option) => (\n                        <CommandItem\n                          key={option.id}\n                          value={getItemValue(section.key, option.id)}\n                          onSelect={() => pick(option.id)}\n                          className={cn(\n                            \"h-[30px] gap-[9px] rounded-md py-0 pr-2 pl-1.5 text-sm data-[selected=true]:bg-[#303030]\",\n                            LIST_TEXT_CLASS,\n                            \"data-[selected=true]:text-[#D4D4D4]\",\n                          )}\n                        >\n                          <span\n                            className={cn(\"shrink-0\", LIST_MUTED_TEXT_CLASS)}\n                          >\n                            {option.offsetLabel}\n                          </span>\n                          <span className=\"min-w-0 flex-1 truncate\">\n                            <ZoneText text={option.name} query={query} />\n                            <span\n                              className={cn(\n                                \"whitespace-pre\",\n                                query !== null && LIST_MUTED_TEXT_CLASS,\n                              )}\n                            >\n                              {\"  –  \"}\n                            </span>\n                            <ZoneText text={option.city} query={query} />\n                          </span>\n                          {section.key === \"recent\" && (\n                            <History\n                              aria-label=\"Recent\"\n                              className={cn(\n                                \"size-3.5 shrink-0\",\n                                LIST_MUTED_TEXT_CLASS,\n                              )}\n                            />\n                          )}\n                        </CommandItem>\n                      ))}\n                    </CommandGroup>\n                  </React.Fragment>\n                ))}\n              </CommandList>\n            </Command>\n          </div>,\n          portalContainer,\n        )}\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-recurrence.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { format, isSameYear, isValid, parse, startOfDay } from \"date-fns\";\nimport type { Locale } from \"date-fns\";\nimport {\n  Check,\n  ChevronDown,\n  ChevronLeft,\n  ChevronRight,\n  ChevronUp,\n  RefreshCcw,\n  RefreshCwOff,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useHoverTooltip } from \"@/hooks/use-hover-tooltip\";\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EventDetailSection,\n  EventDetailTooltip,\n  closeMenuOnEscape,\n  stopEscapePropagation,\n} from \"./event-detail-parts\";\nimport {\n  RECURRENCE_UNITS,\n  describeRecurrenceRule,\n  getDefaultRecurrenceEnd,\n  getEventRecurrenceRule,\n  getRecurrencePresets,\n  isRRule,\n  isSameRecurrenceRule,\n  normalizeRecurrenceRule,\n} from \"@/lib/recurrence\";\nimport { getEventTimeZone, getZonedDay } from \"@/lib/time-zones\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailRecurrenceProps,\n  NormalizedRecurrenceRule,\n  RecurrenceEnd,\n  RecurrenceFrequency,\n  RecurrenceLabel,\n  RecurrenceRule,\n  RecurrenceWeekday,\n} from \"./week-view-types\";\n\n/** Frequencies in the custom dialog's unit menu */\nconst FREQUENCIES: RecurrenceFrequency[] = [\n  \"daily\",\n  \"weekly\",\n  \"monthly\",\n  \"yearly\",\n];\n\n/** Days of the custom dialog's \"On\" row, Sunday first */\nconst DIALOG_WEEKDAYS: RecurrenceWeekday[] = [0, 1, 2, 3, 4, 5, 6];\n\n/** Largest \"Every\" and \"After\" number the custom dialog takes */\nconst MAX_RECURRENCE_NUMBER = 999;\n\n/** Formats the custom dialog's end date reads and writes, most specific first */\nconst END_DATE_FORMATS = [\n  \"EEE MMM d ''yy\",\n  \"EEEEEE MMM d ''yy\",\n  \"EEE MMM d yyyy\",\n  \"MMM d yyyy\",\n  \"MMM d, yyyy\",\n  \"EEE MMM d\",\n  \"MMM d\",\n  \"yyyy-MM-dd\",\n  \"M/d/yyyy\",\n  \"M/d\",\n];\n\n/** Item text in the repeat menu, which is dark in both themes */\nconst MENU_ITEM_CLASS =\n  \"relative h-8 gap-2 rounded-md py-0 pr-3 pl-7 text-sm font-medium text-[#D4D4D4] focus:!bg-[#303030] focus:!text-[#D4D4D4]\";\n\n/** \"on Thu\" in the repeat menu */\nconst MENU_DETAIL_CLASS = \"text-[#7F7F7F]\";\n\n/** A field of the custom dialog: bordered, filled on focus */\nconst DIALOG_FIELD_CLASS =\n  \"rounded-md border border-[#E8E8E4] bg-transparent text-foreground outline-none focus-within:border-[#F5F5F5] focus-within:bg-[#F5F5F5] has-[:disabled]:text-[#C7C5C1] dark:border-[#303030] dark:focus-within:border-[#303030] dark:focus-within:bg-[#303030] dark:has-[:disabled]:text-[#595959]\";\n\n/** Blue of the checked radio and the Done button, the same in both themes */\nconst ACCENT_BG_CLASS = \"bg-[#3A85D3] dark:bg-[#3A85D3]\";\n\n/** Blue of a selected day in the custom dialog, softer than the button's */\nconst SELECTED_DAY_CLASS =\n  \"bg-[#82B7F0] text-white dark:bg-[#245A92] dark:text-white\";\n\n/** What the row shows for an RRULE the details can't read */\nconst CUSTOM_RECURRENCE_LABEL: RecurrenceLabel = {\n  main: \"Custom repeat\",\n  detail: \"\",\n};\n\n/**\n * Props for HoverTooltip\n */\ninterface HoverTooltipProps {\n  /** Text shown above the element */\n  label: string;\n  /**\n   * Checked when the tooltip would show; return false to skip it (e.g. text\n   * that isn't truncated)\n   */\n  when?: (element: HTMLElement) => boolean;\n  /** One element, which the tooltip points at */\n  children: React.ReactElement;\n}\n\n/**\n * The details' tooltip above an element, after the pointer rests on it or\n * once it gets keyboard focus\n */\nfunction HoverTooltip({ label, when, children }: HoverTooltipProps) {\n  const tooltip = useHoverTooltip();\n  const [rect, setRect] = React.useState<DOMRect | null>(null);\n\n  /** Places the tooltip over the wrapped element and schedules it */\n  const show = (wrapper: HTMLElement) => {\n    // The wrapper is `display: contents`: measure the element inside\n    const element = wrapper.firstElementChild;\n    if (!(element instanceof HTMLElement)) return;\n    if (when && !when(element)) return;\n    setRect(element.getBoundingClientRect());\n    tooltip.scheduleOpen();\n  };\n\n  return (\n    <>\n      <span\n        className=\"contents\"\n        onPointerEnter={(e) => show(e.currentTarget)}\n        onPointerLeave={tooltip.scheduleClose}\n        onPointerDown={tooltip.scheduleClose}\n        onFocus={(e) => {\n          if (!e.target.matches(\":focus-visible\")) return;\n          show(e.currentTarget);\n        }}\n        onBlur={tooltip.scheduleClose}\n      >\n        {children}\n      </span>\n      <EventDetailTooltip rect={tooltip.isOpen ? rect : null}>\n        {label}\n      </EventDetailTooltip>\n    </>\n  );\n}\n\n/** Whether an element's text is cut off with an ellipsis */\nfunction isTruncated(element: HTMLElement): boolean {\n  const text = element.querySelector<HTMLElement>(\"[data-truncate]\");\n  return Boolean(text && text.scrollWidth > text.clientWidth);\n}\n\n/** \"Every week\" in full color, \"on Thu\" muted */\nfunction RecurrenceText({\n  label,\n  detailClassName,\n}: {\n  label: RecurrenceLabel;\n  detailClassName: string;\n}) {\n  return (\n    <>\n      <span>{label.main}</span>\n      {label.detail && <span className={detailClassName}> {label.detail}</span>}\n    </>\n  );\n}\n\n/**\n * What the row shows for the event's repeat rule: the rule read out, a\n * display text as it is, \"Custom repeat\" for an RRULE the details can't\n * read, or `null` when it doesn't repeat\n */\nfunction getRecurrenceLabel(\n  event: DetailedCalendarEvent,\n  rule: RecurrenceRule | null,\n  start: Date,\n  locale: Locale,\n): RecurrenceLabel | null {\n  if (rule) return describeRecurrenceRule(rule, start, locale);\n  if (!event.recurrence) return null;\n  if (isRRule(event.recurrence)) return CUSTOM_RECURRENCE_LABEL;\n  return { main: event.recurrence, detail: \"\" };\n}\n\n/** The end the custom dialog's \"Ends\" choice stands for */\nfunction getDialogEnd(\n  type: RecurrenceEnd[\"type\"],\n  date: Date,\n  count: number,\n): RecurrenceEnd {\n  if (type === \"on\") return { type: \"on\", date };\n  if (type === \"after\") return { type: \"after\", count };\n  return { type: \"never\" };\n}\n\n/** Formats the custom dialog's end date: \"Sun Dec 6\", \"Su Nov 7 '27\" another year */\nfunction formatEndDate(date: Date, locale: Locale): string {\n  if (isSameYear(date, new Date()))\n    return format(date, \"EEE MMM d\", { locale });\n  return format(date, \"EEEEEE MMM d ''yy\", { locale });\n}\n\n/** Reads a typed end date, or `null` when it isn't one */\nfunction parseEndDate(text: string, locale: Locale): Date | null {\n  const trimmed = text.trim();\n  for (const pattern of END_DATE_FORMATS) {\n    const date = parse(trimmed, pattern, new Date(), { locale });\n    if (isValid(date)) return startOfDay(date);\n  }\n  return null;\n}\n\n/** A whole number from 1 to `MAX_RECURRENCE_NUMBER`, or `fallback` */\nfunction clampCount(value: number, fallback: number): number {\n  if (!Number.isFinite(value)) return fallback;\n  return Math.min(Math.max(Math.round(value), 1), MAX_RECURRENCE_NUMBER);\n}\n\n/**\n * Props for NumberField\n */\ninterface NumberFieldProps {\n  label: string;\n  value: number;\n  onChange: (value: number) => void;\n  disabled?: boolean;\n}\n\n/** A number with up and down steppers, as the custom dialog's \"Every\" and \"After\" */\nfunction NumberField({ label, value, onChange, disabled }: NumberFieldProps) {\n  const [text, setText] = React.useState(String(value));\n\n  React.useEffect(() => {\n    setText(String(value));\n  }, [value]);\n\n  const commit = () => {\n    const next = clampCount(Number(text), value);\n    setText(String(next));\n    onChange(next);\n  };\n\n  return (\n    <div\n      className={cn(\n        \"flex h-8 w-[72px] items-center pl-2.5 pr-1\",\n        DIALOG_FIELD_CLASS,\n      )}\n    >\n      <input\n        type=\"text\"\n        inputMode=\"numeric\"\n        aria-label={label}\n        value={text}\n        disabled={disabled}\n        onFocus={(e) => e.currentTarget.select()}\n        onChange={(e) => setText(e.target.value.replace(/\\D/g, \"\"))}\n        onBlur={commit}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n            e.preventDefault();\n            onChange(clampCount(value + (e.key === \"ArrowUp\" ? 1 : -1), value));\n          }\n          if (e.key === \"Enter\") commit();\n        }}\n        className=\"min-w-0 flex-1 border-none bg-transparent p-0 outline-none disabled:cursor-default\"\n      />\n      <span className=\"flex flex-col\">\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label={`Increase ${label}`}\n          disabled={disabled}\n          onClick={() => onChange(clampCount(value + 1, value))}\n          className=\"text-[#989795] hover:text-foreground disabled:text-inherit dark:text-[#7F7F7F]\"\n        >\n          <ChevronUp className=\"size-3\" />\n        </button>\n        <button\n          type=\"button\"\n          tabIndex={-1}\n          aria-label={`Decrease ${label}`}\n          disabled={disabled}\n          onClick={() => onChange(clampCount(value - 1, value))}\n          className=\"text-[#989795] hover:text-foreground disabled:text-inherit dark:text-[#7F7F7F]\"\n        >\n          <ChevronDown className=\"size-3\" />\n        </button>\n      </span>\n    </div>\n  );\n}\n\n/** A round radio, blue with a white dot when checked */\nfunction RadioDot({ checked }: { checked: boolean }) {\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        \"flex size-4 shrink-0 items-center justify-center rounded-full\",\n        checked\n          ? ACCENT_BG_CLASS\n          : \"border border-[#E8E8E4] bg-[#F5F5F5] dark:border-[#373737] dark:bg-[#303030]\",\n      )}\n    >\n      {checked && <span className=\"size-1.5 rounded-full bg-white\" />}\n    </span>\n  );\n}\n\n/**\n * Props for CustomRecurrenceDialog\n */\ninterface CustomRecurrenceDialogProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** Day of the occurrence the rule is edited from, in the event's zone */\n  start: Date;\n  /** The rule to start from, or null to start from \"every week\" */\n  rule: RecurrenceRule | null;\n  onSave: (rule: RecurrenceRule) => void;\n}\n\n/**\n * Notion Calendar's \"Repeat\" dialog: every N days, weeks, months or years;\n * the days of the week, or the day of the month; and when it ends (never,\n * on a date, or after a number of times)\n */\nfunction CustomRecurrenceDialog({\n  open,\n  onOpenChange,\n  start,\n  rule,\n  onSave,\n}: CustomRecurrenceDialogProps) {\n  const { locale } = useCalendarConfig();\n  const initial = normalizeRecurrenceRule(\n    rule ?? { frequency: \"weekly\" },\n    start,\n  );\n  const [frequency, setFrequency] = React.useState(initial.frequency);\n  const [interval, setRepeatInterval] = React.useState(initial.interval);\n  const [weekdays, setWeekdays] = React.useState(initial.weekdays);\n  const [monthlyBy, setMonthlyBy] = React.useState(initial.monthlyBy);\n  /** Week of the month a \"weekday-of-month\" rule keeps: the rule's own, else the start's */\n  const weekOfMonth: NormalizedRecurrenceRule[\"weekOfMonth\"] =\n    initial.weekOfMonth;\n  const [endType, setEndType] = React.useState<RecurrenceEnd[\"type\"]>(\n    initial.end.type,\n  );\n  const [endDate, setEndDate] = React.useState(() =>\n    initial.end.type === \"on\"\n      ? initial.end.date\n      : getDefaultRecurrenceEnd(initial.frequency, start).date,\n  );\n  const [endCount, setEndCount] = React.useState(() =>\n    initial.end.type === \"after\"\n      ? initial.end.count\n      : getDefaultRecurrenceEnd(initial.frequency, start).count,\n  );\n  const [endDateText, setEndDateText] = React.useState(() =>\n    formatEndDate(endDate, locale),\n  );\n  const endDateRef = React.useRef<HTMLInputElement>(null);\n  const endCountRef = React.useRef<HTMLDivElement>(null);\n\n  const changeFrequency = (next: RecurrenceFrequency) => {\n    setFrequency(next);\n    const defaults = getDefaultRecurrenceEnd(next, start);\n    if (endType !== \"on\") {\n      setEndDate(defaults.date);\n      setEndDateText(formatEndDate(defaults.date, locale));\n    }\n    if (endType !== \"after\") setEndCount(defaults.count);\n  };\n\n  const toggleWeekday = (day: RecurrenceWeekday) => {\n    setWeekdays((current) => {\n      if (!current.includes(day))\n        return [...current, day].sort((a, b) => a - b);\n      // A weekly rule keeps at least one day\n      if (current.length === 1) return current;\n      return current.filter((other) => other !== day);\n    });\n  };\n\n  const commitEndDate = () => {\n    const parsed = parseEndDate(endDateText, locale);\n    const next = parsed && parsed >= startOfDay(start) ? parsed : endDate;\n    setEndDate(next);\n    setEndDateText(formatEndDate(next, locale));\n  };\n\n  const chooseEnd = (type: RecurrenceEnd[\"type\"]) => {\n    setEndType(type);\n    requestAnimationFrame(() => {\n      if (type === \"on\") endDateRef.current?.select();\n      if (type === \"after\")\n        endCountRef.current?.querySelector(\"input\")?.select();\n    });\n  };\n\n  const save = () => {\n    const end = getDialogEnd(endType, endDate, endCount);\n    const next: RecurrenceRule = { frequency };\n    if (interval > 1) next.interval = interval;\n    if (frequency === \"weekly\") next.weekdays = weekdays;\n    if (frequency === \"weekly\" && rule?.weekStartsOn !== undefined) {\n      next.weekStartsOn = rule.weekStartsOn;\n    }\n    if (frequency === \"monthly\") next.monthlyBy = monthlyBy;\n    if (frequency === \"monthly\" && monthlyBy === \"weekday-of-month\") {\n      next.weekOfMonth = weekOfMonth;\n    }\n    if (end.type !== \"never\") next.end = end;\n    onSave(next);\n  };\n\n  const unit = RECURRENCE_UNITS[frequency];\n  const unitLabel = (value: RecurrenceFrequency) =>\n    interval > 1 ? `${RECURRENCE_UNITS[value]}s` : RECURRENCE_UNITS[value];\n  const dayOfMonth = describeRecurrenceRule(\n    { frequency: \"monthly\", monthlyBy: \"day-of-month\" },\n    start,\n    locale,\n  ).detail.replace(/^on /, \"\");\n  const weekdayOfMonth = describeRecurrenceRule(\n    { frequency: \"monthly\", monthlyBy: \"weekday-of-month\", weekOfMonth },\n    start,\n    locale,\n  ).detail.replace(/^on /, \"\");\n  const ends: { type: RecurrenceEnd[\"type\"]; label: string }[] = [\n    { type: \"never\", label: \"Never\" },\n    { type: \"on\", label: \"On\" },\n    { type: \"after\", label: \"After\" },\n  ];\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent\n        showCloseButton={false}\n        className=\"w-[434px] max-w-[calc(100vw-32px)] gap-5 rounded-xl border-[#E8E8E4] bg-white p-[27px] text-sm font-medium dark:border-[#303030] dark:bg-[#252525]\"\n        onKeyDown={stopEscapePropagation}\n      >\n        <DialogTitle className=\"text-base font-medium\">Repeat</DialogTitle>\n        <DialogDescription className=\"sr-only\">\n          How often the event repeats and when it stops\n        </DialogDescription>\n\n        <div className=\"flex flex-col gap-4\">\n          <div className=\"flex items-center gap-2\">\n            <span className=\"w-12 shrink-0 text-foreground\">Every</span>\n            <NumberField\n              label=\"Interval\"\n              value={interval}\n              onChange={setRepeatInterval}\n            />\n            <DropdownMenu>\n              <DropdownMenuTrigger asChild>\n                <button\n                  type=\"button\"\n                  aria-label={`Unit: ${unit}`}\n                  className={cn(\n                    \"flex h-8 w-[87px] items-center justify-between px-2.5 data-[state=open]:bg-[#F5F5F5] data-popup-open:bg-[#F5F5F5] dark:data-[state=open]:bg-[#303030] dark:data-popup-open:bg-[#303030]\",\n                    DIALOG_FIELD_CLASS,\n                  )}\n                >\n                  {unitLabel(frequency)}\n                  <ChevronDown\n                    className={cn(\"size-3.5\", EVENT_DETAIL_MUTED_CLASS)}\n                  />\n                </button>\n              </DropdownMenuTrigger>\n              <DropdownMenuContent\n                align=\"start\"\n                className={cn(\n                  \"min-w-[140px] rounded-lg\",\n                  EVENT_DETAIL_MENU_CLASS,\n                )}\n                onKeyDown={stopEscapePropagation}\n              >\n                {FREQUENCIES.map((value) => (\n                  <DropdownMenuItem\n                    key={value}\n                    className={MENU_ITEM_CLASS}\n                    onClick={() => changeFrequency(value)}\n                  >\n                    {value === frequency && (\n                      <Check className=\"absolute left-2.5 size-3.5\" />\n                    )}\n                    {unitLabel(value)}\n                  </DropdownMenuItem>\n                ))}\n              </DropdownMenuContent>\n            </DropdownMenu>\n          </div>\n\n          {frequency === \"weekly\" && (\n            <div className=\"flex items-center gap-2\">\n              <span className=\"w-12 shrink-0 text-foreground\">On</span>\n              <div className=\"flex gap-[9px]\" role=\"group\" aria-label=\"Days\">\n                {DIALOG_WEEKDAYS.map((day) => {\n                  const selected = weekdays.includes(day);\n                  const date = new Date(start);\n                  date.setDate(start.getDate() - start.getDay() + day);\n                  return (\n                    <button\n                      key={day}\n                      type=\"button\"\n                      aria-pressed={selected}\n                      aria-label={format(date, \"EEEE\", { locale })}\n                      onClick={() => toggleWeekday(day)}\n                      className={cn(\n                        \"flex size-[26px] items-center justify-center rounded-full text-[11px] font-semibold\",\n                        selected\n                          ? SELECTED_DAY_CLASS\n                          : \"border border-[#E8E8E4] text-foreground hover:bg-[#F5F5F5] dark:border-[#373737] dark:bg-[#303030] dark:hover:bg-[#373737]\",\n                      )}\n                    >\n                      {format(date, \"EEEEEE\", { locale })}\n                    </button>\n                  );\n                })}\n              </div>\n            </div>\n          )}\n\n          {frequency === \"monthly\" && (\n            <div className=\"flex items-center gap-2\">\n              <span className=\"w-12 shrink-0 text-foreground\">On</span>\n              <div\n                role=\"radiogroup\"\n                aria-label=\"Day of the month\"\n                className=\"flex rounded-md bg-[#F5F5F5] p-0.5 dark:bg-[#303030]\"\n              >\n                {(\n                  [\n                    [\"day-of-month\", dayOfMonth],\n                    [\"weekday-of-month\", weekdayOfMonth],\n                  ] as const\n                ).map(([value, text]) => (\n                  <button\n                    key={value}\n                    type=\"button\"\n                    role=\"radio\"\n                    aria-checked={monthlyBy === value}\n                    onClick={() => setMonthlyBy(value)}\n                    className={cn(\n                      \"rounded-[5px] px-4 py-1.5 text-foreground\",\n                      monthlyBy === value &&\n                        \"bg-white shadow-sm dark:bg-[#252525]\",\n                    )}\n                  >\n                    {text}\n                  </button>\n                ))}\n              </div>\n            </div>\n          )}\n\n          <div className=\"flex flex-col gap-3\">\n            <span className=\"text-foreground\">Ends</span>\n            <div\n              role=\"radiogroup\"\n              aria-label=\"Ends\"\n              className=\"flex flex-col gap-2\"\n            >\n              {ends.map(({ type, label }) => (\n                <div key={type} className=\"flex h-8 items-center\">\n                  <button\n                    type=\"button\"\n                    role=\"radio\"\n                    aria-checked={endType === type}\n                    onClick={() => chooseEnd(type)}\n                    className=\"flex w-24 shrink-0 items-center gap-2.5 text-foreground outline-none\"\n                  >\n                    <RadioDot checked={endType === type} />\n                    {label}\n                  </button>\n                  {type === \"on\" && (\n                    <div\n                      className={cn(\n                        \"flex h-8 w-36 items-center px-2.5\",\n                        DIALOG_FIELD_CLASS,\n                      )}\n                    >\n                      <input\n                        ref={endDateRef}\n                        type=\"text\"\n                        aria-label=\"End date\"\n                        value={endDateText}\n                        disabled={endType !== \"on\"}\n                        onChange={(e) => setEndDateText(e.target.value)}\n                        onBlur={commitEndDate}\n                        onKeyDown={(e) => {\n                          if (e.key === \"Enter\") commitEndDate();\n                        }}\n                        className=\"min-w-0 flex-1 border-none bg-transparent p-0 outline-none\"\n                      />\n                    </div>\n                  )}\n                  {type === \"after\" && (\n                    <div\n                      ref={endCountRef}\n                      className=\"flex items-center gap-2.5\"\n                    >\n                      <NumberField\n                        label=\"Occurrences\"\n                        value={endCount}\n                        onChange={setEndCount}\n                        disabled={endType !== \"after\"}\n                      />\n                      <span\n                        className={\n                          endType === \"after\"\n                            ? \"text-foreground\"\n                            : EVENT_DETAIL_MUTED_CLASS\n                        }\n                      >\n                        times\n                      </span>\n                    </div>\n                  )}\n                </div>\n              ))}\n            </div>\n          </div>\n        </div>\n\n        <DialogFooter className=\"flex-row justify-end gap-2\">\n          <button\n            type=\"button\"\n            onClick={() => onOpenChange(false)}\n            className=\"h-8 rounded-md border border-[#E8E8E4] px-3 text-foreground hover:bg-[#F5F5F5] dark:border-[#373737] dark:bg-[#303030] dark:hover:bg-[#373737]\"\n          >\n            Cancel\n          </button>\n          <button\n            type=\"button\"\n            onClick={save}\n            className={cn(\n              \"h-8 rounded-md px-3 text-white hover:brightness-110\",\n              ACCENT_BG_CLASS,\n            )}\n          >\n            Done\n          </button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/**\n * The event's repeat rule, \"Every week on Thu\", or a muted \"Repeat\". Clicking\n * it opens Notion Calendar's menu: \"Does not repeat\", the presets for the\n * event's date (every day, every weekday or weekend day, every week, every 2\n * weeks, every month on the day or on the weekday, every year), the current\n * rule when it is none of those, and \"Custom…\" for the full rule dialog. A\n * repeating event gets buttons to its series' previous and next events.\n */\nexport function EventDetailRecurrence<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({\n  event,\n  onEventChange,\n  onPrevious,\n  onNext,\n}: EventDetailRecurrenceProps<TEvent>) {\n  const { locale } = useCalendarConfig();\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const [menuOpen, setMenuOpen] = React.useState(false);\n  const [customOpen, setCustomOpen] = React.useState(false);\n  /** Remounts the custom dialog on each open, so it starts from the current rule */\n  const [customKey, setCustomKey] = React.useState(0);\n\n  // A rule counts its days in the event's zone\n  const start = getZonedDay(event.start, getEventTimeZone(event));\n  const rule = getEventRecurrenceRule(event);\n  const repeats = Boolean(rule ?? event.recurrence);\n  const label = getRecurrenceLabel(event, rule, start, locale);\n\n  const presets = getRecurrencePresets(start);\n  const checkedPreset = rule\n    ? presets.findIndex((preset) => isSameRecurrenceRule(preset, rule, start))\n    : -1;\n\n  const applyRule = (next: RecurrenceRule | null) => {\n    onEventChange?.({\n      ...event,\n      recurrenceRule: next ?? undefined,\n      recurrence: undefined,\n    });\n  };\n\n  /** Closes the custom dialog and puts focus back on the Repeat button */\n  const closeCustom = () => {\n    setCustomOpen(false);\n    // After the dialog's own focus handling, which has nothing to return to:\n    // it opened from a menu item that is gone\n    requestAnimationFrame(() => triggerRef.current?.focus());\n  };\n\n  const fullText = label\n    ? [label.main, label.detail].filter(Boolean).join(\" \")\n    : \"Repeat\";\n\n  return (\n    <EventDetailSection name=\"recurrence\">\n      <div\n        className={cn(\n          \"flex items-center pr-[13px] pl-[18px]\",\n          EVENT_DETAIL_ROW_HEIGHT_CLASS,\n        )}\n      >\n        <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>\n          <HoverTooltip label={fullText} when={isTruncated}>\n            <DropdownMenuTrigger asChild>\n              <button\n                ref={triggerRef}\n                type=\"button\"\n                aria-label={`Repeat: ${repeats ? fullText : \"does not repeat\"}`}\n                disabled={!onEventChange}\n                className={cn(\n                  EVENT_DETAIL_HOVER_BORDER_CLASS,\n                  \"group/repeat -ml-[13px] flex h-[31px] min-w-0 flex-1 items-center gap-[11px] rounded-sm pr-2 pl-3 text-left outline-none disabled:cursor-default disabled:hover:border-transparent\",\n                  // Without the series buttons the box ends 10px before the panel's edge\n                  !repeats && \"-mr-[3px]\",\n                  \"focus-visible:border-[#3A85D3] dark:focus-visible:border-[#3A85D3]\",\n                  \"data-[state=open]:border-[#F5F5F5] data-[state=open]:bg-[#F5F5F5] data-popup-open:border-[#F5F5F5] data-popup-open:bg-[#F5F5F5] dark:data-[state=open]:border-[#242424] dark:data-[state=open]:bg-[#242424] dark:data-popup-open:border-[#242424] dark:data-popup-open:bg-[#242424]\",\n                )}\n              >\n                <RefreshCcw className={EVENT_DETAIL_ICON_CLASS} />\n                <span data-truncate className=\"min-w-0 flex-1 truncate\">\n                  {label ? (\n                    <RecurrenceText\n                      label={label}\n                      detailClassName={EVENT_DETAIL_SECONDARY_CLASS}\n                    />\n                  ) : (\n                    <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>\n                      Repeat\n                    </span>\n                  )}\n                </span>\n                {onEventChange && (\n                  // Takes room only while it shows, so a rule at rest gets\n                  // the whole width, as in Notion Calendar\n                  <ChevronDown\n                    className={cn(\n                      \"hidden size-4 shrink-0 group-hover/repeat:block group-data-[state=open]/repeat:block group-data-popup-open/repeat:block\",\n                      EVENT_DETAIL_MUTED_CLASS,\n                    )}\n                  />\n                )}\n              </button>\n            </DropdownMenuTrigger>\n          </HoverTooltip>\n          <DropdownMenuContent\n            side=\"left\"\n            align=\"start\"\n            sideOffset={14}\n            className={cn(\n              \"w-max min-w-[231px] rounded-lg\",\n              EVENT_DETAIL_MENU_CLASS,\n            )}\n            onKeyDown={closeMenuOnEscape(() => setMenuOpen(false))}\n          >\n            {repeats && (\n              <>\n                <DropdownMenuItem\n                  className={MENU_ITEM_CLASS}\n                  onClick={() => applyRule(null)}\n                >\n                  <RefreshCwOff className=\"absolute left-2.5 size-3.5 text-[#D4D4D4]\" />\n                  Does not repeat\n                </DropdownMenuItem>\n                <DropdownMenuSeparator className=\"bg-[#303030]\" />\n              </>\n            )}\n            {presets.map((preset, index) => (\n              <DropdownMenuItem\n                key={index}\n                className={MENU_ITEM_CLASS}\n                onClick={() => applyRule(preset)}\n              >\n                {index === checkedPreset && (\n                  <Check className=\"absolute left-2.5 size-3.5 text-[#D4D4D4]\" />\n                )}\n                <span>\n                  <RecurrenceText\n                    label={describeRecurrenceRule(preset, start, locale)}\n                    detailClassName={cn(\"ml-1\", MENU_DETAIL_CLASS)}\n                  />\n                </span>\n              </DropdownMenuItem>\n            ))}\n            {label && checkedPreset === -1 && (\n              <DropdownMenuItem\n                className={MENU_ITEM_CLASS}\n                onClick={() => setMenuOpen(false)}\n              >\n                <Check className=\"absolute left-2.5 size-3.5 text-[#D4D4D4]\" />\n                <span>\n                  <RecurrenceText\n                    label={label}\n                    detailClassName={cn(\"ml-1\", MENU_DETAIL_CLASS)}\n                  />\n                </span>\n              </DropdownMenuItem>\n            )}\n            <DropdownMenuSeparator className=\"bg-[#303030]\" />\n            <DropdownMenuItem\n              className={MENU_ITEM_CLASS}\n              onClick={() => {\n                setCustomKey((key) => key + 1);\n                setCustomOpen(true);\n              }}\n            >\n              Custom…\n            </DropdownMenuItem>\n          </DropdownMenuContent>\n        </DropdownMenu>\n\n        {repeats && (\n          <div className=\"ml-[9px] flex shrink-0 items-center\">\n            <SeriesButton\n              label=\"Go to previous event in this series\"\n              onClick={onPrevious}\n            >\n              <ChevronLeft className=\"size-4\" />\n            </SeriesButton>\n            <SeriesButton\n              label=\"Go to next event in this series\"\n              onClick={onNext}\n            >\n              <ChevronRight className=\"size-4\" />\n            </SeriesButton>\n          </div>\n        )}\n      </div>\n\n      {/* Stays mounted while it closes: its Escape handler must still run to\n          keep the calendar's global Escape from deselecting the event */}\n      <CustomRecurrenceDialog\n        key={customKey}\n        open={customOpen}\n        onOpenChange={(open) => {\n          if (!open) closeCustom();\n        }}\n        start={start}\n        rule={rule}\n        onSave={(next) => {\n          applyRule(next);\n          closeCustom();\n        }}\n      />\n    </EventDetailSection>\n  );\n}\n\n/**\n * Props for SeriesButton\n */\ninterface SeriesButtonProps {\n  /** Tooltip and accessible name */\n  label: string;\n  /** Leave out to disable the button (the end of the series) */\n  onClick?: () => void;\n  children: React.ReactNode;\n}\n\n/** A previous / next arrow of the repeat row */\nfunction SeriesButton({ label, onClick, children }: SeriesButtonProps) {\n  const button = (\n    <button\n      type=\"button\"\n      aria-label={label}\n      disabled={!onClick}\n      onClick={onClick}\n      className={cn(\n        \"flex size-8 items-center justify-center rounded-sm outline-none hover:bg-[#F5F5F5] hover:text-[#32302C] focus-visible:ring-1 focus-visible:ring-[#3A85D3] dark:focus-visible:ring-[#3A85D3] disabled:pointer-events-none disabled:text-[#DDDDDD] dark:hover:bg-[#242424] dark:hover:text-[#D4D4D4] dark:disabled:text-[#373737]\",\n        EVENT_DETAIL_SECONDARY_CLASS,\n      )}\n    >\n      {children}\n    </button>\n  );\n  if (!onClick) return button;\n  return <HoverTooltip label={label}>{button}</HoverTooltip>;\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-participants.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  ArrowLeft,\n  ArrowRight,\n  Check,\n  Copy,\n  DoorOpen,\n  History,\n  Mail,\n  MoreHorizontal,\n  User,\n  X,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { Avatar, AvatarFallback } from \"@/components/ui/avatar\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_ICON_BUTTON_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MENU_ITEM_CLASS,\n  EVENT_DETAIL_MENU_SECONDARY_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailDivider,\n  EventDetailSection,\n  closeMenuOnEscape,\n} from \"./event-detail-parts\";\nimport {\n  EVENT_DETAIL_INPUT_PLACEHOLDER_CLASS,\n  EventDetailSuggestion,\n  EventDetailSuggestions,\n  HighlightedMatch,\n  handleSuggestionKey,\n} from \"./event-detail-suggestions\";\nimport type {\n  DetailedCalendarEvent,\n  EventContact,\n  EventDetailSectionProps,\n  EventParticipant,\n  EventRoom,\n  ParticipantResponse,\n} from \"./week-view-types\";\n\n/** Width of the suggestions list (Notion: 330px) */\nconst SUGGESTIONS_WIDTH = 330;\n\n/** Most contacts listed while typing */\nconst MAX_SUGGESTIONS = 6;\n\n/**\n * A typed address that can be invited without a contact: a plain local\n * part, then a domain of letters, digits and hyphens with a 2+ letter TLD\n */\nconst EMAIL_PATTERN =\n  /^[A-Za-z0-9._%+'-]+@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z]{2,}$/;\n\n/** Placeholder of the field before anyone is added */\nconst EMPTY_PLACEHOLDER = \"Participants and Rooms\";\n\n/** Placeholder of the field under the list of guests */\nconst ADD_PLACEHOLDER = \"Add participant or room\";\n\n/** A row's hover action: a 28px icon button */\nconst ACTION_BUTTON_CLASS = cn(\n  \"flex size-7 shrink-0 items-center justify-center rounded-sm\",\n  EVENT_DETAIL_ICON_BUTTON_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n);\n\n/** Label under a participant's name, by role */\nconst ROLE_LABELS = {\n  organizer: \"Organizer\",\n  optional: \"Optional\",\n} as const;\n\n/** Badge on the avatar for each answer; \"needs-action\" shows none */\nconst RESPONSE_BADGES: Record<\n  Exclude<ParticipantResponse, \"needs-action\">,\n  { className: string; label: string; icon: React.ReactNode }\n> = {\n  accepted: {\n    className: \"bg-[#4AC881]\",\n    label: \"Accepted\",\n    icon: <Check className=\"size-[7px]\" strokeWidth={4} />,\n  },\n  declined: {\n    className: \"bg-[#E56458]\",\n    label: \"Declined\",\n    icon: <X className=\"size-[7px]\" strokeWidth={4} />,\n  },\n  tentative: {\n    className: \"bg-[#9B9A97]\",\n    label: \"Maybe\",\n    icon: <span className=\"text-[7px] leading-none font-bold\">?</span>,\n  },\n};\n\n/** One option of the suggestions list */\ntype ParticipantOption =\n  | { kind: \"contact\"; contact: EventContact }\n  | { kind: \"room\"; room: EventRoom };\n\n/** Whether two addresses are the same, ignoring case */\nfunction isSameEmail(a: string, b: string): boolean {\n  return a.toLowerCase() === b.toLowerCase();\n}\n\n/** A `mailto:` link to the address, its parts percent-encoded */\nfunction getMailtoHref(email: string): string {\n  const at = email.lastIndexOf(\"@\");\n  if (at === -1) return `mailto:${encodeURIComponent(email)}`;\n  const local = encodeURIComponent(email.slice(0, at));\n  const domain = encodeURIComponent(email.slice(at + 1));\n  return `mailto:${local}@${domain}`;\n}\n\n/** Label under a participant's name: \"Organizer\", \"Optional\" or none */\nfunction getRoleLabel(participant: EventParticipant): string | null {\n  if (participant.organizer) return ROLE_LABELS.organizer;\n  if (participant.optional) return ROLE_LABELS.optional;\n  return null;\n}\n\n/** First letter of a name or email, for the avatar */\nfunction getInitial(participant: { name?: string; email: string }): string {\n  return (participant.name ?? participant.email).trim().charAt(0).toUpperCase();\n}\n\n/** Whether the text matches a contact's name or email */\nfunction matchesContact(contact: EventContact, query: string): boolean {\n  const q = query.toLowerCase();\n  return (\n    contact.email.toLowerCase().includes(q) ||\n    (contact.name?.toLowerCase().includes(q) ?? false)\n  );\n}\n\n/** Second line of a room: where it is and how many it seats */\nfunction describeRoom(room: EventRoom): string | undefined {\n  const parts = [\n    room.location,\n    room.capacity ? `${room.capacity} seats` : undefined,\n  ].filter(Boolean);\n  return parts.length > 0 ? parts.join(\" · \") : undefined;\n}\n\n/**\n * Props for ParticipantAvatar\n */\ninterface ParticipantAvatarProps {\n  participant: EventParticipant;\n}\n\n/**\n * A participant's avatar: their initial on a gray disc, with a badge for\n * their answer (Notion: 20px, green check when accepted)\n */\nfunction ParticipantAvatar({ participant }: ParticipantAvatarProps) {\n  const response = participant.response ?? \"needs-action\";\n  const badge = response === \"needs-action\" ? null : RESPONSE_BADGES[response];\n\n  return (\n    <span className=\"relative flex size-5 shrink-0\">\n      <Avatar className=\"size-5\">\n        <AvatarFallback className=\"bg-gradient-to-b from-[#C7C7C7] to-[#B1B1B1] text-[10px] font-semibold text-white\">\n          {getInitial(participant)}\n        </AvatarFallback>\n      </Avatar>\n      {badge && (\n        <span\n          role=\"img\"\n          aria-label={badge.label}\n          className={cn(\n            \"absolute -right-[3px] -bottom-[3px] flex size-[11px] items-center justify-center rounded-full text-white ring-[1.5px] ring-white dark:ring-[#191919]\",\n            badge.className,\n          )}\n        >\n          {badge.icon}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/**\n * Props for ParticipantActions and ParticipantRow\n */\ninterface ParticipantRowProps {\n  participant: EventParticipant;\n  /** Marks them optional or required; leave out when the event is read-only */\n  onToggleOptional?: () => void;\n  /** Removes them; leave out when they can't be removed */\n  onRemove?: () => void;\n}\n\n/**\n * Hover actions of a participant row: copy the email, and, when the event\n * can be edited, a menu to email them, mark them optional or remove them\n */\nfunction ParticipantActions({\n  participant,\n  onToggleOptional,\n  onRemove,\n}: ParticipantRowProps) {\n  const [menuOpen, setMenuOpen] = React.useState(false);\n  const label = participant.name ?? participant.email;\n\n  return (\n    <div\n      className={cn(\n        \"flex shrink-0 items-center gap-0.5 opacity-0 group-hover/participant:opacity-100 focus-within:opacity-100\",\n        menuOpen && \"opacity-100\",\n      )}\n    >\n      <button\n        type=\"button\"\n        aria-label={`Copy ${participant.email}`}\n        title=\"Copy email\"\n        className={ACTION_BUTTON_CLASS}\n        onClick={() => void navigator.clipboard?.writeText(participant.email)}\n      >\n        <Copy className=\"size-4\" />\n      </button>\n      {onToggleOptional && (\n        <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>\n          <DropdownMenuTrigger asChild>\n            <button\n              type=\"button\"\n              aria-label={`More actions for ${label}`}\n              className={ACTION_BUTTON_CLASS}\n            >\n              <MoreHorizontal className=\"size-4\" />\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent\n            align=\"start\"\n            side=\"left\"\n            className={cn(\"min-w-[180px] text-sm\", EVENT_DETAIL_MENU_CLASS)}\n            onKeyDown={closeMenuOnEscape(() => setMenuOpen(false))}\n          >\n            <DropdownMenuItem\n              asChild\n              className={cn(EVENT_DETAIL_MENU_ITEM_CLASS, \"text-sm\")}\n            >\n              <a href={getMailtoHref(participant.email)}>\n                <Mail className=\"size-4\" />\n                Send email\n              </a>\n            </DropdownMenuItem>\n            {!participant.organizer && (\n              <>\n                <DropdownMenuSeparator className=\"bg-[#303030]\" />\n                <DropdownMenuItem\n                  className={cn(EVENT_DETAIL_MENU_ITEM_CLASS, \"text-sm\")}\n                  onClick={onToggleOptional}\n                >\n                  <User className=\"size-4\" />\n                  {participant.optional ? \"Mark required\" : \"Mark optional\"}\n                </DropdownMenuItem>\n              </>\n            )}\n            {onRemove && (\n              <DropdownMenuItem\n                className=\"text-sm text-[#E56458] focus:!bg-[#DE5551] focus:!text-white focus:[&>svg]:!text-white\"\n                onClick={onRemove}\n              >\n                <X className=\"size-4 text-[#E56458]\" />\n                Remove\n              </DropdownMenuItem>\n            )}\n          </DropdownMenuContent>\n        </DropdownMenu>\n      )}\n    </div>\n  );\n}\n\n/**\n * A guest: avatar with their answer, name (or email), \"Organizer\" or\n * \"Optional\" under it, and actions on hover\n */\nfunction ParticipantRow({\n  participant,\n  onToggleOptional,\n  onRemove,\n}: ParticipantRowProps) {\n  const role = getRoleLabel(participant);\n\n  return (\n    <div\n      data-participant={participant.email}\n      className={cn(\n        \"group/participant flex items-center gap-[9px] pr-2 pl-4\",\n        role ? \"min-h-[51px] py-1.5\" : EVENT_DETAIL_ROW_HEIGHT_CLASS,\n      )}\n    >\n      <span className=\"flex w-5 shrink-0 items-center justify-center\">\n        <ParticipantAvatar participant={participant} />\n      </span>\n      <div className=\"flex min-w-0 flex-1 flex-col leading-5\">\n        <span\n          className={cn(\"truncate\", EVENT_DETAIL_TEXT_CLASS)}\n          title={participant.email}\n        >\n          {participant.name ?? participant.email}\n        </span>\n        {role && <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>{role}</span>}\n      </div>\n      <ParticipantActions\n        participant={participant}\n        onToggleOptional={onToggleOptional}\n        onRemove={onRemove}\n      />\n    </div>\n  );\n}\n\n/**\n * Props for RoomRow\n */\ninterface RoomRowProps {\n  room: EventRoom;\n  /** Removes the booking; leave out when the event is read-only */\n  onRemove?: () => void;\n}\n\n/**\n * A booked room: a door on a gray square, its name, and where it is\n */\nfunction RoomRow({ room, onRemove }: RoomRowProps) {\n  const description = describeRoom(room);\n\n  return (\n    <div\n      data-room={room.id}\n      className={cn(\n        \"group/participant flex items-center gap-[9px] pr-2 pl-4\",\n        description ? \"min-h-[51px] py-1.5\" : EVENT_DETAIL_ROW_HEIGHT_CLASS,\n      )}\n    >\n      <span className=\"flex size-5 shrink-0 items-center justify-center rounded-sm bg-gradient-to-b from-[#C7C7C7] to-[#B1B1B1] text-white\">\n        <DoorOpen className=\"size-3\" />\n      </span>\n      <div className=\"flex min-w-0 flex-1 flex-col leading-5\">\n        <span className={cn(\"truncate\", EVENT_DETAIL_TEXT_CLASS)}>\n          {room.name}\n        </span>\n        {description && (\n          <span className={cn(\"truncate\", EVENT_DETAIL_PLACEHOLDER_CLASS)}>\n            {description}\n          </span>\n        )}\n      </div>\n      {onRemove && (\n        <button\n          type=\"button\"\n          aria-label={`Remove ${room.name}`}\n          title=\"Remove\"\n          className={cn(\n            \"opacity-0 group-hover/participant:opacity-100 focus-visible:opacity-100\",\n            ACTION_BUTTON_CLASS,\n          )}\n          onClick={onRemove}\n        >\n          <X className=\"size-4\" />\n        </button>\n      )}\n    </div>\n  );\n}\n\n/**\n * Guests and meeting rooms, as in Notion Calendar: a \"Participants and\n * Rooms\" field until someone is added, then one row per guest (avatar with\n * their answer, \"Organizer\" / \"Optional\", hover actions) and per room, and\n * an \"Add participant or room\" field. Focusing the field lists recent\n * contacts; typing lists matching contacts and rooms (or the typed email).\n * The calendar's account (`calendarEmail`) joins as the organizer, who\n * stays while anyone else is invited. Escape closes the list and adds\n * nobody. Contacts and rooms come from `CalendarProvider`'s `contacts` and\n * `rooms`; without `onEventChange`, the guests are only listed.\n */\nexport function EventDetailParticipants<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const { contacts, rooms: availableRooms } = useCalendarConfig();\n  const participants = React.useMemo(\n    () => event.participants ?? [],\n    [event.participants],\n  );\n  const rooms = React.useMemo(() => event.rooms ?? [], [event.rooms]);\n  const hasPeople = participants.length > 0 || rooms.length > 0;\n  const canEdit = Boolean(onEventChange);\n  const owner = event.calendarEmail;\n\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const listId = React.useId();\n  const [query, setQuery] = React.useState(\"\");\n  const [open, setOpen] = React.useState(false);\n  /** Whether the list shows the rooms instead of people */\n  const [showRooms, setShowRooms] = React.useState(false);\n  const [activeIndex, setActiveIndex] = React.useState(-1);\n\n  const trimmed = query.trim();\n\n  const options = React.useMemo<ParticipantOption[]>(() => {\n    const q = trimmed.toLowerCase();\n    const invited = new Set(participants.map((p) => p.email.toLowerCase()));\n    const booked = new Set(rooms.map((r) => r.id.toLowerCase()));\n    /** Room addresses, never invited as people */\n    const roomIds = new Set([\n      ...booked,\n      ...availableRooms.map((r) => r.id.toLowerCase()),\n    ]);\n    const freeRooms = availableRooms.filter(\n      (r) => !booked.has(r.id.toLowerCase()),\n    );\n    const matchesRoom = (room: EventRoom) =>\n      room.name.toLowerCase().includes(q) || room.id.toLowerCase() === q;\n\n    if (showRooms) {\n      return freeRooms\n        .filter((r) => !q || matchesRoom(r))\n        .map((room) => ({ kind: \"room\", room }));\n    }\n\n    const uninvited = contacts.filter(\n      (c) =>\n        !invited.has(c.email.toLowerCase()) &&\n        !roomIds.has(c.email.toLowerCase()),\n    );\n    if (!q) {\n      return uninvited\n        .filter((c) => c.recent)\n        .slice(0, MAX_SUGGESTIONS)\n        .map((contact) => ({ kind: \"contact\", contact }));\n    }\n\n    const matches: ParticipantOption[] = uninvited\n      .filter((c) => matchesContact(c, trimmed))\n      .slice(0, MAX_SUGGESTIONS)\n      .map((contact) => ({ kind: \"contact\", contact }));\n    const isNewEmail =\n      EMAIL_PATTERN.test(trimmed) &&\n      !invited.has(q) &&\n      !roomIds.has(q) &&\n      !matches.some(\n        (o) => o.kind === \"contact\" && isSameEmail(o.contact.email, trimmed),\n      );\n    if (isNewEmail) {\n      matches.push({ kind: \"contact\", contact: { email: trimmed } });\n    }\n    for (const room of freeRooms) {\n      if (matchesRoom(room)) matches.push({ kind: \"room\", room });\n    }\n    return matches;\n  }, [contacts, availableRooms, participants, rooms, showRooms, trimmed]);\n\n  const hasRoomsList = availableRooms.length > 0;\n  /** \"View rooms and resources\" (or back), the list's last option */\n  const hasFooter = !trimmed && hasRoomsList;\n  const optionCount = options.length + (hasFooter ? 1 : 0);\n  const listOpen = canEdit && open && optionCount > 0;\n\n  // While typing, the first match is active, as in Notion\n  React.useEffect(() => {\n    setActiveIndex(trimmed ? 0 : -1);\n  }, [trimmed, showRooms]);\n\n  const closeList = React.useCallback(() => {\n    setOpen(false);\n    setShowRooms(false);\n    setQuery(\"\");\n  }, []);\n\n  /** The calendar's account joins as organizer with the first guest */\n  const withOrganizer = React.useCallback(\n    (next: EventParticipant[]): EventParticipant[] => {\n      if (participants.length > 0 || !owner) return next;\n      if (next.some((p) => isSameEmail(p.email, owner))) return next;\n      return [{ email: owner, organizer: true, response: \"accepted\" }, ...next];\n    },\n    [owner, participants.length],\n  );\n\n  const pick = React.useCallback(\n    (option: ParticipantOption) => {\n      if (option.kind === \"room\") {\n        onEventChange?.({ ...event, rooms: [...rooms, option.room] });\n      } else {\n        const { email, name } = option.contact;\n        // Your own address has accepted, and organizes unless someone else does\n        const guest: EventParticipant =\n          owner && isSameEmail(email, owner)\n            ? {\n                email,\n                name,\n                organizer: !participants.some((p) => p.organizer),\n                response: \"accepted\",\n              }\n            : { email, name, response: \"needs-action\" };\n        onEventChange?.({\n          ...event,\n          participants: withOrganizer([...participants, guest]),\n        });\n      }\n      setQuery(\"\");\n      setShowRooms(false);\n    },\n    [event, onEventChange, owner, participants, rooms, withOrganizer],\n  );\n\n  const removeParticipant = (email: string) => {\n    const rest = participants.filter((p) => p.email !== email);\n    // Only the organizer left: nobody is invited anymore\n    const next = rest.every((p) => p.organizer) ? [] : rest;\n    onEventChange?.({\n      ...event,\n      participants: next.length > 0 ? next : undefined,\n    });\n  };\n\n  const toggleOptional = (email: string) => {\n    onEventChange?.({\n      ...event,\n      participants: participants.map((p) =>\n        p.email === email ? { ...p, optional: !p.optional } : p,\n      ),\n    });\n  };\n\n  const removeRoom = (id: string) => {\n    const next = rooms.filter((r) => r.id !== id);\n    onEventChange?.({ ...event, rooms: next.length > 0 ? next : undefined });\n  };\n\n  /** Picks an option by index, the footer's after the others */\n  const pickAt = (index: number) => {\n    if (index < options.length) {\n      pick(options[index]);\n      return;\n    }\n    setShowRooms((value) => !value);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"Escape\") {\n      // Close the list, as it was before typing, and keep the event\n      // selected (Notion's Escape adds the highlighted contact; this never\n      // invites anyone)\n      e.preventDefault();\n      e.stopPropagation();\n      closeList();\n      inputRef.current?.blur();\n      return;\n    }\n    if (!listOpen) {\n      if (e.key === \"ArrowDown\" && canEdit) setOpen(true);\n      return;\n    }\n    handleSuggestionKey(e, optionCount, activeIndex, setActiveIndex, pickAt);\n  };\n\n  const optionId = (index: number) => `${listId}-option-${index}`;\n\n  const field = (\n    <div\n      className={cn(\n        \"flex min-h-[35px] items-center\",\n        hasPeople ? \"pr-2 pl-[36px]\" : \"px-2\",\n      )}\n    >\n      <div\n        ref={boxRef}\n        className={cn(\n          \"flex h-8 min-w-0 flex-1 items-center gap-[11px] pr-2\",\n          hasPeople ? \"pl-[8px]\" : \"pl-[9px]\",\n          EVENT_DETAIL_INPUT_GROUP_CLASS,\n        )}\n        onClick={() => inputRef.current?.focus()}\n      >\n        {!hasPeople && <User className={EVENT_DETAIL_ICON_CLASS} />}\n        <input\n          ref={inputRef}\n          type=\"text\"\n          role=\"combobox\"\n          aria-label={hasPeople ? ADD_PLACEHOLDER : EMPTY_PLACEHOLDER}\n          aria-autocomplete=\"list\"\n          aria-expanded={listOpen}\n          aria-controls={listOpen ? listId : undefined}\n          aria-activedescendant={\n            listOpen && activeIndex >= 0 ? optionId(activeIndex) : undefined\n          }\n          data-testid=\"event-participants-input\"\n          value={query}\n          placeholder={hasPeople ? ADD_PLACEHOLDER : EMPTY_PLACEHOLDER}\n          readOnly={!canEdit}\n          onChange={(e) => {\n            setQuery(e.target.value);\n            setOpen(true);\n          }}\n          onFocus={() => setOpen(true)}\n          onBlur={closeList}\n          onKeyDown={handleKeyDown}\n          className={cn(\n            \"min-w-0 flex-1\",\n            EVENT_DETAIL_GROUPED_INPUT_CLASS,\n            EVENT_DETAIL_TEXT_CLASS,\n            EVENT_DETAIL_INPUT_PLACEHOLDER_CLASS,\n          )}\n        />\n      </div>\n    </div>\n  );\n\n  return (\n    <EventDetailSection name=\"participants\">\n      {participants.map((participant) => (\n        <ParticipantRow\n          key={participant.email}\n          participant={participant}\n          onToggleOptional={\n            canEdit ? () => toggleOptional(participant.email) : undefined\n          }\n          // The organizer stays while anyone else is invited\n          onRemove={\n            canEdit && (!participant.organizer || participants.length === 1)\n              ? () => removeParticipant(participant.email)\n              : undefined\n          }\n        />\n      ))}\n      {rooms.map((room) => (\n        <RoomRow\n          key={room.id}\n          room={room}\n          onRemove={canEdit ? () => removeRoom(room.id) : undefined}\n        />\n      ))}\n      {canEdit || !hasPeople ? field : null}\n      {listOpen && (\n        <EventDetailSuggestions\n          id={listId}\n          label={showRooms ? \"Rooms and resources\" : \"Suggested participants\"}\n          anchorRef={boxRef}\n          width={SUGGESTIONS_WIDTH}\n          footer={\n            hasFooter ? (\n              <EventDetailSuggestion\n                id={optionId(options.length)}\n                active={activeIndex === options.length}\n                onActivate={() => setActiveIndex(options.length)}\n                onSelect={() => pickAt(options.length)}\n                className=\"justify-between\"\n              >\n                <RoomsToggleContent showRooms={showRooms} />\n              </EventDetailSuggestion>\n            ) : undefined\n          }\n        >\n          {options.map((option, index) => (\n            <EventDetailSuggestion\n              key={\n                option.kind === \"room\"\n                  ? `room-${option.room.id}`\n                  : option.contact.email\n              }\n              id={optionId(index)}\n              active={index === activeIndex}\n              onActivate={() => setActiveIndex(index)}\n              onSelect={() => pick(option)}\n            >\n              <ParticipantOptionContent option={option} query={trimmed} />\n            </EventDetailSuggestion>\n          ))}\n        </EventDetailSuggestions>\n      )}\n      {hasPeople && <EventDetailDivider className=\"my-2\" />}\n    </EventDetailSection>\n  );\n}\n\n/**\n * Props for RoomsToggleContent\n */\ninterface RoomsToggleContentProps {\n  /** Whether the list shows the rooms, which turns it into \"Back to people\" */\n  showRooms: boolean;\n}\n\n/** The footer option: \"View rooms and resources\", or back to people */\nfunction RoomsToggleContent({ showRooms }: RoomsToggleContentProps) {\n  const iconClass = cn(\"size-4\", EVENT_DETAIL_MENU_SECONDARY_CLASS);\n  if (showRooms) {\n    return (\n      <span className=\"flex items-center gap-2\">\n        <ArrowLeft className={iconClass} />\n        Back to people\n      </span>\n    );\n  }\n  return (\n    <>\n      View rooms and resources\n      <ArrowRight className={iconClass} />\n    </>\n  );\n}\n\n/**\n * Props for ParticipantOptionContent\n */\ninterface ParticipantOptionContentProps {\n  option: ParticipantOption;\n  /** What was typed, bright in the matches */\n  query: string;\n}\n\n/**\n * What an option shows: a contact's name over their email (or the email\n * alone) with a history icon when recent; a room's name over where it is\n */\nfunction ParticipantOptionContent({\n  option,\n  query,\n}: ParticipantOptionContentProps) {\n  if (option.kind === \"room\") {\n    const description = describeRoom(option.room);\n    return (\n      <>\n        <DoorOpen\n          className={cn(\"size-4 shrink-0\", EVENT_DETAIL_MENU_SECONDARY_CLASS)}\n        />\n        <span className=\"flex min-w-0 flex-1 flex-col leading-5\">\n          <span className=\"truncate\">\n            <HighlightedMatch text={option.room.name} query={query} />\n          </span>\n          {description && (\n            <span className={cn(\"truncate\", EVENT_DETAIL_MENU_SECONDARY_CLASS)}>\n              {description}\n            </span>\n          )}\n        </span>\n      </>\n    );\n  }\n\n  const { contact } = option;\n  return (\n    <>\n      <span className=\"flex min-w-0 flex-1 flex-col leading-5\">\n        <span className=\"truncate\">\n          <HighlightedMatch\n            text={contact.name ?? contact.email}\n            query={query}\n          />\n        </span>\n        {contact.name && (\n          <span className={cn(\"truncate\", EVENT_DETAIL_MENU_SECONDARY_CLASS)}>\n            <HighlightedMatch text={contact.email} query={query} />\n          </span>\n        )}\n      </span>\n      {contact.recent && (\n        <History\n          aria-label=\"Recent\"\n          className={cn(\"size-4 shrink-0\", EVENT_DETAIL_MENU_SECONDARY_CLASS)}\n        />\n      )}\n    </>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-conferencing.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  Check,\n  ChevronDown,\n  Link2,\n  LoaderCircle,\n  Video,\n  VideoOff,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MENU_ITEM_CLASS,\n  EVENT_DETAIL_MENU_SECONDARY_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailDivider,\n  EventDetailSection,\n  PANEL_TRIGGER_OPEN_CLASS,\n  ROW_BOX_CLASS,\n  closeMenuOnEscape,\n} from \"./event-detail-parts\";\nimport type {\n  ConferenceProvider,\n  ConferenceProviderOption,\n  DetailedCalendarEvent,\n  EventConference,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** Name shown for a call whose service isn't among the offered ones */\nconst PROVIDER_NAMES: Record<ConferenceProvider, string> = {\n  \"google-meet\": \"Google Meet\",\n  zoom: \"Zoom\",\n  \"microsoft-teams\": \"Microsoft Teams\",\n  other: \"Video call\",\n};\n\n/** Item text in the conferencing menu */\nconst MENU_ITEM_CLASS = cn(EVENT_DETAIL_MENU_ITEM_CLASS, \"gap-2 text-sm\");\n\n/** The fallback camera's color in the (dark) menu */\nconst MENU_ICON_CLASS = cn(\n  \"size-4 shrink-0\",\n  EVENT_DETAIL_MENU_SECONDARY_CLASS,\n);\n\n/** A call being created by an option whose `createConference` is async */\ninterface PendingConference {\n  option: ConferenceProviderOption;\n  /** Event it's created for: another event's panel doesn't show it */\n  eventId: string;\n}\n\n/** Whether `createConference` returned a promise rather than the call */\nfunction isPromiseLike(\n  value: EventConference | PromiseLike<EventConference>,\n): value is PromiseLike<EventConference> {\n  return \"then\" in value;\n}\n\n/**\n * The option that created the call: the one with its label, or, for a call\n * without one (imported, or set by the app), the first of its service\n */\nfunction findOption(\n  providers: ConferenceProviderOption[],\n  conference: EventConference,\n): ConferenceProviderOption | undefined {\n  if (conference.label) {\n    const labeled = providers.find(\n      (option) => option.label === conference.label,\n    );\n    if (labeled) return labeled;\n  }\n  return providers.find((option) => option.provider === conference.provider);\n}\n\n/**\n * Props for ProviderIcon\n */\ninterface ProviderIconProps {\n  /** The option's icon */\n  icon?: React.ReactNode;\n  /** Classes of the camera drawn without an icon */\n  fallbackClassName?: string;\n}\n\n/** A service's 16px icon, or a camera for one without an icon */\nfunction ProviderIcon({\n  icon,\n  fallbackClassName = EVENT_DETAIL_ICON_CLASS,\n}: ProviderIconProps) {\n  if (!icon) {\n    return <Video className={fallbackClassName} />;\n  }\n  return (\n    <span className=\"flex size-4 shrink-0 items-center justify-center [&>svg]:size-4\">\n      {icon}\n    </span>\n  );\n}\n\n/**\n * Props for ConferencingMenuContent\n */\ninterface ConferencingMenuContentProps {\n  providers: ConferenceProviderOption[];\n  /** Whether the event has a call, which adds \"No conferencing\" */\n  hasCall: boolean;\n  /** Option of the event's call, checked in the list */\n  currentOption?: ConferenceProviderOption;\n  onPick: (option: ConferenceProviderOption) => void;\n  onRemove: () => void;\n  /** Called with the item under the pointer or keyboard, previewed in the trigger */\n  onPreview: (option: ConferenceProviderOption | null) => void;\n  /** Closes the menu (on Escape) */\n  onClose: () => void;\n}\n\n/**\n * Notion's conferencing menu: \"No conferencing\" once a call is set, then\n * each service with a check on the current one and its hint (e.g.\n * \"Connect\") at the end\n */\nfunction ConferencingMenuContent({\n  providers,\n  hasCall,\n  currentOption,\n  onPick,\n  onRemove,\n  onPreview,\n  onClose,\n}: ConferencingMenuContentProps) {\n  return (\n    <DropdownMenuContent\n      align=\"start\"\n      side=\"left\"\n      sideOffset={13}\n      className={cn(\"min-w-[227px]\", EVENT_DETAIL_MENU_CLASS)}\n      onMouseLeave={() => onPreview(null)}\n      onKeyDown={closeMenuOnEscape(onClose)}\n    >\n      {hasCall && (\n        <>\n          <DropdownMenuItem\n            className={MENU_ITEM_CLASS}\n            onClick={onRemove}\n            onMouseEnter={() => onPreview(null)}\n          >\n            <span className=\"w-4 shrink-0\" />\n            <VideoOff className=\"size-4 text-white\" />\n            No conferencing\n          </DropdownMenuItem>\n          {providers.length > 0 && (\n            <DropdownMenuSeparator className=\"bg-[#303030]\" />\n          )}\n        </>\n      )}\n      {providers.map((option) => (\n        <DropdownMenuItem\n          key={option.label}\n          className={MENU_ITEM_CLASS}\n          onClick={() => onPick(option)}\n          onMouseEnter={() => onPreview(option)}\n          onFocus={() => onPreview(option)}\n        >\n          <span className=\"flex w-4 shrink-0 items-center justify-center\">\n            {option === currentOption && (\n              <Check className=\"size-4 text-white\" />\n            )}\n          </span>\n          <ProviderIcon\n            icon={option.icon}\n            fallbackClassName={MENU_ICON_CLASS}\n          />\n          <span className=\"flex-1\">{option.label}</span>\n          {option.hint && (\n            <span className={cn(\"ml-3\", EVENT_DETAIL_MENU_SECONDARY_CLASS)}>\n              {option.hint}\n            </span>\n          )}\n        </DropdownMenuItem>\n      ))}\n    </DropdownMenuContent>\n  );\n}\n\n/**\n * The event's video call, as in Notion Calendar. Without one, a muted\n * \"Conferencing\" row opens the services menu; an option whose\n * `createConference` is async shows as pending until its call arrives.\n * With one, the service's icon and name (a link that joins the call) and\n * its meeting code, with a copy link button and the menu (switch service,\n * \"No conferencing\") on hover. Services come from `CalendarProvider`'s\n * `conferenceProviders`; without any, the row is hidden unless the event\n * already has a call.\n */\nexport function EventDetailConferencing<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const { conferenceProviders: providers } = useCalendarConfig();\n  const conference = event.conference;\n  const sectionRef = React.useRef<HTMLDivElement>(null);\n  const joinRef = React.useRef<HTMLAnchorElement>(null);\n  /** The latest event and handler, for a call that arrives after a wait */\n  const eventRef = React.useRef(event);\n  const onEventChangeRef = React.useRef(onEventChange);\n  /** Bumped by every change, so only the latest pending call is applied */\n  const requestRef = React.useRef(0);\n  /** Set when a pending call arrives with focus in the row: focus moves to it */\n  const focusCallRef = React.useRef(false);\n  const [menuOpen, setMenuOpen] = React.useState(false);\n  /** Service under the pointer while the empty row's menu is open */\n  const [preview, setPreview] = React.useState<ConferenceProviderOption | null>(\n    null,\n  );\n  const [pending, setPending] = React.useState<PendingConference | null>(null);\n  const [copied, setCopied] = React.useState(false);\n\n  React.useEffect(() => {\n    eventRef.current = event;\n    onEventChangeRef.current = onEventChange;\n  }, [event, onEventChange]);\n\n  // A call that arrives after the panel closes is dropped\n  React.useEffect(() => {\n    const requests = requestRef;\n    return () => {\n      requests.current += 1;\n    };\n  }, []);\n\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(false), 1500);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n\n  React.useEffect(() => {\n    if (!conference || !focusCallRef.current) return;\n    focusCallRef.current = false;\n    joinRef.current?.focus();\n  }, [conference]);\n\n  const currentOption = conference\n    ? findOption(providers, conference)\n    : undefined;\n  const pendingOption =\n    pending?.eventId === event.id ? pending.option : undefined;\n\n  if (!conference && providers.length === 0) return null;\n\n  const handleOpenChange = (open: boolean) => {\n    if (open && pendingOption) return;\n    setMenuOpen(open);\n    if (!open) setPreview(null);\n  };\n\n  const setCall = (next: EventConference | undefined) => {\n    requestRef.current += 1;\n    setPending(null);\n    onEventChange?.({ ...event, conference: next });\n  };\n\n  const pick = (option: ConferenceProviderOption) => {\n    if (option === currentOption) return;\n    const result = option.createConference(event);\n    if (!isPromiseLike(result)) {\n      // Picked from the menu, which hands focus back to the row\n      focusCallRef.current = true;\n      setCall({ ...result, label: option.label });\n      return;\n    }\n\n    requestRef.current += 1;\n    const request = requestRef.current;\n    const eventId = event.id;\n    setPending({ option, eventId });\n    result.then(\n      (created) => {\n        if (request !== requestRef.current) return;\n        setPending(null);\n        const latest = eventRef.current;\n        if (latest.id !== eventId) return;\n        focusCallRef.current =\n          sectionRef.current?.contains(document.activeElement) ?? false;\n        onEventChangeRef.current?.({\n          ...latest,\n          conference: { ...created, label: option.label },\n        });\n      },\n      () => {\n        if (request === requestRef.current) setPending(null);\n      },\n    );\n  };\n\n  const copyLink = () => {\n    if (!conference) return;\n    void navigator.clipboard?.writeText(conference.url).then(() => {\n      setCopied(true);\n    });\n  };\n\n  const shown = pendingOption ?? preview;\n  /** The call the row shows: none while a new one is being created */\n  const shownCall = pendingOption ? undefined : conference;\n  const callLabel = shownCall\n    ? (currentOption?.label ??\n      shownCall.label ??\n      PROVIDER_NAMES[shownCall.provider])\n    : \"\";\n\n  return (\n    <EventDetailSection name=\"conferencing\" ref={sectionRef}>\n      {/* One menu for both states, so focus returns to the call's menu\n          button once a pick replaces the empty row */}\n      <DropdownMenu open={menuOpen} onOpenChange={handleOpenChange}>\n        <div className=\"flex min-h-[35px] items-center px-2\">\n          {shownCall ? (\n            <div\n              className={cn(\n                \"group/conferencing\",\n                ROW_BOX_CLASS,\n                \"gap-2\",\n                EVENT_DETAIL_HOVER_BORDER_CLASS,\n                // Keyboard focus in the row shows its hover border\n                \"has-[:focus-visible]:border-[#E8E8E4] dark:has-[:focus-visible]:border-[#373737]\",\n                menuOpen && \"border-[#E8E8E4] dark:border-[#373737]\",\n              )}\n            >\n              <a\n                ref={joinRef}\n                href={shownCall.url}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                aria-label={`Join ${callLabel}`}\n                data-testid=\"event-conference-join\"\n                className=\"flex shrink-0 items-center gap-[11px] outline-none\"\n              >\n                <ProviderIcon icon={currentOption?.icon} />\n                <span className={cn(\"shrink-0\", EVENT_DETAIL_TEXT_CLASS)}>\n                  {callLabel}\n                </span>\n              </a>\n              {shownCall.meetingId && (\n                <span\n                  className={cn(\n                    \"min-w-0 truncate\",\n                    EVENT_DETAIL_PLACEHOLDER_CLASS,\n                  )}\n                >\n                  {shownCall.meetingId}\n                </span>\n              )}\n              <button\n                type=\"button\"\n                aria-label={copied ? \"Link copied\" : \"Copy link\"}\n                title={copied ? \"Copied\" : \"Copy link\"}\n                className={cn(\n                  \"hidden size-5 shrink-0 items-center justify-center rounded-sm group-focus-within/conferencing:flex group-hover/conferencing:flex\",\n                  (menuOpen || copied) && \"flex\",\n                  EVENT_DETAIL_SECONDARY_CLASS,\n                )}\n                onClick={copyLink}\n              >\n                {copied ? (\n                  <Check className=\"size-3.5\" />\n                ) : (\n                  <Link2 className=\"size-3.5 -rotate-45\" />\n                )}\n              </button>\n              <span className=\"flex-1\" />\n              {onEventChange && (\n                <DropdownMenuTrigger asChild>\n                  <button\n                    type=\"button\"\n                    aria-label=\"Change conferencing\"\n                    className={cn(\n                      \"hidden size-5 shrink-0 items-center justify-center group-focus-within/conferencing:flex group-hover/conferencing:flex\",\n                      menuOpen && \"flex\",\n                      EVENT_DETAIL_MUTED_CLASS,\n                    )}\n                  >\n                    <ChevronDown className=\"size-4\" />\n                  </button>\n                </DropdownMenuTrigger>\n              )}\n            </div>\n          ) : (\n            <DropdownMenuTrigger asChild>\n              <button\n                type=\"button\"\n                disabled={!onEventChange}\n                aria-busy={pendingOption ? true : undefined}\n                aria-label={\n                  pendingOption\n                    ? `Creating ${pendingOption.label} call`\n                    : undefined\n                }\n                data-testid=\"event-conferencing-trigger\"\n                className={cn(\n                  \"group/conferencing text-left\",\n                  ROW_BOX_CLASS,\n                  EVENT_DETAIL_HOVER_BORDER_CLASS,\n                  menuOpen && PANEL_TRIGGER_OPEN_CLASS,\n                )}\n              >\n                <ProviderIcon icon={shown?.icon} />\n                <span\n                  className={cn(\n                    \"flex-1 truncate\",\n                    shown\n                      ? EVENT_DETAIL_TEXT_CLASS\n                      : EVENT_DETAIL_PLACEHOLDER_CLASS,\n                  )}\n                >\n                  {shown ? shown.label : \"Conferencing\"}\n                </span>\n                {pendingOption ? (\n                  <LoaderCircle\n                    className={cn(\n                      \"size-4 shrink-0 animate-spin\",\n                      EVENT_DETAIL_MUTED_CLASS,\n                    )}\n                  />\n                ) : (\n                  <ChevronDown\n                    className={cn(\n                      \"size-4 shrink-0 opacity-0 group-hover/conferencing:opacity-100\",\n                      menuOpen && \"opacity-100\",\n                      EVENT_DETAIL_MUTED_CLASS,\n                    )}\n                  />\n                )}\n              </button>\n            </DropdownMenuTrigger>\n          )}\n        </div>\n        <ConferencingMenuContent\n          providers={providers}\n          hasCall={Boolean(conference)}\n          currentOption={currentOption}\n          onPick={pick}\n          onRemove={() => setCall(undefined)}\n          onPreview={setPreview}\n          onClose={() => handleOpenChange(false)}\n        />\n      </DropdownMenu>\n      {conference && <EventDetailDivider className=\"my-2\" />}\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-ai-notes.tsx",
      "content": "\"use client\";\n\nimport { NotepadText, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailSection,\n  ROW_BOX_CLASS,\n} from \"./event-detail-parts\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/**\n * AI meeting notes, as in Notion Calendar. Off: a muted \"Add AI meeting\n * notes\" row, or, once the event has a call, Notion's full-width \"Add\n * meeting note\" button (the panel shows it above the call; Notion's\n * chevron menu is left out). On: \"AI meeting notes\" with a button that\n * turns them off. Toggles `aiMeetingNotes`.\n */\nexport function EventDetailAiNotes<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const setNotes = (on: boolean) => {\n    onEventChange?.({ ...event, aiMeetingNotes: on ? true : undefined });\n  };\n\n  if (event.aiMeetingNotes) {\n    return (\n      <EventDetailSection name=\"ai-notes\">\n        <div className=\"flex min-h-[35px] items-center px-2\">\n          <div className={cn(\"group/ai-notes\", ROW_BOX_CLASS)}>\n            <NotepadText className={EVENT_DETAIL_ICON_CLASS} />\n            <span className={cn(\"flex-1 truncate\", EVENT_DETAIL_TEXT_CLASS)}>\n              AI meeting notes\n            </span>\n            {onEventChange && (\n              <button\n                type=\"button\"\n                aria-label=\"Turn off AI meeting notes\"\n                title=\"Turn off AI meeting notes\"\n                className={cn(\n                  \"flex size-5 shrink-0 items-center justify-center opacity-0 group-hover/ai-notes:opacity-100 focus-visible:opacity-100\",\n                  EVENT_DETAIL_SECONDARY_CLASS,\n                )}\n                onClick={() => setNotes(false)}\n              >\n                <X className=\"size-4\" />\n              </button>\n            )}\n          </div>\n        </div>\n      </EventDetailSection>\n    );\n  }\n\n  if (event.conference) {\n    return (\n      <EventDetailSection name=\"ai-notes\">\n        <div className=\"flex min-h-[35px] items-center px-2\">\n          <button\n            type=\"button\"\n            disabled={!onEventChange}\n            data-testid=\"event-ai-notes-button\"\n            className={cn(\n              \"flex h-8 flex-1 items-center rounded-md border border-[#F0F0F0] bg-[#FBFBFB] hover:bg-[#F5F5F5] dark:border-[#303030] dark:bg-[#282828] dark:hover:bg-[#2E2E2E]\",\n              EVENT_DETAIL_TEXT_CLASS,\n            )}\n            onClick={() => setNotes(true)}\n          >\n            <span className=\"flex flex-1 items-center justify-center gap-1.5\">\n              <NotepadText className=\"size-4\" />\n              Add meeting note\n            </span>\n          </button>\n        </div>\n      </EventDetailSection>\n    );\n  }\n\n  return (\n    <EventDetailSection name=\"ai-notes\">\n      <div className=\"flex min-h-[35px] items-center px-2\">\n        <button\n          type=\"button\"\n          disabled={!onEventChange}\n          data-testid=\"event-ai-notes-button\"\n          className={cn(\n            \"text-left\",\n            ROW_BOX_CLASS,\n            EVENT_DETAIL_HOVER_BORDER_CLASS,\n          )}\n          onClick={() => setNotes(true)}\n        >\n          <NotepadText\n            className={cn(\"size-4 shrink-0\", EVENT_DETAIL_MUTED_CLASS)}\n          />\n          <span className={cn(\"truncate\", EVENT_DETAIL_PLACEHOLDER_CLASS)}>\n            Add AI meeting notes\n          </span>\n        </button>\n      </div>\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-location.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { MapPin, Pencil } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n  EVENT_DETAIL_LINK_CLASS,\n  EVENT_DETAIL_MENU_SECONDARY_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailSection,\n  ROW_BOX_CLASS,\n} from \"./event-detail-parts\";\nimport {\n  EVENT_DETAIL_INPUT_PLACEHOLDER_CLASS,\n  EventDetailSuggestion,\n  EventDetailSuggestions,\n  HighlightedMatch,\n  handleSuggestionKey,\n} from \"./event-detail-suggestions\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n  LocationSuggestion,\n} from \"./week-view-types\";\n\n/** Width of the suggestions list (Notion: 292px) */\nconst SUGGESTIONS_WIDTH = 292;\n\n/** Most places listed under the typed text */\nconst MAX_SUGGESTIONS = 5;\n\n/** A location that is a web address opens itself instead of a map */\nconst URL_PATTERN = /^https?:\\/\\/\\S+$/i;\n\n/** The location as it's saved: \"Central Park, New York, NY, USA\" */\nfunction formatSuggestion(place: LocationSuggestion): string {\n  return place.address ? `${place.name}, ${place.address}` : place.name;\n}\n\n/** Where the set location opens: itself when it's a link, else Google Maps */\nfunction getLocationHref(location: string): string {\n  if (URL_PATTERN.test(location)) return location;\n  return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(location)}`;\n}\n\n/**\n * Where the event happens, as in Notion Calendar. Empty: a \"Location\"\n * field; typing lists the typed text first, then matching places (name\n * over address) from `CalendarProvider`'s `locationSuggestions`. Set: the\n * location, underlined, opening in Google Maps (or itself, for a link);\n * clicking the rest of the row, or its edit button, edits it, and clearing\n * the text removes it. Escape restores the location from before editing.\n */\nexport function EventDetailLocation<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const { locationSuggestions } = useCalendarConfig();\n  const location = event.location ?? \"\";\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const listId = React.useId();\n  const [editing, setEditing] = React.useState(false);\n  const [text, setText] = React.useState(location);\n  const [open, setOpen] = React.useState(false);\n  const [activeIndex, setActiveIndex] = React.useState(-1);\n  const linkRef = React.useRef<HTMLAnchorElement>(null);\n  /** Set by Escape and by a pick, so the blur that follows doesn't commit */\n  const skipCommitRef = React.useRef(false);\n  /** Set when a key ends editing: focus goes back to the location */\n  const refocusRef = React.useRef(false);\n\n  // Follow the event while the field isn't being typed into\n  React.useEffect(() => {\n    if (!editing) setText(location);\n  }, [location, editing]);\n\n  // Focus the field when the set location switches to editing, and the\n  // location (the edit button comes next) when a key ends it\n  React.useEffect(() => {\n    if (!editing) {\n      if (!refocusRef.current) return;\n      refocusRef.current = false;\n      linkRef.current?.focus();\n      return;\n    }\n    inputRef.current?.focus();\n    inputRef.current?.select();\n  }, [editing]);\n\n  const trimmed = text.trim();\n\n  /** The typed text, then the places that match it */\n  const options = React.useMemo<LocationSuggestion[]>(() => {\n    if (!trimmed) return [];\n    const q = trimmed.toLowerCase();\n    const places = locationSuggestions\n      .filter((place) => formatSuggestion(place).toLowerCase().includes(q))\n      .filter((place) => formatSuggestion(place) !== trimmed)\n      .slice(0, MAX_SUGGESTIONS);\n    return [{ name: trimmed }, ...places];\n  }, [locationSuggestions, trimmed]);\n\n  const listOpen = open && options.length > 0;\n\n  // The typed text is active, as in Notion\n  React.useEffect(() => {\n    setActiveIndex(trimmed ? 0 : -1);\n  }, [trimmed]);\n\n  const commit = (next: string) => {\n    const value = next.trim();\n    setText(value);\n    if (value === location) return;\n    onEventChange?.({ ...event, location: value || undefined });\n  };\n\n  /**\n   * Leaves the field. After editing a set location, focus returns to the\n   * location\n   */\n  const finishEditing = () => {\n    refocusRef.current = editing;\n    inputRef.current?.blur();\n  };\n\n  const pick = (place: LocationSuggestion) => {\n    skipCommitRef.current = true;\n    commit(formatSuggestion(place));\n    setOpen(false);\n    finishEditing();\n  };\n\n  const handleBlur = () => {\n    setOpen(false);\n    setEditing(false);\n    if (skipCommitRef.current) {\n      skipCommitRef.current = false;\n      return;\n    }\n    commit(text);\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"Escape\") {\n      e.preventDefault();\n      e.stopPropagation();\n      skipCommitRef.current = true;\n      setText(location);\n      finishEditing();\n      return;\n    }\n    if (e.key === \"Enter\" && !listOpen) {\n      e.preventDefault();\n      finishEditing();\n      return;\n    }\n    if (!listOpen) return;\n    handleSuggestionKey(e, options.length, activeIndex, setActiveIndex, (i) =>\n      pick(options[i]),\n    );\n  };\n\n  const optionId = (index: number) => `${listId}-option-${index}`;\n\n  if (location && !editing) {\n    return (\n      <EventDetailSection name=\"location\">\n        <div className=\"flex min-h-[35px] items-center px-2\">\n          <div\n            className={cn(\n              \"group/location flex min-h-8 min-w-0 flex-1 cursor-text items-start gap-[11px] py-[5px] pr-2 pl-[9px]\",\n              EVENT_DETAIL_HOVER_BORDER_CLASS,\n            )}\n            onClick={onEventChange ? () => setEditing(true) : undefined}\n          >\n            <MapPin className={cn(\"mt-0.5\", EVENT_DETAIL_ICON_CLASS)} />\n            <a\n              ref={linkRef}\n              href={getLocationHref(location)}\n              target=\"_blank\"\n              rel=\"noreferrer\"\n              data-testid=\"event-location-link\"\n              className={cn(\n                \"min-w-0 cursor-pointer break-words group-hover/location:decoration-current\",\n                EVENT_DETAIL_LINK_CLASS,\n                EVENT_DETAIL_TEXT_CLASS,\n              )}\n              onClick={(e) => e.stopPropagation()}\n            >\n              {location}\n            </a>\n            {onEventChange && (\n              <>\n                <span className=\"flex-1\" />\n                {/* Shown on hover, and once the location has focus */}\n                <button\n                  type=\"button\"\n                  aria-label=\"Edit location\"\n                  title=\"Edit location\"\n                  className={cn(\n                    \"hidden size-5 shrink-0 items-center justify-center group-focus-within/location:flex group-hover/location:flex\",\n                    EVENT_DETAIL_MUTED_CLASS,\n                  )}\n                  onClick={() => setEditing(true)}\n                >\n                  <Pencil className=\"size-3.5\" />\n                </button>\n              </>\n            )}\n          </div>\n        </div>\n      </EventDetailSection>\n    );\n  }\n\n  return (\n    <EventDetailSection name=\"location\">\n      <div className=\"flex min-h-[35px] items-center px-2\">\n        <div\n          ref={boxRef}\n          className={cn(ROW_BOX_CLASS, EVENT_DETAIL_INPUT_GROUP_CLASS)}\n          onClick={() => inputRef.current?.focus()}\n        >\n          <MapPin className={EVENT_DETAIL_ICON_CLASS} />\n          <input\n            ref={inputRef}\n            type=\"text\"\n            role=\"combobox\"\n            aria-label=\"Location\"\n            aria-autocomplete=\"list\"\n            aria-expanded={listOpen}\n            aria-controls={listOpen ? listId : undefined}\n            aria-activedescendant={\n              listOpen && activeIndex >= 0 ? optionId(activeIndex) : undefined\n            }\n            data-testid=\"event-location-input\"\n            value={text}\n            placeholder=\"Location\"\n            readOnly={!onEventChange}\n            onChange={(e) => {\n              setText(e.target.value);\n              setOpen(true);\n            }}\n            onFocus={() => setOpen(true)}\n            onBlur={handleBlur}\n            onKeyDown={handleKeyDown}\n            className={cn(\n              \"min-w-0 flex-1\",\n              EVENT_DETAIL_GROUPED_INPUT_CLASS,\n              EVENT_DETAIL_TEXT_CLASS,\n              EVENT_DETAIL_INPUT_PLACEHOLDER_CLASS,\n            )}\n          />\n        </div>\n      </div>\n      {listOpen && (\n        <EventDetailSuggestions\n          id={listId}\n          label=\"Suggested places\"\n          anchorRef={boxRef}\n          width={SUGGESTIONS_WIDTH}\n        >\n          {options.map((place, index) => (\n            <EventDetailSuggestion\n              key={`${index}-${formatSuggestion(place)}`}\n              id={optionId(index)}\n              active={index === activeIndex}\n              onActivate={() => setActiveIndex(index)}\n              onSelect={() => pick(place)}\n            >\n              <span className=\"flex min-w-0 flex-1 flex-col leading-5\">\n                <span className=\"truncate\">\n                  {index === 0 ? (\n                    place.name\n                  ) : (\n                    <HighlightedMatch text={place.name} query={trimmed} />\n                  )}\n                </span>\n                {place.address && (\n                  <span\n                    className={cn(\n                      \"truncate\",\n                      EVENT_DETAIL_MENU_SECONDARY_CLASS,\n                    )}\n                  >\n                    {place.address}\n                  </span>\n                )}\n              </span>\n            </EventDetailSuggestion>\n          ))}\n        </EventDetailSuggestions>\n      )}\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-suggestions.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MENU_SECONDARY_CLASS,\n  EVENT_DETAIL_MENU_TEXT_CLASS,\n  getEventDetailPortalContainer,\n} from \"./event-detail-parts\";\n\n/** Gap between the suggestions and the field they belong to (Notion: 13px) */\nconst SUGGESTIONS_GAP = 13;\n\n/** Closest the suggestions get to the viewport's edges */\nconst VIEWPORT_MARGIN = 8;\n\n/** `EVENT_DETAIL_PLACEHOLDER_CLASS`'s colors on an input's placeholder */\nexport const EVENT_DETAIL_INPUT_PLACEHOLDER_CLASS =\n  \"placeholder:text-[#ABABA9] dark:placeholder:text-[#595959]\";\n\n/**\n * Props for EventDetailSuggestions\n */\ninterface EventDetailSuggestionsProps {\n  /** Id of the listbox, set as the field's `aria-controls` */\n  id: string;\n  /** Accessible name of the list, e.g. \"Suggested participants\" */\n  label: string;\n  /** The field's box: the list opens to its left, top-aligned */\n  anchorRef: React.RefObject<HTMLElement | null>;\n  /** Width in px (Notion: 330 for people, 292 for places) */\n  width: number;\n  /** Options (`EventDetailSuggestion`) */\n  children: React.ReactNode;\n  /**\n   * Option under the others, after a separator (e.g. \"View rooms and\n   * resources\"); the field counts it after them\n   */\n  footer?: React.ReactNode;\n}\n\ninterface SuggestionsPosition {\n  top: number;\n  left: number;\n}\n\n/**\n * Places the list left of the field, top-aligned, as Notion does beside\n * its panel. Without room on the left (a narrow window, a popover near the\n * edge), it drops below the field instead.\n */\nfunction getSuggestionsPosition(\n  anchor: DOMRect,\n  width: number,\n): SuggestionsPosition {\n  const left = anchor.left - SUGGESTIONS_GAP - width;\n  if (left >= VIEWPORT_MARGIN) {\n    return { top: anchor.top, left };\n  }\n  const maxLeft = window.innerWidth - width - VIEWPORT_MARGIN;\n  return {\n    top: anchor.bottom + 4,\n    left: Math.max(VIEWPORT_MARGIN, Math.min(anchor.left, maxLeft)),\n  };\n}\n\n/**\n * The floating list a details field shows while it's focused (the\n * participants' contacts, the location's places). The field keeps focus and\n * drives it as a combobox (`aria-activedescendant`), the footer's option\n * included; the list is a portal in the details' React tree, so the details\n * popover counts presses on it as inside. Rendered only while open.\n */\nexport function EventDetailSuggestions({\n  id,\n  label,\n  anchorRef,\n  width,\n  children,\n  footer,\n}: EventDetailSuggestionsProps) {\n  /** Marks the viewport's top-left corner as the list's `fixed` frame sees it */\n  const originRef = React.useRef<HTMLSpanElement>(null);\n  const [container, setContainer] = React.useState<HTMLElement | null>(null);\n  const [position, setPosition] = React.useState<SuggestionsPosition | null>(\n    null,\n  );\n\n  React.useLayoutEffect(() => {\n    const anchor = anchorRef.current;\n    if (anchor) setContainer(getEventDetailPortalContainer(anchor));\n  }, [anchorRef]);\n\n  // Follow the field while the page scrolls or resizes\n  React.useLayoutEffect(() => {\n    if (!container) return;\n    function update() {\n      const anchor = anchorRef.current;\n      const origin = originRef.current;\n      if (!anchor || !origin) return;\n      // A transformed dialog moves `fixed` boxes along with it\n      const offset = origin.getBoundingClientRect();\n      const next = getSuggestionsPosition(\n        anchor.getBoundingClientRect(),\n        width,\n      );\n      setPosition({\n        top: next.top - offset.top,\n        left: next.left - offset.left,\n      });\n    }\n    update();\n    window.addEventListener(\"resize\", update);\n    window.addEventListener(\"scroll\", update, true);\n    return () => {\n      window.removeEventListener(\"resize\", update);\n      window.removeEventListener(\"scroll\", update, true);\n    };\n  }, [anchorRef, container, width]);\n\n  if (!container) return null;\n\n  return ReactDOM.createPortal(\n    <>\n      <span\n        ref={originRef}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none fixed top-0 left-0 size-0\"\n      />\n      {position && (\n        <div\n          id={id}\n          role=\"listbox\"\n          aria-label={label}\n          data-slot=\"event-detail-suggestions\"\n          className={cn(\n            \"fixed z-[9999] overflow-hidden rounded-lg border p-1.5 text-sm font-medium shadow-md\",\n            EVENT_DETAIL_MENU_CLASS,\n          )}\n          style={{ top: position.top, left: position.left, width }}\n          // Presses keep focus in the field\n          onMouseDown={(e) => e.preventDefault()}\n        >\n          {children}\n          {footer && (\n            <>\n              <div\n                role=\"none\"\n                className=\"-mx-1.5 my-1.5 border-t border-[#303030]\"\n              />\n              {footer}\n            </>\n          )}\n        </div>\n      )}\n    </>,\n    container,\n  );\n}\n\n/**\n * Props for EventDetailSuggestion\n */\ninterface EventDetailSuggestionProps {\n  /** Element id, the field's `aria-activedescendant` while active */\n  id: string;\n  /** Whether the keyboard or pointer is on it */\n  active: boolean;\n  /** Called when the pointer moves onto it */\n  onActivate: () => void;\n  /** Picks it */\n  onSelect: () => void;\n  /** Text and icons */\n  children: React.ReactNode;\n  className?: string;\n}\n\n/**\n * One option of `EventDetailSuggestions`: 31px tall (taller with a second\n * line), with the #303030 highlight inset in the list\n */\nexport function EventDetailSuggestion({\n  id,\n  active,\n  onActivate,\n  onSelect,\n  children,\n  className,\n}: EventDetailSuggestionProps) {\n  return (\n    <div\n      id={id}\n      role=\"option\"\n      aria-selected={active}\n      className={cn(\n        \"flex min-h-[31px] cursor-default items-center gap-2 rounded-md px-2 py-1\",\n        EVENT_DETAIL_MENU_TEXT_CLASS,\n        active && \"bg-[#303030] text-white\",\n        className,\n      )}\n      onMouseMove={active ? undefined : onActivate}\n      onClick={onSelect}\n    >\n      {children}\n    </div>\n  );\n}\n\n/**\n * Props for HighlightedMatch\n */\ninterface HighlightedMatchProps {\n  /** Text shown */\n  text: string;\n  /** What was typed; its first match in `text` stays bright */\n  query: string;\n}\n\n/**\n * Text with the part that matches the query bright and the rest muted, as\n * Notion's suggestions show matches while typing. Without a query or a\n * match, the whole text keeps the item's color.\n */\nexport function HighlightedMatch({ text, query }: HighlightedMatchProps) {\n  const trimmed = query.trim();\n  const start = trimmed\n    ? text.toLowerCase().indexOf(trimmed.toLowerCase())\n    : -1;\n  if (start === -1) {\n    return <>{text}</>;\n  }\n  const end = start + trimmed.length;\n  return (\n    <>\n      <span className={EVENT_DETAIL_MENU_SECONDARY_CLASS}>\n        {text.slice(0, start)}\n      </span>\n      <span className=\"text-white\">{text.slice(start, end)}</span>\n      <span className={EVENT_DETAIL_MENU_SECONDARY_CLASS}>\n        {text.slice(end)}\n      </span>\n    </>\n  );\n}\n\n/**\n * Keyboard handling shared by the suggestion fields: arrows move the active\n * option (wrapping), Enter picks it. Returns whether the key was handled.\n */\nexport function handleSuggestionKey(\n  e: React.KeyboardEvent<HTMLInputElement>,\n  count: number,\n  activeIndex: number,\n  setActiveIndex: (index: number) => void,\n  onPick: (index: number) => void,\n): boolean {\n  if (e.key === \"ArrowDown\" && count > 0) {\n    e.preventDefault();\n    setActiveIndex(activeIndex < 0 ? 0 : (activeIndex + 1) % count);\n    return true;\n  }\n  if (e.key === \"ArrowUp\" && count > 0) {\n    e.preventDefault();\n    setActiveIndex(activeIndex <= 0 ? count - 1 : activeIndex - 1);\n    return true;\n  }\n  if (e.key === \"Enter\" && activeIndex >= 0 && activeIndex < count) {\n    e.preventDefault();\n    onPick(activeIndex);\n    return true;\n  }\n  return false;\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-links.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  autoUpdate,\n  flip,\n  offset,\n  shift,\n  useFloating,\n} from \"@floating-ui/react-dom\";\nimport {\n  Check,\n  CircleHelp,\n  Copy,\n  File,\n  FileArchive,\n  FileAudio,\n  FileImage,\n  FileSpreadsheet,\n  FileText,\n  FileVideo,\n  Link,\n  Paperclip,\n  X,\n} from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useHoverTooltip } from \"@/hooks/use-hover-tooltip\";\nimport { findDescriptionUrls } from \"./event-detail-description\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n  EVENT_DETAIL_LINK_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailPlaceholderRow,\n  EventDetailSection,\n  getEventDetailPortalContainer,\n} from \"./event-detail-parts\";\nimport type {\n  DetailedCalendarEvent,\n  EventAttachment,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** How long the copy button shows its check mark, in ms */\nconst COPIED_FEEDBACK_DURATION = 1500;\n\n/** Gap between a link row and the tooltip above it, in px */\nconst LINK_TOOLTIP_OFFSET = 10;\n\n/** Gap between the \"?\" of a description link and its tooltip, in px */\nconst HELP_TOOLTIP_OFFSET = 6;\n\n/** Gap between the panel's left edge and the add-link menu, in px */\nconst ADD_LINK_MENU_OFFSET = 8;\n\n/** Closest a floating layer comes to the window's edges, in px */\nconst VIEWPORT_PADDING = 8;\n\n/** A domain typed without a scheme, e.g. \"example.com/notes\" */\nconst BARE_DOMAIN_PATTERN = /^[\\w-]+(\\.[\\w-]+)+(:\\d+)?([/?#]\\S*)?$/;\n\n/** Floating layers sit above the panel and every calendar layer */\nconst FLOATING_LAYER_Z_CLASS = \"z-[9999]\";\n\n/** Schemes a link may open: web pages, never script or inline data */\nconst LINK_PROTOCOLS = [\"http:\", \"https:\"];\n\n/** A file can also open from the object URL made when it was attached here */\nconst ATTACHMENT_PROTOCOLS = [...LINK_PROTOCOLS, \"blob:\"];\n\n/** Base a relative address resolves against while its scheme is checked */\nconst RELATIVE_URL_BASE = \"https://relative.invalid\";\n\n/** Elements Tab can stop at, before checking they're shown */\nconst TABBABLE_SELECTOR =\n  'a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * A row of the list: Notion's 32px box, 8px in from the panel's edges, in\n * a 35px row, with its icon centered 26px from the edge and its text from\n * 45px like the panel's other rows\n */\nconst LINK_ROW_CLASS =\n  \"mx-2 my-[1.5px] flex min-h-8 items-center gap-[11px] border border-transparent pr-[7px] pl-[9px]\";\n\n/** The add row without an icon: its box starts 8px before the text column */\nconst INDENTED_ROW_CLASS =\n  \"my-[1.5px] mr-2 ml-[36px] flex min-h-8 items-center border pr-[7px] pl-2\";\n\n/** Text of an action control that turns to the panel's text color on hover */\nconst HOVER_TEXT_CLASS =\n  \"text-[#929292] hover:text-[#32302C] dark:text-[#7F7F7F] dark:hover:text-[#D4D4D4]\";\n\n/**\n * A row's end controls (remove, \"?\"): shown while the row is hovered or\n * focused, and always where nothing can hover\n */\nconst ROW_ACTION_CLASS =\n  \"opacity-0 group-focus-within/link:opacity-100 group-hover/link:opacity-100 [@media(hover:none)]:opacity-100\";\n\n/** Tooltips are dark in both themes, like Notion's */\nconst TOOLTIP_CLASS =\n  \"rounded-md border border-[#303030] bg-[#252525] px-2.5 py-1.5 text-sm leading-5 font-medium text-white shadow-md\";\n\n/** A menu option; the highlighted one gets `MENU_OPTION_ACTIVE_CLASS` */\nconst MENU_OPTION_CLASS =\n  \"flex w-full cursor-default gap-[9px] rounded-sm px-2 py-1.5 text-left text-sm leading-5 font-medium text-[#E1E1E1]\";\n\n/** The highlighted menu option: by pointer, arrow keys, or a typed link */\nconst MENU_OPTION_ACTIVE_CLASS = \"bg-[#303030] text-white\";\n\n/**\n * What the add-link menu offers: the typed link, or a file from the\n * computer while nothing is typed\n */\ntype AddLinkOption = { kind: \"link\"; url: string } | { kind: \"attach\" };\n\n/**\n * The address typed text links to (\"https://...\" or a bare domain), or\n * null when it isn't one: Notion only adds links\n */\nfunction parseLinkInput(text: string): string | null {\n  const trimmed = text.trim();\n  if (trimmed === \"\" || /\\s/.test(trimmed)) return null;\n\n  let candidate = trimmed;\n  if (!/^https?:\\/\\//i.test(trimmed)) {\n    if (!BARE_DOMAIN_PATTERN.test(trimmed)) return null;\n    candidate = `https://${trimmed}`;\n  }\n\n  try {\n    const { hostname } = new URL(candidate);\n    return hostname.includes(\".\") || hostname === \"localhost\"\n      ? candidate\n      : null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * `url` when it opens with one of `protocols`, else undefined. Links and\n * files come in with the event, so a `javascript:` or `data:` address must\n * never reach an `href`. A relative address keeps the page's own scheme.\n */\nfunction safeHref(\n  url: string,\n  protocols: readonly string[] = LINK_PROTOCOLS,\n): string | undefined {\n  try {\n    const { protocol } = new URL(url, RELATIVE_URL_BASE);\n    return protocols.includes(protocol) ? url : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Focuses what Tab reaches after `element`, skipping `layer`: Tab out of a\n * layer portaled away from the element it opened from\n */\nfunction focusNextTabbable(element: HTMLElement, layer: HTMLElement | null) {\n  const tabbables = Array.from(\n    element.ownerDocument.querySelectorAll<HTMLElement>(TABBABLE_SELECTOR),\n  ).filter(\n    (candidate) =>\n      candidate.tabIndex >= 0 &&\n      !layer?.contains(candidate) &&\n      !candidate.closest(\"[inert]\") &&\n      candidate.getClientRects().length > 0,\n  );\n  tabbables[tabbables.indexOf(element) + 1]?.focus();\n}\n\n/** File size the way Finder writes it: \"248 KB\", \"1.2 MB\" */\nfunction formatFileSize(bytes: number): string {\n  if (bytes < 1000) return `${bytes} B`;\n  const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n  let size = bytes / 1000;\n  let unit = 0;\n  while (size >= 1000 && unit < units.length - 1) {\n    size /= 1000;\n    unit += 1;\n  }\n  return `${size < 10 ? size.toFixed(1) : Math.round(size)} ${units[unit]}`;\n}\n\n/** Kind of file an attachment is, from its MIME type */\ntype FileKind = \"image\" | \"video\" | \"audio\" | \"sheet\" | \"archive\" | \"text\";\n\n/** Kind of file a MIME type names, or null for any other file */\nfunction fileKind(type: string | undefined): FileKind | null {\n  if (!type) return null;\n  if (type.startsWith(\"image/\")) return \"image\";\n  if (type.startsWith(\"video/\")) return \"video\";\n  if (type.startsWith(\"audio/\")) return \"audio\";\n  if (type.includes(\"spreadsheet\") || type.includes(\"csv\")) return \"sheet\";\n  if (/zip|compressed|tar|rar|7z/.test(type)) return \"archive\";\n  if (type === \"application/pdf\" || type.startsWith(\"text/\")) return \"text\";\n  if (type.includes(\"document\") || type.includes(\"msword\")) return \"text\";\n  return null;\n}\n\n/** Icon for each kind of file */\nconst FILE_KIND_ICONS: Record<FileKind, LucideIcon> = {\n  image: FileImage,\n  video: FileVideo,\n  audio: FileAudio,\n  sheet: FileSpreadsheet,\n  archive: FileArchive,\n  text: FileText,\n};\n\n/** An attached file's icon, picked by its MIME type */\nfunction FileTypeIcon({ type }: { type: string | undefined }) {\n  const kind = fileKind(type);\n  return React.createElement(kind ? FILE_KIND_ICONS[kind] : File, {\n    className: EVENT_DETAIL_ICON_CLASS,\n  });\n}\n\n/**\n * Props for FloatingLayer\n */\ninterface FloatingLayerProps extends React.ComponentProps<\"div\"> {\n  /** Element the layer belongs to, which picks where it mounts */\n  owner: Element;\n}\n\n/**\n * A layer portaled out of the panel. `data-calendar-popover` tells the\n * calendar a press here is inside the event details, so it doesn't close\n * or deselect them.\n */\nfunction FloatingLayer({ owner, className, ...props }: FloatingLayerProps) {\n  return createPortal(\n    <div\n      data-calendar-popover=\"\"\n      className={cn(FLOATING_LAYER_Z_CLASS, className)}\n      {...props}\n    />,\n    getEventDetailPortalContainer(owner),\n  );\n}\n\n/**\n * Props for HelpTooltipIcon\n */\ninterface HelpTooltipIconProps {\n  /** What the tooltip says */\n  label: string;\n  /** Called when the pointer enters (true) or leaves (false) the \"?\" */\n  onHoverChange?: (isHovered: boolean) => void;\n}\n\n/**\n * A \"?\" that explains itself in a dark tooltip above it, flush with its\n * right edge\n */\nfunction HelpTooltipIcon({ label, onHoverChange }: HelpTooltipIconProps) {\n  const [iconElement, setIconElement] = React.useState<HTMLElement | null>(\n    null,\n  );\n  const tooltip = useHoverTooltip();\n  const { refs, floatingStyles } = useFloating({\n    open: tooltip.isOpen,\n    placement: \"top-end\",\n    strategy: \"fixed\",\n    whileElementsMounted: autoUpdate,\n    middleware: [\n      offset(HELP_TOOLTIP_OFFSET),\n      shift({ padding: VIEWPORT_PADDING }),\n    ],\n  });\n\n  const setIcon = React.useCallback(\n    (node: HTMLElement | null) => {\n      refs.setReference(node);\n      setIconElement(node);\n    },\n    [refs],\n  );\n\n  const setTooltip = React.useCallback(\n    (node: HTMLElement | null) => refs.setFloating(node),\n    [refs],\n  );\n\n  return (\n    <span\n      ref={setIcon}\n      role=\"img\"\n      aria-label={label}\n      className={cn(\n        \"-mr-1 flex size-6 shrink-0 items-center justify-center\",\n        EVENT_DETAIL_TEXT_CLASS,\n      )}\n      onMouseEnter={() => {\n        tooltip.scheduleOpen();\n        onHoverChange?.(true);\n      }}\n      onMouseLeave={() => {\n        tooltip.scheduleClose();\n        onHoverChange?.(false);\n      }}\n    >\n      <CircleHelp className=\"size-4\" strokeWidth={1.5} />\n      {tooltip.isOpen && iconElement && (\n        <FloatingLayer\n          ref={setTooltip}\n          owner={iconElement}\n          role=\"tooltip\"\n          style={floatingStyles}\n          className={cn(TOOLTIP_CLASS, \"pointer-events-none whitespace-nowrap\")}\n        >\n          {label}\n        </FloatingLayer>\n      )}\n    </span>\n  );\n}\n\n/**\n * Props for LinkTooltip\n */\ninterface LinkTooltipProps {\n  url: string;\n  /** Row the tooltip is centered above */\n  owner: Element;\n  /**\n   * The row's link. Tab from it reaches the copy button; Shift+Tab and\n   * Escape go back to it, and Tab moves on to what follows it.\n   */\n  link: HTMLElement | null;\n  floatingRef: (node: HTMLElement | null) => void;\n  style: React.CSSProperties;\n  onMouseEnter: () => void;\n  onMouseLeave: () => void;\n  /** Focus left the copy button for somewhere other than the link */\n  onFocusLeave: () => void;\n}\n\n/**\n * The link's address with a copy button, in a dark tooltip above its row\n */\nfunction LinkTooltip({\n  url,\n  owner,\n  link,\n  floatingRef,\n  style,\n  onMouseEnter,\n  onMouseLeave,\n  onFocusLeave,\n}: LinkTooltipProps) {\n  const [layerElement, setLayerElement] = React.useState<HTMLElement | null>(\n    null,\n  );\n  const [isCopied, setIsCopied] = React.useState(false);\n\n  React.useEffect(() => {\n    if (!isCopied) return;\n    const timer = window.setTimeout(\n      () => setIsCopied(false),\n      COPIED_FEEDBACK_DURATION,\n    );\n    return () => window.clearTimeout(timer);\n  }, [isCopied]);\n\n  const setLayer = React.useCallback(\n    (node: HTMLElement | null) => {\n      floatingRef(node);\n      setLayerElement(node);\n    },\n    [floatingRef],\n  );\n\n  const copyUrl = React.useCallback(() => {\n    // A denied permission or an insecure page leaves the button as it was\n    navigator.clipboard\n      ?.writeText(url)\n      .then(() => setIsCopied(true))\n      .catch(() => {});\n  }, [url]);\n\n  // The layer is portaled away from the row, so Tab is routed by hand\n  const handleCopyKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLButtonElement>) => {\n      if (!link) return;\n      if (e.key === \"Escape\" || (e.key === \"Tab\" && e.shiftKey)) {\n        // Keep the calendar's Escape from deselecting the event\n        e.preventDefault();\n        e.stopPropagation();\n        link.focus();\n        return;\n      }\n      if (e.key !== \"Tab\") return;\n      e.preventDefault();\n      focusNextTabbable(link, layerElement);\n    },\n    [layerElement, link],\n  );\n\n  const handleCopyBlur = React.useCallback(\n    (e: React.FocusEvent<HTMLButtonElement>) => {\n      if (link && e.relatedTarget === link) return;\n      onFocusLeave();\n    },\n    [link, onFocusLeave],\n  );\n\n  return (\n    <FloatingLayer\n      ref={setLayer}\n      owner={owner}\n      role=\"tooltip\"\n      style={style}\n      onMouseEnter={onMouseEnter}\n      onMouseLeave={onMouseLeave}\n      className={cn(TOOLTIP_CLASS, \"flex max-w-[280px] items-center gap-2\")}\n    >\n      <span className=\"truncate\">{url}</span>\n      <button\n        type=\"button\"\n        aria-label={isCopied ? \"Link copied\" : \"Copy link\"}\n        onClick={copyUrl}\n        onKeyDown={handleCopyKeyDown}\n        onBlur={handleCopyBlur}\n        className=\"flex size-4 shrink-0 items-center justify-center rounded-sm text-[#9B9B9B] outline-none hover:text-white focus-visible:text-white focus-visible:ring-1 focus-visible:ring-white/60\"\n      >\n        {isCopied ? (\n          <Check className=\"size-3.5\" />\n        ) : (\n          <Copy className=\"size-3.5\" />\n        )}\n      </button>\n    </FloatingLayer>\n  );\n}\n\n/**\n * Props for LinkRow\n */\ninterface LinkRowProps {\n  url: string;\n  /** Text shown for the link: its title, or the address */\n  label: string;\n  /** Removes the link; leave out when it can't be removed here */\n  onRemove?: () => void;\n  /**\n   * Whether the link comes from the description: a \"?\" explains that\n   * instead of a remove button\n   */\n  isFromDescription?: boolean;\n}\n\n/**\n * A link: icon and underlined text that opens it. Hovering shows the\n * address above the row, and a remove button (or a \"?\" for a link written\n * in the description) at its end; Tab onto the link shows the address too.\n * An address that isn't a web page shows as text that opens nothing.\n */\nfunction LinkRow({ url, label, onRemove, isFromDescription }: LinkRowProps) {\n  const href = safeHref(url);\n\n  const [rowElement, setRowElement] = React.useState<HTMLElement | null>(null);\n  const [linkElement, setLinkElement] =\n    React.useState<HTMLAnchorElement | null>(null);\n  /** The \"?\" shows its own tooltip, in place of the address */\n  const [isHelpHovered, setIsHelpHovered] = React.useState(false);\n  /** The link or the tooltip's copy button has keyboard focus */\n  const [hasKeyboardFocus, setHasKeyboardFocus] = React.useState(false);\n  const tooltip = useHoverTooltip();\n  const isTooltipOpen = tooltip.isOpen || hasKeyboardFocus;\n  const { refs, floatingStyles } = useFloating({\n    open: isTooltipOpen,\n    placement: \"top\",\n    strategy: \"fixed\",\n    whileElementsMounted: autoUpdate,\n    middleware: [\n      offset(LINK_TOOLTIP_OFFSET),\n      shift({ padding: VIEWPORT_PADDING }),\n    ],\n  });\n\n  const setRow = React.useCallback(\n    (node: HTMLElement | null) => {\n      refs.setReference(node);\n      setRowElement(node);\n    },\n    [refs],\n  );\n\n  const setTooltip = React.useCallback(\n    (node: HTMLElement | null) => refs.setFloating(node),\n    [refs],\n  );\n\n  const handleLinkFocus = React.useCallback(\n    (e: React.FocusEvent<HTMLAnchorElement>) => {\n      if (e.currentTarget.matches(\":focus-visible\")) setHasKeyboardFocus(true);\n    },\n    [],\n  );\n\n  // Moving on to the tooltip's copy button keeps it open\n  const handleLinkBlur = React.useCallback(\n    (e: React.FocusEvent<HTMLAnchorElement>) => {\n      const next = e.relatedTarget;\n      if (next instanceof Node && refs.floating.current?.contains(next)) {\n        return;\n      }\n      setHasKeyboardFocus(false);\n    },\n    [refs],\n  );\n\n  // Tab goes from the link into its tooltip, which is portaled elsewhere\n  const handleLinkKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLAnchorElement>) => {\n      if (e.key !== \"Tab\" || e.shiftKey || !hasKeyboardFocus) return;\n      const layer = refs.floating.current;\n      const copyButton = layer?.querySelector(\"button\");\n      if (!copyButton) return;\n      e.preventDefault();\n      copyButton.focus();\n    },\n    [hasKeyboardFocus, refs],\n  );\n\n  const handleTooltipFocusLeave = React.useCallback(\n    () => setHasKeyboardFocus(false),\n    [],\n  );\n\n  return (\n    <div\n      ref={setRow}\n      data-link-url={url}\n      className={cn(LINK_ROW_CLASS, \"group/link\")}\n      onMouseEnter={tooltip.scheduleOpen}\n      onMouseLeave={tooltip.scheduleClose}\n    >\n      <span className=\"flex w-4 shrink-0 items-center justify-center\">\n        <Link className={EVENT_DETAIL_ICON_CLASS} />\n      </span>\n      <a\n        ref={setLinkElement}\n        href={href}\n        target=\"_blank\"\n        rel=\"noopener noreferrer\"\n        onFocus={handleLinkFocus}\n        onBlur={handleLinkBlur}\n        onKeyDown={handleLinkKeyDown}\n        className={cn(\n          \"min-w-0 truncate\",\n          EVENT_DETAIL_TEXT_CLASS,\n          href && EVENT_DETAIL_LINK_CLASS,\n        )}\n      >\n        {label}\n      </a>\n      <span\n        className={cn(\"ml-auto flex shrink-0 items-center\", ROW_ACTION_CLASS)}\n      >\n        {isFromDescription && (\n          <HelpTooltipIcon\n            label=\"Linked in event description\"\n            onHoverChange={setIsHelpHovered}\n          />\n        )}\n        {!isFromDescription && onRemove && (\n          <button\n            type=\"button\"\n            aria-label={`Remove ${label}`}\n            onClick={onRemove}\n            className={cn(\n              \"-mr-1.5 flex size-6 items-center justify-center\",\n              HOVER_TEXT_CLASS,\n            )}\n          >\n            <X className=\"size-5\" strokeWidth={1.5} />\n          </button>\n        )}\n      </span>\n      {isTooltipOpen && !isHelpHovered && rowElement && (\n        <LinkTooltip\n          url={url}\n          owner={rowElement}\n          link={linkElement}\n          floatingRef={setTooltip}\n          style={floatingStyles}\n          onMouseEnter={tooltip.keepOpen}\n          onMouseLeave={tooltip.scheduleClose}\n          onFocusLeave={handleTooltipFocusLeave}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * Props for AttachmentRow\n */\ninterface AttachmentRowProps {\n  attachment: EventAttachment;\n  /** Removes the file; leave out for read-only details */\n  onRemove?: () => void;\n}\n\n/**\n * An attached file: its type's icon, its name (opening the file), its size\n * muted after it, and a remove button on hover. A file whose address isn't\n * a web page or an object URL shows its name only.\n */\nfunction AttachmentRow({ attachment, onRemove }: AttachmentRowProps) {\n  const href = safeHref(attachment.url, ATTACHMENT_PROTOCOLS);\n\n  return (\n    <div\n      data-attachment-name={attachment.name}\n      className={cn(LINK_ROW_CLASS, \"group/link\")}\n    >\n      <span className=\"flex w-4 shrink-0 items-center justify-center\">\n        <FileTypeIcon type={attachment.type} />\n      </span>\n      <a\n        href={href}\n        target=\"_blank\"\n        rel=\"noopener noreferrer\"\n        download={href?.startsWith(\"blob:\") ? attachment.name : undefined}\n        className={cn(\n          \"min-w-0 truncate\",\n          EVENT_DETAIL_TEXT_CLASS,\n          href && EVENT_DETAIL_LINK_CLASS,\n        )}\n      >\n        {attachment.name}\n      </a>\n      {attachment.size !== undefined && (\n        <span className={cn(\"shrink-0\", EVENT_DETAIL_SECONDARY_CLASS)}>\n          {formatFileSize(attachment.size)}\n        </span>\n      )}\n      {onRemove && (\n        <button\n          type=\"button\"\n          aria-label={`Remove ${attachment.name}`}\n          onClick={onRemove}\n          className={cn(\n            \"-mr-1.5 ml-auto flex size-6 shrink-0 items-center justify-center\",\n            HOVER_TEXT_CLASS,\n            ROW_ACTION_CLASS,\n          )}\n        >\n          <X className=\"size-5\" strokeWidth={1.5} />\n        </button>\n      )}\n    </div>\n  );\n}\n\n/**\n * Props for AddLinkMenu\n */\ninterface AddLinkMenuProps {\n  id: string;\n  /** The add row, whose top the menu lines up with */\n  owner: HTMLElement;\n  options: AddLinkOption[];\n  activeIndex: number;\n  onActiveIndexChange: (index: number) => void;\n  onChoose: (option: AddLinkOption) => void;\n}\n\n/**\n * Notion's add-link menu: to the left of the panel, its top level with the\n * input. It offers the typed link, or a file while nothing is typed. It\n * never takes focus from the input: the input drives it with the arrow keys\n * and Enter.\n */\nfunction AddLinkMenu({\n  id,\n  owner,\n  options,\n  activeIndex,\n  onActiveIndexChange,\n  onChoose,\n}: AddLinkMenuProps) {\n  const { refs, floatingStyles } = useFloating({\n    open: true,\n    placement: \"left-start\",\n    strategy: \"fixed\",\n    whileElementsMounted: autoUpdate,\n    middleware: [\n      offset(ADD_LINK_MENU_OFFSET),\n      flip({ fallbackPlacements: [\"bottom-start\"] }),\n      shift({ padding: VIEWPORT_PADDING }),\n    ],\n  });\n\n  const setMenu = React.useCallback(\n    (node: HTMLElement | null) => refs.setFloating(node),\n    [refs],\n  );\n\n  // Measure from the panel's left edge, at the input's height\n  React.useLayoutEffect(() => {\n    const edge = owner.closest(\"[data-section]\") ?? owner;\n    refs.setReference({\n      contextElement: owner,\n      getBoundingClientRect() {\n        const box = owner.getBoundingClientRect();\n        const left = edge.getBoundingClientRect().left;\n        return {\n          x: left,\n          y: box.top,\n          left,\n          top: box.top,\n          right: box.right,\n          bottom: box.bottom,\n          width: box.right - left,\n          height: box.height,\n        };\n      },\n    });\n  }, [owner, refs]);\n\n  const isLinkMenu = options.some((option) => option.kind === \"link\");\n\n  return (\n    <FloatingLayer\n      ref={setMenu}\n      owner={owner}\n      style={floatingStyles}\n      // Keep the input focused while an option is pressed\n      onMouseDown={(e) => e.preventDefault()}\n      className={cn(\n        \"rounded-md border p-1 shadow-md\",\n        EVENT_DETAIL_MENU_CLASS,\n        isLinkMenu ? \"w-[260px]\" : \"w-60\",\n      )}\n    >\n      <div id={id} role=\"listbox\" aria-label=\"Add links and attachments\">\n        {options.map((option, index) => (\n          <div\n            key={option.kind}\n            id={`${id}-${option.kind}`}\n            role=\"option\"\n            aria-selected={index === activeIndex}\n            onMouseEnter={() => onActiveIndexChange(index)}\n            onMouseLeave={() => onActiveIndexChange(-1)}\n            onClick={() => onChoose(option)}\n            className={cn(\n              MENU_OPTION_CLASS,\n              index === activeIndex && MENU_OPTION_ACTIVE_CLASS,\n            )}\n          >\n            {option.kind === \"link\" ? (\n              <>\n                <Link className=\"size-4 shrink-0 text-[#656565]\" />\n                <span className=\"truncate\">{option.url}</span>\n              </>\n            ) : (\n              <>\n                <Paperclip className=\"mt-px size-4 shrink-0\" />\n                <span className=\"flex flex-col gap-[3px]\">\n                  <span>Attach file</span>\n                  <span className=\"text-[#8A8A8A]\">\n                    Upload from your computer\n                  </span>\n                </span>\n              </>\n            )}\n          </div>\n        ))}\n      </div>\n    </FloatingLayer>\n  );\n}\n\n/**\n * Props for AddLinkRow\n */\ninterface AddLinkRowProps {\n  /** Whether the row leads with the link icon: only while the list is empty */\n  hasIcon: boolean;\n  onAddLink: (url: string) => void;\n  onAttachFiles: (files: File[]) => void;\n}\n\n/**\n * The muted \"Add links and attachments\" row. Clicking turns it into a\n * \"Paste link...\" input with Notion's menu beside the panel: Enter adds a\n * typed link, and with nothing typed the menu attaches a file instead.\n * Text that isn't a link is dropped. Escape closes the menu, then the input.\n */\nfunction AddLinkRow({ hasIcon, onAddLink, onAttachFiles }: AddLinkRowProps) {\n  const menuId = React.useId();\n\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const fileInputRef = React.useRef<HTMLInputElement>(null);\n  /**\n   * Set when the typed text was already handled (added, dropped or Escaped)\n   * so the blur that follows does nothing more\n   */\n  const isHandledRef = React.useRef(false);\n\n  const [rowElement, setRowElement] = React.useState<HTMLDivElement | null>(\n    null,\n  );\n  const [isEditing, setIsEditing] = React.useState(false);\n  const [text, setText] = React.useState(\"\");\n  const [isMenuOpen, setIsMenuOpen] = React.useState(false);\n  /** Option under the pointer or picked with the arrow keys; -1 for none */\n  const [activeIndex, setActiveIndex] = React.useState(-1);\n  /** Right after a link is added the row reads \"Paste link...\", as Notion's */\n  const [hasJustAdded, setHasJustAdded] = React.useState(false);\n\n  React.useLayoutEffect(() => {\n    if (isEditing) inputRef.current?.focus();\n  }, [isEditing]);\n\n  const typedUrl = parseLinkInput(text);\n  const options = React.useMemo<AddLinkOption[]>(() => {\n    if (text.trim() === \"\") return [{ kind: \"attach\" }];\n    if (typedUrl) return [{ kind: \"link\", url: typedUrl }];\n    return [];\n  }, [text, typedUrl]);\n  // A typed link is picked as soon as it's recognized\n  const highlightedIndex = typedUrl ? 0 : activeIndex;\n  const highlighted = options[highlightedIndex];\n\n  /** Leaves the input, after its text was handled */\n  const finish = React.useCallback(() => {\n    isHandledRef.current = true;\n    setText(\"\");\n    inputRef.current?.blur();\n  }, []);\n\n  const choose = React.useCallback(\n    (option: AddLinkOption) => {\n      if (option.kind === \"attach\") {\n        fileInputRef.current?.click();\n        return;\n      }\n      onAddLink(option.url);\n      setHasJustAdded(true);\n      finish();\n    },\n    [finish, onAddLink],\n  );\n\n  const handleFocus = React.useCallback(() => {\n    setIsMenuOpen(true);\n    setActiveIndex(-1);\n  }, []);\n\n  const handleBlur = React.useCallback(() => {\n    setIsEditing(false);\n    setIsMenuOpen(false);\n    if (isHandledRef.current) {\n      isHandledRef.current = false;\n      return;\n    }\n    // Leaving the input keeps a typed link, like the other fields' blur\n    setHasJustAdded(false);\n    setText(\"\");\n    if (typedUrl) {\n      onAddLink(typedUrl);\n      setHasJustAdded(true);\n    }\n  }, [onAddLink, typedUrl]);\n\n  const handleChange = React.useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      setText(e.target.value);\n      setIsMenuOpen(true);\n      setActiveIndex(-1);\n    },\n    [],\n  );\n\n  const handleKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLInputElement>) => {\n      if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n        if (options.length === 0) return;\n        e.preventDefault();\n        setIsMenuOpen(true);\n        const step = e.key === \"ArrowDown\" ? 1 : -1;\n        // From no option, Down picks the first and Up the last\n        const from = highlightedIndex < 0 && step < 0 ? 0 : highlightedIndex;\n        const next = from + step;\n        setActiveIndex(\n          ((next % options.length) + options.length) % options.length,\n        );\n        return;\n      }\n      if (e.key === \"Enter\") {\n        e.preventDefault();\n        if (isMenuOpen && highlighted) {\n          choose(highlighted);\n          return;\n        }\n        // Notion drops text that isn't a link\n        if (text.trim() !== \"\") {\n          setHasJustAdded(false);\n          finish();\n        }\n        return;\n      }\n      if (e.key !== \"Escape\") return;\n      // Keep the calendar's Escape from deselecting the event\n      e.preventDefault();\n      e.stopPropagation();\n      if (isMenuOpen && options.length > 0) {\n        setIsMenuOpen(false);\n        return;\n      }\n      setHasJustAdded(false);\n      finish();\n    },\n    [choose, finish, highlighted, highlightedIndex, isMenuOpen, options, text],\n  );\n\n  const handleFilesPicked = React.useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      const files = Array.from(e.target.files ?? []);\n      e.target.value = \"\";\n      if (files.length === 0) return;\n      onAttachFiles(files);\n    },\n    [onAttachFiles],\n  );\n\n  const rowClass = hasIcon ? LINK_ROW_CLASS : INDENTED_ROW_CLASS;\n  const icon = hasIcon && (\n    <span className=\"flex w-4 shrink-0 items-center justify-center\">\n      <Link className={EVENT_DETAIL_ICON_CLASS} />\n    </span>\n  );\n  const isMenuShown = isEditing && isMenuOpen && options.length > 0;\n\n  return (\n    <>\n      {isEditing ? (\n        <div\n          ref={setRowElement}\n          className={cn(rowClass, EVENT_DETAIL_INPUT_GROUP_CLASS)}\n          onClick={() => inputRef.current?.focus()}\n        >\n          {icon}\n          <input\n            ref={inputRef}\n            value={text}\n            placeholder=\"Paste link...\"\n            aria-label=\"Paste link\"\n            role=\"combobox\"\n            aria-autocomplete=\"list\"\n            aria-expanded={isMenuShown}\n            aria-controls={isMenuShown ? menuId : undefined}\n            aria-activedescendant={\n              isMenuShown && highlighted\n                ? `${menuId}-${highlighted.kind}`\n                : undefined\n            }\n            onChange={handleChange}\n            onFocus={handleFocus}\n            onBlur={handleBlur}\n            onKeyDown={handleKeyDown}\n            className={cn(\n              EVENT_DETAIL_GROUPED_INPUT_CLASS,\n              EVENT_DETAIL_TEXT_CLASS,\n              \"min-w-0 flex-1 placeholder:text-[#ABABA9] dark:placeholder:text-[#595959]\",\n            )}\n          />\n        </div>\n      ) : (\n        <button\n          type=\"button\"\n          onClick={() => setIsEditing(true)}\n          className={cn(rowClass, EVENT_DETAIL_HOVER_BORDER_CLASS, \"text-left\")}\n        >\n          {icon}\n          <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>\n            {hasJustAdded ? \"Paste link...\" : \"Add links and attachments\"}\n          </span>\n        </button>\n      )}\n      {isMenuShown && rowElement && (\n        <AddLinkMenu\n          id={menuId}\n          owner={rowElement}\n          options={options}\n          activeIndex={highlightedIndex}\n          onActiveIndexChange={setActiveIndex}\n          onChoose={choose}\n        />\n      )}\n      <input\n        ref={fileInputRef}\n        type=\"file\"\n        multiple\n        hidden\n        aria-label=\"Attach file\"\n        onChange={handleFilesPicked}\n      />\n    </>\n  );\n}\n\n/**\n * The event's links and attached files, then the links written in its\n * description (marked with a \"?\"), then the row that adds more. With none,\n * it's the muted \"Add links and attachments\" row alone. Files are kept as\n * name, size and type with an object URL; nothing is uploaded.\n */\nexport function EventDetailLinks<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const links = React.useMemo(() => event.links ?? [], [event.links]);\n  const attachments = React.useMemo(\n    () => event.attachments ?? [],\n    [event.attachments],\n  );\n  const descriptionUrls = React.useMemo(() => {\n    const linked = new Set(links.map((link) => link.url));\n    return findDescriptionUrls(event.description).filter(\n      (url) => !linked.has(url),\n    );\n  }, [event.description, links]);\n\n  const addLink = React.useCallback(\n    (url: string) => {\n      if (links.some((link) => link.url === url)) return;\n      onEventChange?.({ ...event, links: [...links, { url }] });\n    },\n    [event, links, onEventChange],\n  );\n\n  const removeLink = React.useCallback(\n    (index: number) => {\n      onEventChange?.({ ...event, links: links.filter((_, i) => i !== index) });\n    },\n    [event, links, onEventChange],\n  );\n\n  const attachFiles = React.useCallback(\n    (files: File[]) => {\n      const added = files.map<EventAttachment>((file) => ({\n        name: file.name,\n        url: URL.createObjectURL(file),\n        size: file.size,\n        type: file.type || undefined,\n      }));\n      onEventChange?.({ ...event, attachments: [...attachments, ...added] });\n    },\n    [attachments, event, onEventChange],\n  );\n\n  const removeAttachment = React.useCallback(\n    (index: number) => {\n      const removed = attachments[index];\n      if (removed?.url.startsWith(\"blob:\")) URL.revokeObjectURL(removed.url);\n      onEventChange?.({\n        ...event,\n        attachments: attachments.filter((_, i) => i !== index),\n      });\n    },\n    [attachments, event, onEventChange],\n  );\n\n  const isEmpty =\n    links.length === 0 &&\n    attachments.length === 0 &&\n    descriptionUrls.length === 0;\n\n  if (isEmpty && !onEventChange) {\n    return (\n      <EventDetailSection name=\"links\">\n        <EventDetailPlaceholderRow\n          icon={Link}\n          label=\"Add links and attachments\"\n        />\n      </EventDetailSection>\n    );\n  }\n\n  return (\n    <EventDetailSection name=\"links\">\n      {links.map((link, index) => (\n        <LinkRow\n          key={`${index}-${link.url}`}\n          url={link.url}\n          label={link.title ?? link.url}\n          onRemove={onEventChange ? () => removeLink(index) : undefined}\n        />\n      ))}\n      {attachments.map((attachment, index) => (\n        <AttachmentRow\n          key={`${index}-${attachment.url}`}\n          attachment={attachment}\n          onRemove={onEventChange ? () => removeAttachment(index) : undefined}\n        />\n      ))}\n      {descriptionUrls.map((url) => (\n        <LinkRow key={url} url={url} label={url} isFromDescription />\n      ))}\n      {onEventChange && (\n        <AddLinkRow\n          hasIcon={isEmpty}\n          onAddLink={addLink}\n          onAttachFiles={attachFiles}\n        />\n      )}\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-description.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_INPUT_CLASS,\n  EVENT_DETAIL_LINK_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_TEXT_CLASS,\n  EventDetailSection,\n} from \"./event-detail-parts\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** A web address in free text, up to the next space, quote or angle bracket */\nconst URL_PATTERN = /https?:\\/\\/[^\\s<>\"]+/g;\n\n/** Punctuation that ends the sentence around an address, not the address */\nconst TRAILING_PUNCTUATION_PATTERN = /[.,;:!?'\"]+$/;\n\n/**\n * Lines the description editor is tall enough for while it's edited, before\n * it grows with the text, as Notion's is\n */\nconst DESCRIPTION_MIN_LINES = 3;\n\n/**\n * The description box, read or edited: 8px in from the panel's edges, with\n * the text from 16px, one 32px line tall at rest in a 35px row, its lines\n * 20px apart, as Notion's\n */\nconst DESCRIPTION_BOX_CLASS =\n  \"mx-2 my-[1.5px] block rounded-sm border px-[7px] py-[5px] leading-5 break-words whitespace-pre-wrap\";\n\n/**\n * A run of description text; `url` is set when the run is a web address\n */\ninterface DescriptionPart {\n  text: string;\n  url?: string;\n}\n\n/**\n * Drops sentence punctuation from the end of an address, and a closing\n * parenthesis the address didn't open (\"(see https://example.com)\")\n */\nfunction trimUrl(raw: string): string {\n  let url = raw.replace(TRAILING_PUNCTUATION_PATTERN, \"\");\n  while (url.endsWith(\")\") && url.split(\")\").length > url.split(\"(\").length) {\n    url = url.slice(0, -1).replace(TRAILING_PUNCTUATION_PATTERN, \"\");\n  }\n  return url;\n}\n\n/**\n * Splits a description into plain text and the web addresses written in it\n */\nfunction splitDescriptionLinks(text: string): DescriptionPart[] {\n  const parts: DescriptionPart[] = [];\n  let end = 0;\n  for (const match of text.matchAll(URL_PATTERN)) {\n    const start = match.index ?? 0;\n    const url = trimUrl(match[0]);\n    if (start > end) parts.push({ text: text.slice(end, start) });\n    parts.push({ text: url, url });\n    end = start + url.length;\n  }\n  if (end < text.length) parts.push({ text: text.slice(end) });\n  return parts;\n}\n\n/**\n * The web addresses written in a description, each once, in order. Notion\n * lists them with the event's links.\n */\nexport function findDescriptionUrls(description: string | undefined): string[] {\n  if (!description) return [];\n  const urls = splitDescriptionLinks(description).flatMap((part) =>\n    part.url ? [part.url] : [],\n  );\n  return Array.from(new Set(urls));\n}\n\n/** Sets a textarea's height to fit its text; its `rows` keep the minimum */\nfunction fitToText(textarea: HTMLTextAreaElement) {\n  textarea.style.height = \"auto\";\n  const border = textarea.offsetHeight - textarea.clientHeight;\n  textarea.style.height = `${textarea.scrollHeight + border}px`;\n}\n\n/**\n * The description at rest: its text, with each web address a link, or a\n * muted \"Description\" when there's none\n */\nfunction DescriptionText({ description }: { description: string }) {\n  if (!description) {\n    return <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>Description</span>;\n  }\n\n  return (\n    <span className={EVENT_DETAIL_TEXT_CLASS}>\n      {splitDescriptionLinks(description).map((part, index) => {\n        if (!part.url) {\n          return <React.Fragment key={index}>{part.text}</React.Fragment>;\n        }\n        return (\n          <a\n            key={index}\n            href={part.url}\n            target=\"_blank\"\n            rel=\"noopener noreferrer\"\n            className={cn(EVENT_DETAIL_LINK_CLASS, \"cursor-pointer\")}\n          >\n            {part.text}\n          </a>\n        );\n      })}\n    </span>\n  );\n}\n\n/**\n * The event's notes. At rest they read as text whose web addresses are\n * links, or a muted \"Description\"; clicking (anywhere but a link) or Tab\n * turns them into an editor that is three lines tall and grows with the\n * text. Blur keeps the edit and Escape puts back the text from before. It\n * has no icon: the text starts on the panel's left column.\n */\nexport function EventDetailDescription<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const description = event.description ?? \"\";\n\n  const textareaRef = React.useRef<HTMLTextAreaElement>(null);\n  /** Set by Escape so the blur that follows doesn't commit */\n  const escapePressedRef = React.useRef(false);\n  /** Description when editing started, put back on Escape */\n  const descriptionOnFocusRef = React.useRef(description);\n  /**\n   * Set while a press is on the box: its focus waits for the click, which\n   * knows whether a link was pressed. Safari focuses the box, not the link.\n   */\n  const isPressingRef = React.useRef(false);\n\n  const [isEditing, setIsEditing] = React.useState(false);\n  const [text, setText] = React.useState(description);\n\n  // Follow the event while the description isn't being typed into\n  React.useEffect(() => {\n    if (isEditing) return;\n    setText(description);\n  }, [description, isEditing]);\n\n  // Open the editor with the caret after the text\n  React.useLayoutEffect(() => {\n    if (!isEditing) return;\n    const textarea = textareaRef.current;\n    if (!textarea) return;\n    textarea.focus();\n    textarea.setSelectionRange(textarea.value.length, textarea.value.length);\n  }, [isEditing]);\n\n  // Grow the editor with its text\n  React.useLayoutEffect(() => {\n    if (textareaRef.current) fitToText(textareaRef.current);\n  }, [text, isEditing]);\n\n  // Fit it again when a new panel width rewraps the text\n  React.useEffect(() => {\n    const textarea = textareaRef.current;\n    if (!isEditing || !textarea) return;\n    let width = textarea.offsetWidth;\n    const observer = new ResizeObserver(() => {\n      if (textarea.offsetWidth === width) return;\n      width = textarea.offsetWidth;\n      fitToText(textarea);\n    });\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [isEditing]);\n\n  const startEditing = React.useCallback(() => {\n    if (!onEventChange) return;\n    descriptionOnFocusRef.current = description;\n    setIsEditing(true);\n  }, [description, onEventChange]);\n\n  // The event takes the text on blur, so an address being typed doesn't\n  // show up in the links list one letter at a time\n  const handleChange = React.useCallback(\n    (e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value),\n    [],\n  );\n\n  const handleBlur = React.useCallback(() => {\n    setIsEditing(false);\n    if (escapePressedRef.current) {\n      escapePressedRef.current = false;\n      return;\n    }\n    if (text === description) return;\n    onEventChange?.({ ...event, description: text === \"\" ? undefined : text });\n  }, [description, event, onEventChange, text]);\n\n  const handleKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n      if (e.key !== \"Escape\") return;\n      // Keep the calendar's Escape from deselecting the event\n      e.preventDefault();\n      e.stopPropagation();\n      escapePressedRef.current = true;\n      setText(descriptionOnFocusRef.current);\n      textareaRef.current?.blur();\n    },\n    [],\n  );\n\n  const handleBoxPointerDown = React.useCallback(() => {\n    isPressingRef.current = true;\n  }, []);\n\n  // Tab onto the box opens the editor; a press leaves that to its click\n  const handleBoxFocus = React.useCallback(\n    (e: React.FocusEvent<HTMLDivElement>) => {\n      const isPress = isPressingRef.current;\n      isPressingRef.current = false;\n      if (isPress || e.target !== e.currentTarget) return;\n      startEditing();\n    },\n    [startEditing],\n  );\n\n  const handleBoxBlur = React.useCallback(() => {\n    isPressingRef.current = false;\n  }, []);\n\n  // A click opens the editor, unless it's on a link in the text\n  const handleBoxClick = React.useCallback(\n    (e: React.MouseEvent<HTMLDivElement>) => {\n      isPressingRef.current = false;\n      if (e.target instanceof Element && e.target.closest(\"a\")) return;\n      startEditing();\n    },\n    [startEditing],\n  );\n\n  if (isEditing) {\n    return (\n      <EventDetailSection name=\"description\">\n        <textarea\n          ref={textareaRef}\n          rows={DESCRIPTION_MIN_LINES}\n          value={text}\n          placeholder=\"Description\"\n          aria-label=\"Description\"\n          onChange={handleChange}\n          onBlur={handleBlur}\n          onKeyDown={handleKeyDown}\n          className={cn(\n            DESCRIPTION_BOX_CLASS,\n            EVENT_DETAIL_INPUT_CLASS,\n            EVENT_DETAIL_TEXT_CLASS,\n            \"resize-none overflow-hidden placeholder:text-[#ABABA9] dark:placeholder:text-[#595959]\",\n          )}\n        />\n      </EventDetailSection>\n    );\n  }\n\n  if (!onEventChange) {\n    return (\n      <EventDetailSection name=\"description\">\n        <div className={cn(DESCRIPTION_BOX_CLASS, \"border-transparent\")}>\n          <DescriptionText description={description} />\n        </div>\n      </EventDetailSection>\n    );\n  }\n\n  return (\n    <EventDetailSection name=\"description\">\n      <div\n        role=\"textbox\"\n        aria-multiline\n        aria-label=\"Description\"\n        tabIndex={0}\n        onPointerDown={handleBoxPointerDown}\n        onFocus={handleBoxFocus}\n        onBlur={handleBoxBlur}\n        onClick={handleBoxClick}\n        className={cn(\n          DESCRIPTION_BOX_CLASS,\n          \"cursor-text border-transparent\",\n          EVENT_DETAIL_HOVER_BORDER_CLASS,\n        )}\n      >\n        <DescriptionText description={description} />\n      </div>\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-calendar.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { Check, ChevronDown } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport { EVENT_COLOR_SWATCH_CLASS } from \"./event-context-menu\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  PANEL_MENU_ITEM_CLASS,\n  PANEL_MENU_ITEM_CURRENT_CLASS,\n  PANEL_MENU_LABEL_CLASS,\n  PANEL_MENU_SURFACE_CLASS,\n  PANEL_TRIGGER_OPEN_CLASS,\n  ROW_BOX_CLASS,\n  EventDetailSection,\n  EventDetailTooltip,\n  getPanelMenuSideOffset,\n  stopEscapePropagation,\n} from \"./event-detail-parts\";\nimport {\n  EVENT_COLORS,\n  groupCalendarsByEmail,\n  moveEventToCalendar,\n  resolveEventColor,\n} from \"@/lib/event-utils\";\nimport type {\n  CalendarInfo,\n  DetailedCalendarEvent,\n  EventColor,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** Name of each event color, shown in the swatch tooltips */\nconst COLOR_NAMES: Record<EventColor, string> = {\n  red: \"Red\",\n  orange: \"Orange\",\n  yellow: \"Yellow\",\n  green: \"Green\",\n  blue: \"Blue\",\n  purple: \"Purple\",\n  gray: \"Gray\",\n};\n\n/** A 14px color swatch */\nconst SWATCH_CLASS = \"size-3.5 shrink-0 rounded-[4px]\";\n\n/**\n * Props for CalendarSwatch\n */\ninterface CalendarSwatchProps {\n  /** Color of the event's calendar, when it is listed */\n  calendarColor?: EventColor;\n  /** The color the event is drawn in: its own, else its calendar's */\n  eventColor: EventColor;\n}\n\n/**\n * The calendar's color, with the event's own color in front of it when it\n * has a different one, as Notion draws it\n */\nfunction CalendarSwatch({ calendarColor, eventColor }: CalendarSwatchProps) {\n  if (!calendarColor || eventColor === calendarColor) {\n    return (\n      <span\n        data-testid=\"event-calendar-swatch\"\n        className={cn(SWATCH_CLASS, EVENT_COLOR_SWATCH_CLASS[eventColor])}\n      />\n    );\n  }\n\n  return (\n    <span\n      data-testid=\"event-calendar-swatch\"\n      className=\"relative h-3.5 w-[22px] shrink-0\"\n    >\n      <span\n        className={cn(\n          \"absolute top-0 left-0\",\n          SWATCH_CLASS,\n          EVENT_COLOR_SWATCH_CLASS[calendarColor],\n        )}\n      />\n      <span\n        className={cn(\n          \"absolute top-0 right-0\",\n          SWATCH_CLASS,\n          EVENT_COLOR_SWATCH_CLASS[eventColor],\n        )}\n      />\n    </span>\n  );\n}\n\n/**\n * Props for ColorSwatchItem\n */\ninterface ColorSwatchItemProps {\n  color: EventColor;\n  /** Whether the event is drawn in this color */\n  checked: boolean;\n  onPick: (color: EventColor) => void;\n  /** Called with the color while it is hovered or focused, null after */\n  onPreview: (color: EventColor | null) => void;\n}\n\n/**\n * One color of the picker's \"Event color\" row, with its name in a tooltip\n */\nfunction ColorSwatchItem({\n  color,\n  checked,\n  onPick,\n  onPreview,\n}: ColorSwatchItemProps) {\n  const [rect, setRect] = React.useState<DOMRect | null>(null);\n\n  const show = React.useCallback(\n    (e: React.SyntheticEvent<HTMLElement>) => {\n      setRect(e.currentTarget.getBoundingClientRect());\n      onPreview(color);\n    },\n    [color, onPreview],\n  );\n\n  const hide = React.useCallback(() => {\n    setRect(null);\n    onPreview(null);\n  }, [onPreview]);\n\n  return (\n    <DropdownMenuItem\n      aria-label={COLOR_NAMES[color]}\n      aria-checked={checked}\n      role=\"menuitemradio\"\n      data-color={color}\n      className=\"relative flex size-3.5 items-center justify-center rounded-[4px] p-0 focus:bg-transparent focus-visible:ring-2 focus-visible:ring-white/60\"\n      onClick={() => onPick(color)}\n      onMouseEnter={show}\n      onMouseLeave={hide}\n      onFocus={show}\n      onBlur={hide}\n    >\n      <span\n        className={cn(\n          \"absolute inset-0 rounded-[4px]\",\n          EVENT_COLOR_SWATCH_CLASS[color],\n        )}\n      />\n      {checked && (\n        <Check className=\"relative size-3 !text-black/55\" strokeWidth={2.5} />\n      )}\n      <EventDetailTooltip rect={rect}>{COLOR_NAMES[color]}</EventDetailTooltip>\n    </DropdownMenuItem>\n  );\n}\n\n/**\n * The calendar the event belongs to, with its color swatch. Opens a menu to\n * move the event to another calendar (grouped by account) and to give it its\n * own color.\n */\nexport function EventDetailCalendar<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const sectionRef = React.useRef<HTMLDivElement>(null);\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const [open, setOpen] = React.useState(false);\n  const [sideOffset, setSideOffset] = React.useState(0);\n  /** Color hovered or focused in the picker, previewed in the swatch */\n  const [previewColor, setPreviewColor] = React.useState<EventColor | null>(\n    null,\n  );\n  /** Whether an item of the open picker has been hovered or focused yet */\n  const [pointed, setPointed] = React.useState(false);\n  /** Calendar hovered or focused in the picker, previewed in the row */\n  const [previewCalendar, setPreviewCalendar] =\n    React.useState<CalendarInfo | null>(null);\n  const { calendars } = useCalendarConfig();\n\n  const groups = React.useMemo(\n    () => groupCalendarsByEmail(calendars),\n    [calendars],\n  );\n  const calendar = calendars.find((c) => c.id === event.calendarId);\n  /** The color the event is drawn in: its own, else its calendar's */\n  const eventColor = resolveEventColor(event, calendars);\n  const shownCalendar = previewCalendar ?? calendar;\n  /** The color the row shows: the previewed one, or the event's once moved */\n  const shownColor =\n    previewColor ??\n    (previewCalendar\n      ? resolveEventColor(\n          moveEventToCalendar(event, previewCalendar, calendars),\n          calendars,\n        )\n      : eventColor);\n  const name =\n    calendar?.name ?? event.calendarEmail ?? event.calendarId ?? \"Calendar\";\n  const shownName = previewCalendar?.name ?? name;\n\n  const handleOpenChange = React.useCallback((next: boolean) => {\n    setOpen(next);\n    if (!next) {\n      setPreviewColor(null);\n      setPreviewCalendar(null);\n      return;\n    }\n    setSideOffset(getPanelMenuSideOffset(triggerRef, sectionRef));\n    setPointed(false);\n  }, []);\n\n  const handleCalendarPick = React.useCallback(\n    (to: CalendarInfo) => {\n      if (to.id === event.calendarId) return;\n      onEventChange?.(moveEventToCalendar(event, to, calendars));\n    },\n    [event, calendars, onEventChange],\n  );\n\n  const handleColorPick = React.useCallback(\n    (color: EventColor) => {\n      if (color === event.color) return;\n      onEventChange?.({ ...event, color });\n    },\n    [event, onEventChange],\n  );\n\n  const swatchAndName = (\n    <>\n      <span className=\"flex w-4 shrink-0 items-center justify-center\">\n        <CalendarSwatch\n          calendarColor={shownCalendar?.color}\n          eventColor={shownColor}\n        />\n      </span>\n      <span className=\"min-w-0 flex-1 truncate\">{shownName}</span>\n    </>\n  );\n\n  // Read-only details: the calendar without its menu\n  if (!onEventChange) {\n    return (\n      <EventDetailSection name=\"calendar\" className=\"px-2\">\n        <div className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}>\n          <div className={cn(ROW_BOX_CLASS, \"border border-transparent\")}>\n            <span className=\"sr-only\">Calendar: </span>\n            {swatchAndName}\n          </div>\n        </div>\n      </EventDetailSection>\n    );\n  }\n\n  return (\n    <EventDetailSection ref={sectionRef} name=\"calendar\" className=\"px-2\">\n      <DropdownMenu open={open} onOpenChange={handleOpenChange}>\n        <div className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}>\n          <DropdownMenuTrigger asChild>\n            <button\n              ref={triggerRef}\n              type=\"button\"\n              aria-label={`Calendar: ${name}`}\n              // Base UI moves focus into the menu after it opens: an Escape\n              // before that reaches the trigger\n              onKeyDown={open ? stopEscapePropagation : undefined}\n              className={cn(\n                ROW_BOX_CLASS,\n                \"group/trigger w-full text-left outline-none\",\n                EVENT_DETAIL_HOVER_BORDER_CLASS,\n                open && PANEL_TRIGGER_OPEN_CLASS,\n              )}\n            >\n              {swatchAndName}\n              <ChevronDown\n                className={cn(\n                  \"size-3.5 shrink-0 opacity-0 group-hover/trigger:opacity-100 group-focus-visible/trigger:opacity-100\",\n                  EVENT_DETAIL_MUTED_CLASS,\n                  open && \"opacity-100\",\n                )}\n              />\n            </button>\n          </DropdownMenuTrigger>\n        </div>\n        <DropdownMenuContent\n          side=\"left\"\n          align=\"start\"\n          sideOffset={sideOffset}\n          aria-label=\"Calendar\"\n          className={cn(EVENT_DETAIL_MENU_CLASS, PANEL_MENU_SURFACE_CLASS)}\n          onKeyDown={stopEscapePropagation}\n        >\n          {groups.map((group) => (\n            <div key={group.email ?? \"\"} role=\"group\" aria-label={group.email}>\n              {group.email && (\n                <div className={PANEL_MENU_LABEL_CLASS}>{group.email}</div>\n              )}\n              {group.calendars.map((item) => {\n                const selected = item.id === event.calendarId;\n                return (\n                  <DropdownMenuItem\n                    key={item.id}\n                    role=\"menuitemradio\"\n                    aria-checked={selected}\n                    className={cn(\n                      PANEL_MENU_ITEM_CLASS,\n                      selected && !pointed && PANEL_MENU_ITEM_CURRENT_CLASS,\n                    )}\n                    onClick={() => handleCalendarPick(item)}\n                    onMouseEnter={() => {\n                      setPointed(true);\n                      setPreviewCalendar(item);\n                    }}\n                    onMouseLeave={() => setPreviewCalendar(null)}\n                    onFocus={() => {\n                      setPointed(true);\n                      setPreviewCalendar(item);\n                    }}\n                    onBlur={() => setPreviewCalendar(null)}\n                  >\n                    <span className=\"flex w-3.5 shrink-0 items-center justify-center\">\n                      {selected && <Check className=\"size-3.5 !text-current\" />}\n                    </span>\n                    <span\n                      className={cn(\n                        \"ml-[9px]\",\n                        SWATCH_CLASS,\n                        EVENT_COLOR_SWATCH_CLASS[item.color],\n                      )}\n                    />\n                    <span className=\"ml-[11px] truncate\">{item.name}</span>\n                  </DropdownMenuItem>\n                );\n              })}\n            </div>\n          ))}\n          {groups.length > 0 && (\n            <DropdownMenuSeparator className=\"mx-1 my-1.5 bg-[#303030]\" />\n          )}\n          <div className={PANEL_MENU_LABEL_CLASS}>Event color</div>\n          <div\n            role=\"group\"\n            aria-label=\"Event color\"\n            className=\"flex items-center gap-2 pt-1.5 pr-2.5 pb-2.5 pl-[31px]\"\n          >\n            {EVENT_COLORS.map((color) => (\n              <ColorSwatchItem\n                key={color}\n                color={color}\n                checked={color === eventColor}\n                onPick={handleColorPick}\n                onPreview={(color) => {\n                  if (color) setPointed(true);\n                  setPreviewColor(color);\n                }}\n              />\n            ))}\n          </div>\n        </DropdownMenuContent>\n      </DropdownMenu>\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-availability.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  Check,\n  ChevronDown,\n  CircleHelp,\n  SquareArrowOutUpRight,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport {\n  EVENT_DETAIL_HOVER_BORDER_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_MUTED_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  PANEL_MENU_ITEM_CLASS,\n  PANEL_MENU_ITEM_CURRENT_CLASS,\n  PANEL_MENU_SURFACE_CLASS,\n  PANEL_TRIGGER_OPEN_CLASS,\n  EventDetailSection,\n  EventDetailTooltip,\n  getPanelMenuSideOffset,\n  stopEscapePropagation,\n} from \"./event-detail-parts\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n} from \"./week-view-types\";\n\n/** One choice of a `PanelSelect` menu */\ninterface PanelSelectOption<TValue extends string> {\n  value: TValue;\n  label: string;\n  /** Explanation shown by the \"?\" icon of the highlighted item */\n  help: string;\n  /** Whether the explanation ends with an external-link icon (help article) */\n  helpLink?: boolean;\n  /** Draws a separator after this option */\n  separatorAfter?: boolean;\n}\n\n/** Busy or free: `DetailedCalendarEvent[\"status\"]` once set */\ntype EventStatus = NonNullable<DetailedCalendarEvent[\"status\"]>;\n\n/** Who can see the event: `DetailedCalendarEvent[\"visibility\"]` once set */\ntype EventVisibility = NonNullable<DetailedCalendarEvent[\"visibility\"]>;\n\n/** Choices of the busy/free menu */\nconst AVAILABILITY_OPTIONS: PanelSelectOption<EventStatus>[] = [\n  {\n    value: \"busy\",\n    label: \"Busy\",\n    help: \"Show me as busy to other people during this event\",\n  },\n  {\n    value: \"free\",\n    label: \"Free\",\n    help: \"Show me as free to other people during this event\",\n  },\n];\n\n/** Choices of the visibility menu */\nconst VISIBILITY_OPTIONS: PanelSelectOption<EventVisibility>[] = [\n  {\n    value: \"default\",\n    label: \"Default visibility\",\n    help: \"The visibility of this event follows the sharing settings of this calendar. Anyone who can see this calendar can see the details of this event.\",\n    helpLink: true,\n    separatorAfter: true,\n  },\n  {\n    value: \"public\",\n    label: \"Public\",\n    help: \"Anyone can see the details of this event.\",\n    helpLink: true,\n  },\n  {\n    value: \"private\",\n    label: \"Private\",\n    help: \"Nobody can see the details of this event unless they have permission to make changes to this calendar.\",\n    helpLink: true,\n  },\n];\n\n/**\n * Props for HelpTextWithLink\n */\ninterface HelpTextWithLinkProps {\n  text: string;\n}\n\n/**\n * Help text ending with the external-link icon, kept on the line of the\n * last word as Notion wraps it\n */\nfunction HelpTextWithLink({ text }: HelpTextWithLinkProps) {\n  const lastSpace = text.lastIndexOf(\" \");\n  return (\n    <>\n      {text.slice(0, lastSpace + 1)}\n      <span className=\"whitespace-nowrap\">\n        {text.slice(lastSpace + 1)}\n        <SquareArrowOutUpRight\n          aria-hidden\n          className=\"ml-1 inline size-3 -translate-y-px align-middle text-[#8A8A8A]\"\n        />\n      </span>\n    </>\n  );\n}\n\n/**\n * Props for HelpIcon\n */\ninterface HelpIconProps {\n  option: PanelSelectOption<string>;\n  /** Shows the icon without the item being highlighted */\n  visible: boolean;\n}\n\n/**\n * The \"?\" at the end of a highlighted menu item, explaining it in a tooltip\n */\nfunction HelpIcon({ option, visible }: HelpIconProps) {\n  const [rect, setRect] = React.useState<DOMRect | null>(null);\n\n  return (\n    <span\n      data-testid=\"menu-help\"\n      className={cn(\n        \"ml-auto flex size-3.5 shrink-0 items-center justify-center opacity-0 group-focus/item:opacity-100 group-data-[highlighted]/item:opacity-100\",\n        visible && \"opacity-100\",\n      )}\n      onMouseEnter={(e) => setRect(e.currentTarget.getBoundingClientRect())}\n      onMouseLeave={() => setRect(null)}\n    >\n      <CircleHelp\n        aria-hidden\n        className=\"size-3.5 !text-[#9B9B9B] group-hover/item:!text-[#D5D5D5]\"\n      />\n      <EventDetailTooltip rect={rect}>\n        {option.helpLink ? (\n          <HelpTextWithLink text={option.help} />\n        ) : (\n          option.help\n        )}\n      </EventDetailTooltip>\n    </span>\n  );\n}\n\n/**\n * Props for PanelSelect\n */\ninterface PanelSelectProps<TValue extends string> {\n  /** Accessible name of the trigger, e.g. \"Availability\" */\n  name: string;\n  value: TValue;\n  options: PanelSelectOption<TValue>[];\n  /** The section the menu lines up beside */\n  sectionRef: React.RefObject<HTMLElement | null>;\n  className?: string;\n  /** Called with the picked choice; without it the value is read-only text */\n  onValueChange?: (value: TValue) => void;\n}\n\n/**\n * A value of the panel picked from a menu that opens beside the panel: the\n * value with a chevron on hover, the menu with a check on the current value\n * and a \"?\" explaining each choice. Hovering or highlighting a choice\n * previews it in the trigger; Escape closes the menu and keeps the value.\n */\nfunction PanelSelect<TValue extends string>({\n  name,\n  value,\n  options,\n  sectionRef,\n  className,\n  onValueChange,\n}: PanelSelectProps<TValue>) {\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const [open, setOpen] = React.useState(false);\n  const [sideOffset, setSideOffset] = React.useState(0);\n  /** Choice hovered or highlighted in the open menu */\n  const [preview, setPreview] = React.useState<TValue | null>(null);\n  /** Whether a choice of the open menu has been hovered or highlighted yet */\n  const [pointed, setPointed] = React.useState(false);\n\n  const handleOpenChange = React.useCallback(\n    (next: boolean) => {\n      setOpen(next);\n      setPreview(null);\n      if (!next) return;\n      setSideOffset(getPanelMenuSideOffset(triggerRef, sectionRef));\n      setPointed(false);\n    },\n    [sectionRef],\n  );\n\n  const showPreview = React.useCallback((next: TValue) => {\n    setPointed(true);\n    setPreview(next);\n  }, []);\n\n  const hidePreview = React.useCallback(() => setPreview(null), []);\n\n  const shown = options.find((o) => o.value === (preview ?? value));\n  const current = options.find((o) => o.value === value);\n\n  if (!onValueChange) {\n    return (\n      <div\n        className={cn(\n          \"flex h-8 min-w-0 items-center border border-transparent px-2\",\n          className,\n        )}\n      >\n        <span className=\"sr-only\">{name}: </span>\n        <span className=\"truncate\">{current?.label ?? value}</span>\n      </div>\n    );\n  }\n\n  return (\n    <DropdownMenu open={open} onOpenChange={handleOpenChange}>\n      <DropdownMenuTrigger asChild>\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          aria-label={`${name}: ${current?.label ?? value}`}\n          // Base UI moves focus into the menu after it opens: an Escape before\n          // that reaches the trigger\n          onKeyDown={open ? stopEscapePropagation : undefined}\n          className={cn(\n            \"group/trigger flex h-8 min-w-0 items-center justify-between gap-2 px-2 text-left outline-none\",\n            EVENT_DETAIL_HOVER_BORDER_CLASS,\n            open && PANEL_TRIGGER_OPEN_CLASS,\n            className,\n          )}\n        >\n          <span className=\"truncate\">{shown?.label ?? value}</span>\n          <ChevronDown\n            className={cn(\n              \"mr-0.5 size-3.5 shrink-0 opacity-0 group-hover/trigger:opacity-100 group-focus-visible/trigger:opacity-100\",\n              EVENT_DETAIL_MUTED_CLASS,\n              open && \"opacity-100\",\n            )}\n          />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        side=\"left\"\n        align=\"start\"\n        sideOffset={sideOffset}\n        aria-label={name}\n        onKeyDown={stopEscapePropagation}\n        className={cn(\n          \"w-[216px]\",\n          EVENT_DETAIL_MENU_CLASS,\n          PANEL_MENU_SURFACE_CLASS,\n        )}\n      >\n        {options.map((option) => {\n          const selected = option.value === value;\n          return (\n            <React.Fragment key={option.value}>\n              <DropdownMenuItem\n                role=\"menuitemradio\"\n                aria-checked={selected}\n                className={cn(\n                  PANEL_MENU_ITEM_CLASS,\n                  selected && !pointed && PANEL_MENU_ITEM_CURRENT_CLASS,\n                )}\n                onClick={() => {\n                  if (option.value !== value) onValueChange(option.value);\n                }}\n                onMouseEnter={() => showPreview(option.value)}\n                onMouseLeave={hidePreview}\n                onFocus={() => showPreview(option.value)}\n                onBlur={hidePreview}\n              >\n                <span className=\"flex w-3.5 shrink-0 items-center justify-center\">\n                  {selected && <Check className=\"size-3.5 !text-current\" />}\n                </span>\n                <span className=\"ml-2 truncate\">{option.label}</span>\n                <HelpIcon option={option} visible={selected && !pointed} />\n              </DropdownMenuItem>\n              {option.separatorAfter && (\n                <DropdownMenuSeparator className=\"mx-1 my-[5px] bg-[#303030]\" />\n              )}\n            </React.Fragment>\n          );\n        })}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * Busy or free, and who can see the event, side by side under the calendar.\n * Each opens a menu beside the panel.\n */\nexport function EventDetailAvailability<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const sectionRef = React.useRef<HTMLDivElement>(null);\n\n  const handleStatusChange = React.useCallback(\n    (status: EventStatus) => {\n      onEventChange?.({ ...event, status });\n    },\n    [event, onEventChange],\n  );\n\n  const handleVisibilityChange = React.useCallback(\n    (visibility: EventVisibility) => {\n      onEventChange?.({ ...event, visibility });\n    },\n    [event, onEventChange],\n  );\n\n  return (\n    <EventDetailSection ref={sectionRef} name=\"availability\">\n      <div\n        className={cn(\n          \"flex items-center gap-[5px] pr-2 pl-9\",\n          EVENT_DETAIL_ROW_HEIGHT_CLASS,\n        )}\n      >\n        <PanelSelect\n          name=\"Availability\"\n          value={event.status ?? \"busy\"}\n          options={AVAILABILITY_OPTIONS}\n          sectionRef={sectionRef}\n          className=\"w-[102px] shrink-0\"\n          onValueChange={onEventChange && handleStatusChange}\n        />\n        <PanelSelect\n          name=\"Visibility\"\n          value={event.visibility ?? \"default\"}\n          options={VISIBILITY_OPTIONS}\n          sectionRef={sectionRef}\n          className=\"flex-1\"\n          onValueChange={onEventChange && handleVisibilityChange}\n        />\n      </div>\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-reminders.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport {\n  autoUpdate,\n  flip,\n  offset,\n  shift,\n  useFloating,\n} from \"@floating-ui/react-dom\";\nimport { Bell, X } from \"lucide-react\";\nimport type { Locale } from \"date-fns\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useCalendarConfig } from \"./calendar-provider\";\nimport {\n  EVENT_DETAIL_GROUPED_INPUT_CLASS,\n  EVENT_DETAIL_ICON_CLASS,\n  EVENT_DETAIL_INPUT_GROUP_CLASS,\n  EVENT_DETAIL_MENU_CLASS,\n  EVENT_DETAIL_PLACEHOLDER_CLASS,\n  EVENT_DETAIL_ROW_HEIGHT_CLASS,\n  EVENT_DETAIL_SECONDARY_CLASS,\n  PANEL_MENU_SURFACE_CLASS,\n  ROW_BOX_CLASS,\n  EventDetailSection,\n  getEventDetailPortalContainer,\n} from \"./event-detail-parts\";\nimport { addReminder, formatTime, getReminderMinutes } from \"@/lib/event-utils\";\nimport type {\n  DetailedCalendarEvent,\n  EventDetailSectionProps,\n  EventReminder,\n  HourCycle,\n} from \"./week-view-types\";\n\n/** Gap in px between the suggestions and the panel's left edge */\nconst SUGGESTIONS_GAP = 4;\n\n/** Units a typed number is offered in, in Notion's order */\nconst REMINDER_UNITS: EventReminder[\"unit\"][] = [\n  \"minutes\",\n  \"hours\",\n  \"days\",\n  \"weeks\",\n];\n\n/** Unit after a reminder's amount: [one, many], as in \"1hour\" and \"2hours\" */\nconst REMINDER_UNIT_LABELS: Record<EventReminder[\"unit\"], [string, string]> = {\n  minutes: [\"min\", \"min\"],\n  hours: [\"hour\", \"hours\"],\n  days: [\"day\", \"days\"],\n  weeks: [\"week\", \"weeks\"],\n};\n\n/**\n * Words a typed unit can be the start of, for each unit: \"10m\", \"10 min\",\n * \"10 minutes\", \"10 mins\", \"2h\", \"2 hrs\", \"3d\", \"1w\", \"1 wk\"\n */\nconst REMINDER_UNIT_NAMES: Record<EventReminder[\"unit\"], string[]> = {\n  minutes: [\"minutes\", \"mins\"],\n  hours: [\"hours\", \"hrs\"],\n  days: [\"days\"],\n  weeks: [\"weeks\", \"wks\"],\n};\n\n/**\n * Furthest a suggested reminder fires before the event: 4 weeks, Google\n * Calendar's limit, which Notion follows (\"2\" offers 2weeks, \"5\" no weeks)\n */\nconst MAX_REMINDER_MINUTES = 4 * 7 * 24 * 60;\n\n/** A reminder at the start of the event */\nconst AT_START_REMINDER: EventReminder = { amount: 0, unit: \"minutes\" };\n\n/** Label of a reminder at the start of the event */\nconst AT_START_LABEL = \"At start of event\";\n\n/** Reminders offered before anything is typed, for a timed event */\nconst TIMED_PRESETS: EventReminder[] = [\n  AT_START_REMINDER,\n  { amount: 5, unit: \"minutes\" },\n  { amount: 10, unit: \"minutes\" },\n  { amount: 30, unit: \"minutes\" },\n  { amount: 1, unit: \"hours\" },\n];\n\n/** Reminders offered before anything is typed, for an all-day event */\nconst ALL_DAY_PRESETS: EventReminder[] = [\n  AT_START_REMINDER,\n  { amount: 1, unit: \"days\" },\n  { amount: 2, unit: \"days\" },\n  { amount: 3, unit: \"days\" },\n  { amount: 1, unit: \"weeks\" },\n];\n\n/**\n * \"10min\", \"1hour\", \"2days\" (with a hair space, as Notion sets it), or null\n * for a reminder at the start of the event\n */\nfunction formatReminderAmount(reminder: EventReminder): string | null {\n  if (reminder.amount === 0) return null;\n  const [one, many] = REMINDER_UNIT_LABELS[reminder.unit];\n  return `${reminder.amount}\\u200A${reminder.amount === 1 ? one : many}`;\n}\n\n/** \" at 9 AM\" for an all-day reminder's time of day, \"\" without one */\nfunction formatReminderTimeOfDay(\n  reminder: EventReminder,\n  hourCycle: HourCycle,\n  locale: Locale,\n): string {\n  if (!reminder.time) return \"\";\n  const { hours, minutes } = reminder.time;\n  return ` at ${formatTime(new Date(2000, 0, 1, hours, minutes), hourCycle, locale)}`;\n}\n\n/**\n * A reminder as text: \"10min before\", \"1day before at 9 AM\", \"At start of\n * event\", or \"On the day at 9 AM\" for an all-day reminder on the day itself\n */\nfunction formatReminderLabel(\n  reminder: EventReminder,\n  hourCycle: HourCycle,\n  locale: Locale,\n): string {\n  const amount = formatReminderAmount(reminder);\n  const timeOfDay = formatReminderTimeOfDay(reminder, hourCycle, locale);\n  if (amount) return `${amount} before${timeOfDay}`;\n  if (timeOfDay) return `On the day${timeOfDay}`;\n  return AT_START_LABEL;\n}\n\n/**\n * Suggestions for what was typed: a number is offered in every unit its\n * text can start (\"2h\" in hours, \"10 mins\" in minutes) up to 4 weeks before\n * (`MAX_REMINDER_MINUTES`: \"5\" offers no weeks), 0 once as \"At start of\n * event\", other text filters the presets. Empty text offers the presets.\n */\nfunction getSuggestions(\n  query: string,\n  presets: EventReminder[],\n): EventReminder[] {\n  const trimmed = query.trim().toLowerCase();\n  if (trimmed.length === 0) return presets;\n\n  const match = /^(\\d+)\\s*([a-z]*)$/.exec(trimmed);\n  if (match) {\n    const amount = Number.parseInt(match[1], 10);\n    const unitText = match[2];\n    const units = REMINDER_UNITS.filter((unit) =>\n      REMINDER_UNIT_NAMES[unit].some((name) => name.startsWith(unitText)),\n    );\n    if (units.length === 0) return [];\n    if (amount === 0) return [AT_START_REMINDER];\n    return units\n      .map((unit) => ({ amount, unit }))\n      .filter(\n        (reminder) => getReminderMinutes(reminder) <= MAX_REMINDER_MINUTES,\n      );\n  }\n\n  return presets.filter((preset) =>\n    (formatReminderAmount(preset) ?? AT_START_LABEL)\n      .toLowerCase()\n      .includes(trimmed),\n  );\n}\n\n/**\n * Props for ReminderLabel\n */\ninterface ReminderLabelProps {\n  reminder: EventReminder;\n  /** Color of the muted \"before\" */\n  beforeClassName: string;\n}\n\n/**\n * One reminder as Notion writes it: \"10min before\", with \"before\" muted,\n * \"1day before at 9 AM\", \"At start of event\"\n */\nfunction ReminderLabel({ reminder, beforeClassName }: ReminderLabelProps) {\n  const { hourCycle, locale } = useCalendarConfig();\n  const amount = formatReminderAmount(reminder);\n  if (!amount) return <>{formatReminderLabel(reminder, hourCycle, locale)}</>;\n\n  return (\n    <>\n      {amount} <span className={beforeClassName}>before</span>\n      {formatReminderTimeOfDay(reminder, hourCycle, locale)}\n    </>\n  );\n}\n\n/**\n * Props for ReminderSuggestions\n */\ninterface ReminderSuggestionsProps {\n  /** Element the list lines up with: the section, so it opens beside the panel */\n  reference: HTMLElement | null;\n  /** Element the list renders into (`getEventDetailPortalContainer()`) */\n  container: HTMLElement;\n  suggestions: EventReminder[];\n  /** Index of the highlighted suggestion, -1 for none */\n  highlightedIndex: number;\n  /** Id of the list, for the input's `aria-controls` */\n  id: string;\n  onHighlight: (index: number) => void;\n  onPick: (reminder: EventReminder) => void;\n}\n\n/**\n * The suggestions of the reminder input, in a floating list beside the\n * panel. It never takes focus: the input keeps it, as in a combobox.\n */\nfunction ReminderSuggestions({\n  reference,\n  container,\n  suggestions,\n  highlightedIndex,\n  id,\n  onHighlight,\n  onPick,\n}: ReminderSuggestionsProps) {\n  const { refs, floatingStyles } = useFloating({\n    open: true,\n    placement: \"left-start\",\n    strategy: \"fixed\",\n    whileElementsMounted: autoUpdate,\n    middleware: [offset(SUGGESTIONS_GAP), flip(), shift({ padding: 8 })],\n  });\n\n  React.useLayoutEffect(() => {\n    refs.setReference(reference);\n  }, [refs, reference]);\n\n  const setFloating = React.useCallback(\n    (node: HTMLDivElement | null) => refs.setFloating(node),\n    [refs],\n  );\n\n  return ReactDOM.createPortal(\n    <div\n      ref={setFloating}\n      id={id}\n      role=\"listbox\"\n      aria-label=\"Reminders\"\n      data-calendar-popover=\"\"\n      style={floatingStyles}\n      className={cn(\n        \"z-50 w-[216px] border\",\n        EVENT_DETAIL_MENU_CLASS,\n        PANEL_MENU_SURFACE_CLASS,\n      )}\n      // Keep focus in the input when a suggestion is pressed\n      onMouseDown={(e) => e.preventDefault()}\n    >\n      {suggestions.map((reminder, index) => (\n        <div\n          key={index}\n          id={`${id}-${index}`}\n          role=\"option\"\n          aria-selected={index === highlightedIndex}\n          className={cn(\n            \"flex h-8 cursor-default items-center rounded-md px-2 text-xs text-[#CCCCCC] select-none\",\n            index === highlightedIndex && \"bg-[#303030] text-[#F0F0F0]\",\n          )}\n          onMouseEnter={() => onHighlight(index)}\n          onClick={() => onPick(reminder)}\n        >\n          <span>\n            <ReminderLabel\n              reminder={reminder}\n              beforeClassName=\"text-[#717070]\"\n            />\n          </span>\n        </div>\n      ))}\n    </div>,\n    container,\n  );\n}\n\n/**\n * A \"Reminders\" input, then one row per reminder, from the one closest to\n * the start. Focusing the input lists presets beside the panel, typing a\n * number offers it in minutes, hours, days and weeks; picking one adds it\n * unless a reminder firing at the same moment is set (\"60min\" and \"1hour\").\n * As in Notion, adding one closes the list and keeps the input focused and\n * empty: typing, or focusing the input again, opens it. Escape closes the\n * list and clears the input. Hovering a reminder shows an × that removes it.\n */\nexport function EventDetailReminders<\n  TEvent extends DetailedCalendarEvent = DetailedCalendarEvent,\n>({ event, onEventChange }: EventDetailSectionProps<TEvent>) {\n  const { hourCycle, locale } = useCalendarConfig();\n  /** Without `onEventChange` the reminders are listed, never edited */\n  const readOnly = !onEventChange;\n  const listId = React.useId();\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const [section, setSection] = React.useState<HTMLDivElement | null>(null);\n  const [focused, setFocused] = React.useState(false);\n  const [query, setQuery] = React.useState(\"\");\n  /**\n   * Whether the list stays closed while the input is empty: after typing\n   * and clearing the text, or after adding a reminder. Typing opens it\n   * again, and so does a new focus.\n   */\n  const [closedWhenEmpty, setClosedWhenEmpty] = React.useState(false);\n  const [highlightedIndex, setHighlightedIndex] = React.useState(-1);\n  /**\n   * Whether the highlighted suggestion is previewed in the input: after\n   * moving to it with the arrows or the pointer, not after typing\n   */\n  const [previewing, setPreviewing] = React.useState(false);\n  const reminders = React.useMemo(\n    () => event.reminders ?? [],\n    [event.reminders],\n  );\n\n  const presets = event.isAllDay ? ALL_DAY_PRESETS : TIMED_PRESETS;\n  const suggestions = React.useMemo(\n    () => getSuggestions(query, presets),\n    [query, presets],\n  );\n  const highlighted =\n    highlightedIndex >= 0 ? suggestions[highlightedIndex] : undefined;\n  const open =\n    focused && suggestions.length > 0 && (query.length > 0 || !closedWhenEmpty);\n\n  const preview = previewing ? highlighted : undefined;\n  /** Text the input shows: the previewed suggestion, or what was typed */\n  const shownText = preview\n    ? (formatReminderAmount(preview) ?? AT_START_LABEL)\n    : query;\n\n  // Keep the previewed text selected, as Notion does, so typing replaces it\n  React.useEffect(() => {\n    if (!preview) return;\n    inputRef.current?.select();\n  }, [preview]);\n\n  const highlightAndPreview = React.useCallback((index: number) => {\n    setHighlightedIndex(index);\n    setPreviewing(true);\n  }, []);\n\n  const handlePick = React.useCallback(\n    (reminder: EventReminder) => {\n      setQuery(\"\");\n      setClosedWhenEmpty(true);\n      setHighlightedIndex(-1);\n      setPreviewing(false);\n      const next = addReminder(reminders, reminder);\n      if (next === reminders) return;\n      onEventChange?.({ ...event, reminders: next });\n    },\n    [event, reminders, onEventChange],\n  );\n\n  const removeReminder = React.useCallback(\n    (index: number) => {\n      onEventChange?.({\n        ...event,\n        reminders: reminders.filter((_, i) => i !== index),\n      });\n    },\n    [event, reminders, onEventChange],\n  );\n\n  const handleChange = React.useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      const next = e.target.value;\n      setQuery(next);\n      setClosedWhenEmpty(true);\n      // A typed value highlights its first suggestion, ready for Enter\n      setHighlightedIndex(next.trim().length > 0 ? 0 : -1);\n      setPreviewing(false);\n    },\n    [],\n  );\n\n  const handleFocus = React.useCallback(() => {\n    setFocused(true);\n  }, []);\n\n  const handleBlur = React.useCallback(() => {\n    setFocused(false);\n    setQuery(\"\");\n    setClosedWhenEmpty(false);\n    setHighlightedIndex(-1);\n    setPreviewing(false);\n  }, []);\n\n  const handleKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLInputElement>) => {\n      if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n        // A closed list stays closed, as in Notion\n        if (!open) return;\n        e.preventDefault();\n        const step = e.key === \"ArrowDown\" ? 1 : -1;\n        setHighlightedIndex((index) => {\n          if (index === -1) return step === 1 ? 0 : suggestions.length - 1;\n          return (index + step + suggestions.length) % suggestions.length;\n        });\n        setPreviewing(true);\n        return;\n      }\n      if (e.key === \"Enter\") {\n        e.preventDefault();\n        if (open && highlighted) handlePick(highlighted);\n        return;\n      }\n      if (e.key === \"Escape\") {\n        // Stop here so the global handler doesn't deselect the event; leaving\n        // the input closes the list and clears it\n        e.preventDefault();\n        e.stopPropagation();\n        inputRef.current?.blur();\n      }\n    },\n    [open, suggestions.length, highlighted, handlePick],\n  );\n\n  const bell = (\n    <span className=\"flex w-4 shrink-0 items-center justify-center\">\n      <Bell className={EVENT_DETAIL_ICON_CLASS} />\n    </span>\n  );\n\n  return (\n    <EventDetailSection ref={setSection} name=\"reminders\" className=\"px-2\">\n      <div className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}>\n        {readOnly ? (\n          // Read-only details: the heading without the input\n          <div className={cn(ROW_BOX_CLASS, \"border border-transparent\")}>\n            {bell}\n            <span className={EVENT_DETAIL_PLACEHOLDER_CLASS}>Reminders</span>\n          </div>\n        ) : (\n          <div\n            className={cn(\n              ROW_BOX_CLASS,\n              \"w-full\",\n              EVENT_DETAIL_INPUT_GROUP_CLASS,\n            )}\n            onClick={() => inputRef.current?.focus()}\n          >\n            {bell}\n            <input\n              ref={inputRef}\n              type=\"text\"\n              role=\"combobox\"\n              aria-label=\"Add reminder\"\n              aria-expanded={open}\n              aria-controls={open ? listId : undefined}\n              aria-autocomplete=\"list\"\n              aria-activedescendant={\n                open && highlightedIndex >= 0\n                  ? `${listId}-${highlightedIndex}`\n                  : undefined\n              }\n              placeholder=\"Reminders\"\n              value={shownText}\n              onChange={handleChange}\n              onFocus={handleFocus}\n              onBlur={handleBlur}\n              onKeyDown={handleKeyDown}\n              className={cn(\n                // The placeholder token (EVENT_DETAIL_PLACEHOLDER_CLASS), as the title sets it\n                \"min-w-0 flex-1 placeholder:text-[#ABABA9] dark:placeholder:text-[#595959]\",\n                EVENT_DETAIL_GROUPED_INPUT_CLASS,\n              )}\n            />\n          </div>\n        )}\n      </div>\n      {open && (\n        <ReminderSuggestions\n          reference={section}\n          container={getEventDetailPortalContainer(section)}\n          suggestions={suggestions}\n          highlightedIndex={highlightedIndex}\n          id={listId}\n          onHighlight={highlightAndPreview}\n          onPick={handlePick}\n        />\n      )}\n      {reminders.map((reminder, index) => (\n        <div\n          // Two reminders can share amount and unit (an all-day one's time\n          // differs, or the host passed duplicates)\n          key={index}\n          data-testid=\"event-reminder\"\n          className={cn(\"flex items-center\", EVENT_DETAIL_ROW_HEIGHT_CLASS)}\n        >\n          <div\n            className={cn(\n              ROW_BOX_CLASS,\n              \"group/reminder w-full rounded-sm border border-transparent\",\n              !readOnly && \"hover:bg-[#F5F5F5] dark:hover:bg-[#242424]\",\n            )}\n          >\n            <span className=\"w-4 shrink-0\" />\n            <span className=\"min-w-0 flex-1 truncate\">\n              <ReminderLabel\n                reminder={reminder}\n                beforeClassName={EVENT_DETAIL_SECONDARY_CLASS}\n              />\n            </span>\n            {!readOnly && (\n              <button\n                type=\"button\"\n                aria-label={`Remove reminder: ${formatReminderLabel(reminder, hourCycle, locale).replace(\"\\u200A\", \" \")}`}\n                className=\"flex size-5 shrink-0 items-center justify-center rounded-sm text-[#919091] opacity-0 group-hover/reminder:opacity-100 focus-visible:opacity-100 dark:text-[#818181]\"\n                onClick={() => removeReminder(index)}\n              >\n                <X className=\"size-3.5\" />\n              </button>\n            )}\n          </div>\n        </div>\n      ))}\n    </EventDetailSection>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-detail-popover.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  autoUpdate,\n  flip,\n  limitShift,\n  offset,\n  shift,\n  useFloating,\n} from \"@floating-ui/react-dom\";\nimport type { Placement } from \"@floating-ui/react-dom\";\nimport { PanelRightIcon, X } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { focusEventElement } from \"@/hooks/use-event-keyboard\";\nimport { usePopoverDismiss } from \"@/hooks/use-popover-dismiss\";\nimport { Button } from \"@/components/ui/button\";\nimport { EventDetailPanel } from \"./event-detail-panel\";\nimport {\n  isInsideCalendarPopover,\n  useCalendarPopoverBoundary,\n} from \"./calendar-popover-context\";\nimport {\n  useCalendarEventActions,\n  useCalendarRenderSlots,\n  useCalendarSeries,\n} from \"./calendar-provider\";\nimport { useEventTitleFocus } from \"./event-title-focus-context\";\nimport type { CalendarEvent, EventPopoverAnchor } from \"./week-view-types\";\n\n/** Gap between the anchor and the popover, in px */\nconst POPOVER_SIDE_OFFSET = 8;\n\n/** Collision padding on the bottom, left and right edges, in px */\nconst POPOVER_COLLISION_PADDING = { bottom: 8, left: 16, right: 16 };\n\n/** Elements of the panel that Tab can reach, in order */\nfunction getTabbables(container: HTMLElement): HTMLElement[] {\n  return Array.from(container.querySelectorAll<HTMLElement>(\"*\")).filter(\n    (el) =>\n      el.tabIndex >= 0 &&\n      !el.hidden &&\n      !(el as HTMLButtonElement).disabled &&\n      !(el instanceof HTMLInputElement && el.type === \"hidden\") &&\n      el.getClientRects().length > 0 &&\n      getComputedStyle(el).visibility !== \"hidden\",\n  );\n}\n\n/**\n * Tab and Shift+Tab cycle inside the details, as Radix's non-modal popover\n * content does with a looping (not trapping) focus scope: Tab on the last\n * control moves to the first, Shift+Tab on the first moves to the last. From\n * the panel itself (focused by a press on a blank part of it), Tab enters at\n * the first control and Shift+Tab at the last.\n */\nfunction loopFocus(e: React.KeyboardEvent<HTMLElement>) {\n  if (e.key !== \"Tab\" || e.altKey || e.ctrlKey || e.metaKey) return;\n  if (e.defaultPrevented) return;\n  const panel = e.currentTarget;\n  const tabbables = getTabbables(panel);\n  const first = tabbables[0];\n  const last = tabbables[tabbables.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    if (active === panel) e.preventDefault();\n    return;\n  }\n  const edge = e.shiftKey ? first : last;\n  if (active !== edge && active !== panel) return;\n  const next = e.shiftKey ? last : first;\n  e.preventDefault();\n  next.focus({ preventScroll: true });\n  if (next instanceof HTMLInputElement) next.select();\n}\n\n/**\n * The transform origin for each placement: the panel grows out of the side\n * and corner that face its anchor.\n */\nconst TRANSFORM_ORIGIN_BY_PLACEMENT: Record<Placement, string> = {\n  top: \"center bottom\",\n  \"top-start\": \"left bottom\",\n  \"top-end\": \"right bottom\",\n  bottom: \"center top\",\n  \"bottom-start\": \"left top\",\n  \"bottom-end\": \"right top\",\n  left: \"right center\",\n  \"left-start\": \"right top\",\n  \"left-end\": \"right bottom\",\n  right: \"left center\",\n  \"right-start\": \"left top\",\n  \"right-end\": \"left bottom\",\n};\n\ninterface EventDetailPopoverProps {\n  event: CalendarEvent;\n  /** The panel's id, for the trigger's `aria-controls` */\n  id?: string;\n  /** What the popover is placed beside */\n  anchor: EventPopoverAnchor;\n  /**\n   * The element that toggles the popover (the event itself). Presses and\n   * focus on it don't close the popover, since its own click does.\n   */\n  triggerRef?: React.RefObject<Element | null>;\n  onEventChange?: (event: CalendarEvent) => void;\n  onClose: () => void;\n  /** Callback for the expand button (e.g. dock to a side panel). Hidden when absent. */\n  onExpand?: () => void;\n  /** Which side to prefer for the popover. Defaults to \"right\". */\n  side?: \"right\" | \"bottom\" | \"left\" | \"top\";\n  /** Alignment along the side axis. Defaults to \"center\". */\n  align?: \"start\" | \"center\" | \"end\";\n  /**\n   * Override the top collision padding. When omitted the header height is\n   * used so the popover never overlaps the weekday header. All-day events\n   * live *inside* the header, so they pass a small value to avoid being\n   * pushed off-screen.\n   */\n  collisionPaddingTop?: number;\n}\n\n/**\n * The event details in a popover beside `anchor`. It renders its own\n * floating layer instead of the shadcn/ui Popover, so it works the same\n * with the Radix and the Base UI styles.\n */\nexport function EventDetailPopover({\n  event,\n  id,\n  anchor,\n  triggerRef,\n  onEventChange,\n  onClose,\n  onExpand,\n  side = \"right\",\n  align = \"center\",\n  collisionPaddingTop,\n}: EventDetailPopoverProps) {\n  const { boundary, headerHeight, view } = useCalendarPopoverBoundary();\n  const { pendingEventId, clearPending } = useEventTitleFocus();\n  const { renderEventDetails } = useCalendarRenderSlots();\n  const series = useCalendarSeries();\n  const eventActions = useCalendarEventActions();\n  const panelRef = React.useRef<HTMLDivElement>(null);\n  /** Just created by click-to-create: its title should be focused */\n  const isNew = pendingEventId === event.id;\n\n  /**\n   * In day view the event trigger spans the full grid width, leaving no room\n   * for a 320px popover on either side within the calendar container.\n   * Skip the collision boundary so the popover stays within the viewport.\n   */\n  const isDayView = view === \"day\";\n  const collisionBoundary = !isDayView && boundary ? [boundary] : [];\n  const detectOverflowOptions = {\n    padding: {\n      top: collisionPaddingTop ?? headerHeight,\n      ...POPOVER_COLLISION_PADDING,\n    },\n    boundary: collisionBoundary,\n    altBoundary: collisionBoundary.length > 0,\n  };\n  const placement: Placement = align === \"center\" ? side : `${side}-${align}`;\n\n  const {\n    refs,\n    floatingStyles,\n    placement: placedAt,\n  } = useFloating({\n    open: true,\n    placement,\n    strategy: \"fixed\",\n    // left/top rather than a transform: the enter animation animates the\n    // transform, and would slide the panel in from the viewport's corner\n    transform: false,\n    whileElementsMounted: autoUpdate,\n    middleware: [\n      offset(POPOVER_SIDE_OFFSET),\n      shift({\n        mainAxis: true,\n        crossAxis: false,\n        limiter: limitShift(),\n        ...detectOverflowOptions,\n      }),\n      flip(detectOverflowOptions),\n    ],\n  });\n\n  // After every render: a ref object keeps its identity when its element\n  // changes, and floating-ui ignores a reference it already has\n  React.useLayoutEffect(() => {\n    refs.setReference(\"current\" in anchor ? anchor.current : anchor);\n  });\n\n  const setPanel = React.useCallback(\n    (node: HTMLDivElement | null) => {\n      panelRef.current = node;\n      refs.setFloating(node);\n    },\n    [refs],\n  );\n\n  /**\n   * Escape closes the popover before the keydown reaches the event. If focus\n   * was on the event or in the details (which unmount and drop it), put it\n   * back on the event once that has happened.\n   */\n  const handleEscapeKeyDown = React.useCallback(() => {\n    const active = document.activeElement;\n    if (!(active instanceof HTMLElement)) return;\n    const hadFocus =\n      active.dataset.eventId === event.id || isInsideCalendarPopover(active);\n    if (!hadFocus) return;\n    requestAnimationFrame(() => {\n      if (document.activeElement && document.activeElement !== document.body) {\n        return;\n      }\n      focusEventElement(boundary, event.id);\n    });\n  }, [boundary, event.id]);\n\n  const dismissHandlers = usePopoverDismiss({\n    panelRef,\n    triggerRef,\n    onEscape: handleEscapeKeyDown,\n    onDismiss: onClose,\n  });\n\n  // Custom details get `isNew` for one render; the default panel clears the\n  // request itself once it has focused the title\n  React.useEffect(() => {\n    if (!renderEventDetails || !isNew) return;\n    clearPending();\n  }, [renderEventDetails, isNew, clearPending]);\n\n  // The provider works out the selected event's series neighbors; the\n  // arrows are disabled at the series' ends\n  const isSeriesEvent = series.eventId === event.id;\n  const previousInSeries = isSeriesEvent ? series.previousInSeries : null;\n  const nextInSeries = isSeriesEvent ? series.nextInSeries : null;\n\n  const popoverHeaderActions = (\n    <>\n      {onExpand && (\n        <Button\n          variant=\"ghost\"\n          size=\"icon\"\n          className=\"size-7 text-[#C7C5C1] dark:text-[#595959]\"\n          onClick={(e) => {\n            e.stopPropagation();\n            onExpand();\n          }}\n          title=\"Dock to sidebar\"\n        >\n          <PanelRightIcon className=\"size-4\" />\n        </Button>\n      )}\n      <Button\n        variant=\"ghost\"\n        size=\"icon\"\n        className=\"size-7 text-[#C7C5C1] dark:text-[#595959]\"\n        onClick={(e) => {\n          e.stopPropagation();\n          onClose();\n        }}\n        title=\"Close\"\n      >\n        <X className=\"size-4\" />\n      </Button>\n    </>\n  );\n\n  // The provider measures its boundary after it mounts. Until then there is\n  // nothing to place the panel against, and no way to tell whether the\n  // calendar sits in a dialog: rendering once that is known keeps the panel\n  // in one container, rather than moving it (and remounting it) a render later\n  if (!boundary) return null;\n\n  /**\n   * Inside a dialog (or a sheet or drawer), the panel goes into that dialog\n   * rather than the body: a modal dialog keeps focus inside its own element\n   * and turns off pointer events on the rest of the page.\n   */\n  const portalContainer =\n    boundary.closest<HTMLElement>('[role=\"dialog\"], [role=\"alertdialog\"]') ??\n    document.body;\n\n  return createPortal(\n    <div\n      ref={setPanel}\n      id={id}\n      role=\"dialog\"\n      aria-label=\"Event details\"\n      data-calendar-popover=\"\"\n      data-side={placedAt.split(\"-\")[0]}\n      tabIndex={-1}\n      // The views' own click handlers never see a press in the details, or in\n      // anything the details render in a portal\n      onClick={(e) => e.stopPropagation()}\n      onKeyDown={loopFocus}\n      {...dismissHandlers}\n      style={{\n        ...floatingStyles,\n        transformOrigin: TRANSFORM_ORIGIN_BY_PLACEMENT[placedAt],\n      }}\n      className={cn(\n        \"z-50 w-[320px] max-h-[80vh] overflow-y-auto rounded-lg border bg-popover/60 text-popover-foreground shadow-lg outline-hidden backdrop-blur-xl\",\n        \"animate-in fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\",\n      )}\n    >\n      {renderEventDetails ? (\n        renderEventDetails({ event, close: onClose, isNew })\n      ) : (\n        <EventDetailPanel\n          event={event}\n          onEventChange={onEventChange}\n          onPrevWeek={\n            previousInSeries\n              ? () => series.showSeriesOccurrence(previousInSeries)\n              : undefined\n          }\n          onNextWeek={\n            nextInSeries\n              ? () => series.showSeriesOccurrence(nextInSeries)\n              : undefined\n          }\n          onCut={\n            eventActions ? () => eventActions.cutEvent(event.id) : undefined\n          }\n          onCopy={\n            eventActions ? () => eventActions.copyEvent(event.id) : undefined\n          }\n          onDuplicate={\n            eventActions\n              ? () => eventActions.duplicateEvent(event.id)\n              : undefined\n          }\n          onDelete={\n            eventActions ? () => eventActions.deleteEvent(event.id) : undefined\n          }\n          headerActions={popoverHeaderActions}\n          autoFocusTitle={isNew}\n          onTitleAutoFocused={clearPending}\n        />\n      )}\n    </div>,\n    portalContainer,\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/components/event-context-menu.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  Check,\n  Copy,\n  Monitor,\n  SquareDashed,\n  TabletSmartphone,\n  Trash2,\n} from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  EVENT_COLORS,\n  groupCalendarsByEmail,\n  moveEventToCalendar,\n  resolveEventColor,\n} from \"@/lib/event-utils\";\nimport {\n  useCalendarConfig,\n  useCalendarEventActions,\n} from \"./calendar-provider\";\nimport { EVENT_ACTION_KEYS } from \"./event-detail-parts\";\nimport type {\n  CalendarInfo,\n  DetailedCalendarEvent,\n  EventColor,\n} from \"./week-view-types\";\n\n/**\n * Swatch of an event or calendar color in a picker (this menu, the details\n * panel's calendar picker): the color events are drawn with\n */\nexport const EVENT_COLOR_SWATCH_CLASS: Record<EventColor, string> = {\n  red: \"bg-event-red-border\",\n  orange: \"bg-event-orange-border\",\n  yellow: \"bg-event-yellow-border\",\n  green: \"bg-event-green-border\",\n  blue: \"bg-event-blue-border\",\n  purple: \"bg-event-purple-border\",\n  gray: \"bg-event-gray-border\",\n};\n\ninterface EventContextMenuProps {\n  /** The right-clicked event; \"Block on calendar\" moves it to that calendar */\n  event: DetailedCalendarEvent;\n  position: { x: number; y: number };\n  onClose: () => void;\n  onEventChange?: (event: DetailedCalendarEvent) => void;\n}\n\nfunction MenuItem({\n  className,\n  children,\n  onSelect,\n  disabled,\n  keyShortcuts,\n}: {\n  className?: string;\n  children: React.ReactNode;\n  onSelect?: () => void;\n  /** Its action isn't available (outside a calendar provider) */\n  disabled?: boolean;\n  /** The keys that run it, for assistive tech (`aria-keyshortcuts`) */\n  keyShortcuts?: string;\n}) {\n  return (\n    <button\n      type=\"button\"\n      disabled={disabled}\n      aria-keyshortcuts={keyShortcuts}\n      className={cn(\n        \"relative flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-xs outline-none select-none\",\n        \"text-white hover:bg-[#303030] focus:bg-[#303030]\",\n        \"disabled:pointer-events-none disabled:opacity-50\",\n        className,\n      )}\n      onClick={onSelect}\n    >\n      {children}\n    </button>\n  );\n}\n\n/** An action's keys at the end of its row. Screen readers get `aria-keyshortcuts` instead */\nfunction Shortcut({ children }: { children: React.ReactNode }) {\n  return (\n    <span aria-hidden className=\"ml-auto text-xs text-white/40\">\n      {children}\n    </span>\n  );\n}\n\nfunction Separator() {\n  return <div className=\"-mx-1 my-1 h-px bg-[#303030]\" />;\n}\n\nfunction SubMenu({\n  trigger,\n  children,\n}: {\n  trigger: React.ReactNode;\n  children: React.ReactNode;\n}) {\n  const [open, setOpen] = React.useState(false);\n  const timeoutRef = React.useRef<ReturnType<typeof setTimeout>>(null);\n\n  function handleMouseEnter() {\n    if (timeoutRef.current) clearTimeout(timeoutRef.current);\n    setOpen(true);\n  }\n\n  function handleMouseLeave() {\n    timeoutRef.current = setTimeout(() => setOpen(false), 150);\n  }\n\n  return (\n    <div\n      className=\"relative\"\n      onMouseEnter={handleMouseEnter}\n      onMouseLeave={handleMouseLeave}\n    >\n      <button\n        type=\"button\"\n        className={cn(\n          \"relative flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-xs outline-none select-none\",\n          \"text-white hover:bg-[#303030] focus:bg-[#303030]\",\n          open && \"bg-[#303030]\",\n        )}\n      >\n        {trigger}\n        <svg\n          className=\"ml-auto size-4 text-white/60\"\n          xmlns=\"http://www.w3.org/2000/svg\"\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth=\"2\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        >\n          <path d=\"m9 18 6-6-6-6\" />\n        </svg>\n      </button>\n      {open && (\n        <div className=\"absolute left-full top-0 ml-1 min-w-[180px] rounded-sm border border-[#303030] bg-[#252525] p-1 shadow-lg\">\n          {children}\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport function EventContextMenu({\n  event,\n  position,\n  onClose,\n  onEventChange,\n}: EventContextMenuProps) {\n  const menuRef = React.useRef<HTMLDivElement>(null);\n  const [adjustedPos, setAdjustedPos] = React.useState(position);\n  const [ready, setReady] = React.useState(false);\n  const { calendars } = useCalendarConfig();\n  const eventActions = useCalendarEventActions();\n  const currentColor = resolveEventColor(event, calendars);\n  const calendarGroups = React.useMemo(\n    () => groupCalendarsByEmail(calendars),\n    [calendars],\n  );\n\n  React.useLayoutEffect(() => {\n    const menu = menuRef.current;\n    if (!menu) return;\n\n    const menuHeight = menu.offsetHeight;\n    const menuWidth = menu.offsetWidth;\n    let y = position.y;\n    let x = position.x;\n\n    if (position.y + menuHeight > window.innerHeight) {\n      y = position.y - menuHeight;\n    }\n    if (position.x + menuWidth > window.innerWidth) {\n      x = position.x - menuWidth;\n    }\n\n    setAdjustedPos({ x, y });\n    setReady(true);\n  }, [position]);\n\n  React.useEffect(() => {\n    function handleClickOutside(e: MouseEvent) {\n      if (!menuRef.current) return;\n      if (menuRef.current.contains(e.target as Node)) return;\n      onClose();\n    }\n\n    function handleEscape(e: KeyboardEvent) {\n      if (e.key !== \"Escape\") return;\n      onClose();\n    }\n\n    // Use capture to close before other handlers fire\n    document.addEventListener(\"mousedown\", handleClickOutside, true);\n    document.addEventListener(\"keydown\", handleEscape);\n    return () => {\n      document.removeEventListener(\"mousedown\", handleClickOutside, true);\n      document.removeEventListener(\"keydown\", handleEscape);\n    };\n  }, [onClose]);\n\n  function handleColorSelect(color: EventColor) {\n    onEventChange?.({ ...event, color });\n    onClose();\n  }\n\n  function handleCalendarSelect(calendar: CalendarInfo) {\n    if (calendar.id !== event.calendarId) {\n      onEventChange?.(moveEventToCalendar(event, calendar, calendars));\n    }\n    onClose();\n  }\n\n  /** Closes the menu, then runs an event action on the right-clicked event */\n  function runAction(action: (eventId: string) => void) {\n    onClose();\n    action(event.id);\n  }\n\n  return createPortal(\n    <div\n      ref={menuRef}\n      className=\"fixed z-50 min-w-[200px] rounded-sm border border-[#303030] bg-[#252525] p-1 shadow-md animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none\"\n      style={{\n        top: adjustedPos.y,\n        left: adjustedPos.x,\n        opacity: ready ? 1 : 0,\n      }}\n    >\n      {/* Color selector row */}\n      <div className=\"flex items-center gap-1.5 px-2 py-1.5\">\n        {EVENT_COLORS.map((color) => (\n          <button\n            key={color}\n            type=\"button\"\n            className={cn(\n              \"relative flex size-3 items-center justify-center rounded-xs\",\n              EVENT_COLOR_SWATCH_CLASS[color],\n            )}\n            onClick={() => handleColorSelect(color)}\n          >\n            {color === currentColor && <Check className=\"size-2 text-white\" />}\n          </button>\n        ))}\n      </div>\n\n      {/* Block on calendar (only when the provider lists calendars) */}\n      {calendarGroups.length > 0 && (\n        <>\n          <Separator />\n          <SubMenu\n            trigger={\n              <>\n                <Monitor className=\"size-3.5\" />\n                Block on calendar\n              </>\n            }\n          >\n            {calendarGroups.map((group) => (\n              <React.Fragment key={group.email ?? \"\"}>\n                {group.email && (\n                  <div className=\"px-2 py-1 text-[10px] text-white/40\">\n                    {group.email}\n                  </div>\n                )}\n                {group.calendars.map((cal) => (\n                  <MenuItem\n                    key={cal.id}\n                    onSelect={() => handleCalendarSelect(cal)}\n                  >\n                    <div\n                      className={cn(\n                        \"size-3 rounded-xs shrink-0\",\n                        EVENT_COLOR_SWATCH_CLASS[cal.color],\n                      )}\n                    />\n                    {cal.name}\n                  </MenuItem>\n                ))}\n              </React.Fragment>\n            ))}\n          </SubMenu>\n        </>\n      )}\n\n      <Separator />\n\n      <MenuItem\n        disabled={!eventActions}\n        keyShortcuts={EVENT_ACTION_KEYS.cut.aria}\n        onSelect={\n          eventActions ? () => runAction(eventActions.cutEvent) : undefined\n        }\n      >\n        <SquareDashed className=\"size-3.5\" />\n        Cut\n        <Shortcut>{EVENT_ACTION_KEYS.cut.label}</Shortcut>\n      </MenuItem>\n      <MenuItem\n        disabled={!eventActions}\n        keyShortcuts={EVENT_ACTION_KEYS.copy.aria}\n        onSelect={\n          eventActions ? () => runAction(eventActions.copyEvent) : undefined\n        }\n      >\n        <TabletSmartphone className=\"size-3.5\" />\n        Copy\n        <Shortcut>{EVENT_ACTION_KEYS.copy.label}</Shortcut>\n      </MenuItem>\n      <MenuItem\n        disabled={!eventActions}\n        keyShortcuts={EVENT_ACTION_KEYS.duplicate.aria}\n        onSelect={\n          eventActions\n            ? () => runAction(eventActions.duplicateEvent)\n            : undefined\n        }\n      >\n        <Copy className=\"size-3.5\" />\n        Duplicate\n        <Shortcut>{EVENT_ACTION_KEYS.duplicate.label}</Shortcut>\n      </MenuItem>\n\n      <Separator />\n\n      <MenuItem\n        disabled={!eventActions}\n        keyShortcuts={EVENT_ACTION_KEYS.delete.aria}\n        onSelect={\n          eventActions ? () => runAction(eventActions.deleteEvent) : undefined\n        }\n        className=\"text-[#E56458] hover:!bg-[#DE5551] hover:!text-white focus:!bg-[#DE5551] focus:!text-white [&:hover>svg]:!text-white [&:focus>svg]:!text-white [&:hover>.ml-auto]:!text-white [&:focus>.ml-auto]:!text-white\"\n      >\n        <Trash2 className=\"size-3.5 text-[#E56458]\" />\n        Delete\n        <Shortcut>{EVENT_ACTION_KEYS.delete.label}</Shortcut>\n      </MenuItem>\n    </div>,\n    document.body,\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "src/hooks/use-popover-dismiss.ts",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { isEventInsideCalendarPopover } from \"@/components/calendar-popover-context\";\n\n/**\n * A trigger in the details whose popup is open: a menu, a select or a popover\n * in custom details. Radix and Base UI both set `aria-expanded` on it as soon\n * as the popup opens, before focus moves in.\n */\nconst OPEN_POPUP_TRIGGER_SELECTOR =\n  '[aria-expanded=\"true\"][aria-haspopup]:not([aria-haspopup=\"false\"]), [aria-expanded=\"true\"][role=\"combobox\"]';\n\ninterface PopoverDismissOptions {\n  /** The popover's panel */\n  panelRef: React.RefObject<HTMLElement | null>;\n  /** The element that toggles the popover itself; presses on it aren't outside */\n  triggerRef?: React.RefObject<Element | null>;\n  /** Called on Escape, before `onDismiss` */\n  onEscape: () => void;\n  onDismiss: () => void;\n}\n\n/** Spread on the panel, so the hook sees events from its React tree */\nexport interface PopoverDismissHandlers {\n  onPointerDownCapture: (e: React.PointerEvent) => void;\n  onFocusCapture: (e: React.FocusEvent) => void;\n}\n\n/**\n * Closes a popover the way a non-modal shadcn/ui popover does: on Escape, on\n * a press outside it and when focus moves outside it. Not outside: the panel\n * and everything in its React tree, including what it renders in portals (its\n * menus, a select's list in custom details); the trigger; and a layer opened\n * from the panel, which takes the press or the Escape for itself.\n *\n * On touch, a press outside closes the popover on the click that ends it, so\n * a scroll that starts outside doesn't.\n */\nexport function usePopoverDismiss({\n  panelRef,\n  triggerRef,\n  onEscape,\n  onDismiss,\n}: PopoverDismissOptions): PopoverDismissHandlers {\n  const onEscapeRef = React.useRef(onEscape);\n  const onDismissRef = React.useRef(onDismiss);\n  /**\n   * The native pointerdown and focusin events that went through the panel's\n   * React tree. The document listeners look their own event up here, which\n   * holds however React's root sits: React's capture handlers run before\n   * them whether React listens on a container (Vite) or on the document\n   * itself (Next.js App Router).\n   */\n  const [insideEvents] = React.useState(() => new WeakSet<Event>());\n  /**\n   * The element last focused through the panel's React tree while outside\n   * its DOM: focus is in a popup the details opened in a portal (a menu, a\n   * select's list, or a popover opened from inside one of those).\n   */\n  const portalFocusRef = React.useRef<Element | null>(null);\n\n  React.useEffect(() => {\n    onEscapeRef.current = onEscape;\n    onDismissRef.current = onDismiss;\n  }, [onEscape, onDismiss]);\n\n  React.useEffect(() => {\n    /**\n     * Whether a layer opened from the details is open: a trigger in the panel\n     * says so, or focus sits in a popup the panel rendered in a portal. It\n     * owns Escape and outside presses until it closes, the way stacked layers\n     * behave in shadcn/ui. Layers opened anywhere else on the page don't\n     * count.\n     */\n    function hasOpenLayer(): boolean {\n      if (panelRef.current?.querySelector(OPEN_POPUP_TRIGGER_SELECTOR)) {\n        return true;\n      }\n      const focused = portalFocusRef.current;\n      return focused !== null && focused === document.activeElement;\n    }\n\n    function isOutside(e: Event): boolean {\n      const target = e.target;\n      if (!(target instanceof Node)) return false;\n      if (insideEvents.has(e)) return false;\n      if (triggerRef?.current?.contains(target)) return false;\n      return !isEventInsideCalendarPopover(e);\n    }\n\n    function handleKeyDown(e: KeyboardEvent) {\n      if (e.key !== \"Escape\" || hasOpenLayer()) return;\n      // Marks the Escape as taken, as Radix layers do: a Radix dialog the\n      // calendar sits in then leaves it to the details and stays open\n      e.preventDefault();\n      onEscapeRef.current();\n      onDismissRef.current();\n    }\n\n    /** On touch, the click that ends the press; a scroll never fires one */\n    let pendingClick: (() => void) | null = null;\n    function clearPendingClick() {\n      if (!pendingClick) return;\n      document.removeEventListener(\"click\", pendingClick);\n      pendingClick = null;\n    }\n    function dismissOnClick() {\n      pendingClick = null;\n      onDismissRef.current();\n    }\n\n    /**\n     * Whether a layer opened from the panel was open when the press began.\n     * Read before the layer's own listeners can close it: a Base UI menu\n     * closes on a capture listener added after this one.\n     */\n    let layerOpenOnPress = false;\n    function notePointerDown() {\n      layerOpenOnPress = hasOpenLayer();\n    }\n\n    function handlePointerDown(e: PointerEvent) {\n      if (layerOpenOnPress || !isOutside(e)) {\n        // A press inside cancels a touch outside still waiting for its click\n        clearPendingClick();\n        return;\n      }\n      if (e.pointerType !== \"touch\") {\n        onDismissRef.current();\n        return;\n      }\n      clearPendingClick();\n      pendingClick = dismissOnClick;\n      document.addEventListener(\"click\", dismissOnClick, { once: true });\n    }\n\n    function handleFocusIn(e: FocusEvent) {\n      if (hasOpenLayer() || !isOutside(e)) return;\n      // Focus on an element the panel sits in (the dialog it's portaled into,\n      // after a press on a blank part of it) hasn't left the panel\n      const panel = panelRef.current;\n      if (panel && e.target instanceof Node && e.target.contains(panel)) return;\n      onDismissRef.current();\n    }\n\n    // Escape is handled first, on the window's capture phase: before the\n    // calendar's own key handlers, and before a dialog's on the document\n    window.addEventListener(\"keydown\", handleKeyDown, true);\n    document.addEventListener(\"pointerdown\", notePointerDown, true);\n    document.addEventListener(\"focusin\", handleFocusIn);\n    // Start listening for presses a tick later, so the press that opened the\n    // popover doesn't close it\n    const timer = window.setTimeout(() => {\n      document.addEventListener(\"pointerdown\", handlePointerDown);\n    }, 0);\n\n    return () => {\n      window.clearTimeout(timer);\n      window.removeEventListener(\"keydown\", handleKeyDown, true);\n      document.removeEventListener(\"pointerdown\", notePointerDown, true);\n      document.removeEventListener(\"focusin\", handleFocusIn);\n      document.removeEventListener(\"pointerdown\", handlePointerDown);\n      clearPendingClick();\n    };\n  }, [panelRef, triggerRef, insideEvents]);\n\n  return React.useMemo(\n    () => ({\n      onPointerDownCapture: (e: React.PointerEvent) => {\n        insideEvents.add(e.nativeEvent);\n      },\n      onFocusCapture: (e: React.FocusEvent) => {\n        insideEvents.add(e.nativeEvent);\n        const panel = panelRef.current;\n        const target = e.target;\n        const inPortal =\n          target instanceof Element &&\n          panel !== null &&\n          !panel.contains(target);\n        portalFocusRef.current = inPortal ? target : null;\n      },\n    }),\n    [insideEvents, panelRef],\n  );\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-inline-edit.ts",
      "content": "import * as React from \"react\";\n\n/**\n * Options for `useInlineEdit`\n */\nexport interface UseInlineEditOptions {\n  /** The input's ref, used to blur it on Enter and Escape */\n  inputRef: React.RefObject<HTMLInputElement | null>;\n  /** Text the field shows while it isn't being edited, derived from the event */\n  value: string;\n  /**\n   * Commits the typed text on blur or Enter. Returns the text to show\n   * afterwards, or `null` to reject it and restore the text from focus.\n   */\n  onCommit: (text: string) => string | null;\n  /** Called on every keystroke, e.g. to preview a title on the calendar */\n  onInput?: (text: string) => void;\n  /**\n   * Called with the text from focus after Escape or a rejected commit, e.g.\n   * to undo a preview\n   */\n  onRestore?: (text: string) => void;\n}\n\n/**\n * Props to spread on the `<input>` an inline edit drives (pass its ref\n * separately)\n */\nexport interface InlineEditInputProps {\n  value: string;\n  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n  onFocus: () => void;\n  onBlur: () => void;\n  onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;\n}\n\n/**\n * Value `useInlineEdit` returns\n */\nexport interface UseInlineEditResult {\n  /** Text in the field right now, typed or derived */\n  text: string;\n  /** Spread on the `<input>` */\n  inputProps: InlineEditInputProps;\n}\n\n/**\n * The details panel's inline edit pattern for one text field: local text\n * while typing, Enter commits by blurring, Escape restores the text from\n * focus without committing (and stops the key from reaching the calendar's\n * global Escape, which would deselect the event).\n */\nexport function useInlineEdit({\n  inputRef,\n  value,\n  onCommit,\n  onInput,\n  onRestore,\n}: UseInlineEditOptions): UseInlineEditResult {\n  const [text, setText] = React.useState(value);\n  /** Set by Escape so the blur that follows doesn't commit */\n  const escapePressedRef = React.useRef(false);\n  /** Text when the field gained focus, restored on Escape or a rejected commit */\n  const valueOnFocusRef = React.useRef(value);\n\n  // Follow the event while the field isn't being typed into\n  React.useEffect(() => {\n    setText(value);\n  }, [value]);\n\n  const handleChange = React.useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      setText(e.target.value);\n      onInput?.(e.target.value);\n    },\n    [onInput],\n  );\n\n  const handleFocus = React.useCallback(() => {\n    valueOnFocusRef.current = value;\n  }, [value]);\n\n  const handleBlur = React.useCallback(() => {\n    if (escapePressedRef.current) {\n      escapePressedRef.current = false;\n      return;\n    }\n    const committed = onCommit(text);\n    if (committed !== null) {\n      setText(committed);\n      return;\n    }\n    setText(valueOnFocusRef.current);\n    onRestore?.(valueOnFocusRef.current);\n  }, [onCommit, onRestore, text]);\n\n  const handleKeyDown = React.useCallback(\n    (e: React.KeyboardEvent<HTMLInputElement>) => {\n      if (e.key === \"Enter\") {\n        // The Enter that confirms an IME composition belongs to the IME\n        // (Safari reports it as keyCode 229, with isComposing already false)\n        if (e.nativeEvent.isComposing || e.keyCode === 229) return;\n        e.preventDefault();\n        inputRef.current?.blur();\n        return;\n      }\n      if (e.key !== \"Escape\") return;\n      e.preventDefault();\n      e.stopPropagation();\n      escapePressedRef.current = true;\n      setText(valueOnFocusRef.current);\n      onRestore?.(valueOnFocusRef.current);\n      inputRef.current?.blur();\n    },\n    [inputRef, onRestore],\n  );\n\n  return {\n    text,\n    inputProps: {\n      value: text,\n      onChange: handleChange,\n      onFocus: handleFocus,\n      onBlur: handleBlur,\n      onKeyDown: handleKeyDown,\n    },\n  };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-hover-tooltip.ts",
      "content": "import * as React from \"react\";\n\n/**\n * Value `useHoverTooltip` returns\n */\nexport interface UseHoverTooltipResult {\n  /** Whether the tooltip shows */\n  isOpen: boolean;\n  /** The pointer entered the trigger: opens after `TOOLTIP_OPEN_DELAY` */\n  scheduleOpen: () => void;\n  /** The pointer left the trigger or the tooltip: closes after `TOOLTIP_CLOSE_DELAY` */\n  scheduleClose: () => void;\n  /** The pointer reached the tooltip before it closed: keeps it open */\n  keepOpen: () => void;\n}\n\n/** How long the pointer rests on a trigger before its tooltip shows, in ms */\nconst TOOLTIP_OPEN_DELAY = 500;\n\n/** Time to move the pointer from a trigger onto its tooltip, in ms */\nconst TOOLTIP_CLOSE_DELAY = 120;\n\n/**\n * Open state of a tooltip that shows after the pointer rests on its\n * trigger, and stays while the pointer moves onto it\n */\nexport function useHoverTooltip(): UseHoverTooltipResult {\n  const [isOpen, setIsOpen] = React.useState(false);\n  const timerRef = React.useRef<number | null>(null);\n\n  const clearTimer = React.useCallback(() => {\n    if (timerRef.current === null) return;\n    window.clearTimeout(timerRef.current);\n    timerRef.current = null;\n  }, []);\n\n  React.useEffect(() => clearTimer, [clearTimer]);\n\n  const scheduleOpen = React.useCallback(() => {\n    clearTimer();\n    timerRef.current = window.setTimeout(\n      () => setIsOpen(true),\n      TOOLTIP_OPEN_DELAY,\n    );\n  }, [clearTimer]);\n\n  const scheduleClose = React.useCallback(() => {\n    clearTimer();\n    timerRef.current = window.setTimeout(\n      () => setIsOpen(false),\n      TOOLTIP_CLOSE_DELAY,\n    );\n  }, [clearTimer]);\n\n  return { isOpen, scheduleOpen, scheduleClose, keepOpen: clearTimer };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/hooks/use-field-popover.ts",
      "content": "import * as React from \"react\";\n\n/** Attribute marking a field's popover: focus moving into it comes straight back */\nexport const FIELD_POPOVER_ATTRIBUTE = \"data-event-detail-field-popover\";\n\n/**\n * Options for `useFieldPopover`\n */\nexport interface UseFieldPopoverOptions {\n  /** The field's input */\n  inputRef: React.RefObject<HTMLInputElement | null>;\n  /** Whether the field's popover is open */\n  open: boolean;\n  /** Focus came into the field: opens the popover */\n  onEnter: () => void;\n  /** Focus left the field, not by Escape or a pick: sets what was typed or chosen */\n  onCommit: () => void;\n  /** Escape: puts back the value from before the popover opened */\n  onRestore: () => void;\n  /** Closes the popover */\n  onClose: () => void;\n}\n\n/**\n * Value `useFieldPopover` returns\n */\nexport interface UseFieldPopoverResult {\n  /** Spread on the `<input>` */\n  inputProps: {\n    onFocus: (e: React.FocusEvent<HTMLInputElement>) => void;\n    onBlur: (e: React.FocusEvent<HTMLInputElement>) => void;\n  };\n  /** Called as a press on the field's box starts */\n  notePress: () => void;\n  /** Called before the popover hands focus back to the input */\n  noteReturnFocus: () => void;\n  /** Escape: restores the value, closes the popover and leaves the field */\n  escape: () => void;\n  /** Closes the popover and leaves the field after a pick that set the value */\n  leave: () => void;\n}\n\n/** Selects an input's text once React has put its new value in it */\nexport function selectInputSoon(\n  inputRef: React.RefObject<HTMLInputElement | null>,\n) {\n  requestAnimationFrame(() => {\n    const input = inputRef.current;\n    if (input && document.activeElement === input) input.select();\n  });\n}\n\n/** Whether focus is moving into a field popover (it comes straight back) */\nfunction isFieldPopover(target: EventTarget | null): boolean {\n  return (\n    target instanceof Element &&\n    target.closest(`[${FIELD_POPOVER_ATTRIBUTE}]`) !== null\n  );\n}\n\n/**\n * Focus, blur and Escape for a details field with a popover (the time menu,\n * the date picker), following the panel's inline edit pattern: focus opens\n * the popover, blur commits and closes it, Escape restores the value and\n * leaves the field without committing.\n *\n * The popover libraries move focus as they open and close, and the hook\n * keeps it in the field:\n * - Opening, the popover takes focus and hands it back to the input; that\n *   focus isn't entering the field again.\n * - Escape reaches Radix and Base UI on the document, where Base UI stops\n *   it, so the hook takes it first on the window while the popover is open,\n *   and keeps it from the details' and the calendar's own Escape (which\n *   would deselect the event).\n * - Closing, Base UI hands focus back to the input it came from. After the\n *   field is left, a focus with no source is that hand-back until the field\n *   is pressed again, and it's turned away.\n */\nexport function useFieldPopover({\n  inputRef,\n  open,\n  onEnter,\n  onCommit,\n  onRestore,\n  onClose,\n}: UseFieldPopoverOptions): UseFieldPopoverResult {\n  const optionsRef = React.useRef({\n    open,\n    onEnter,\n    onCommit,\n    onRestore,\n    onClose,\n  });\n  /** Set while the popover hands focus back to the input */\n  const returningFocusRef = React.useRef(false);\n  /** Set when the field is left with its popover open, until it's pressed again */\n  const leftOpenRef = React.useRef(false);\n  /** Set by Escape and a pick, whose blur must not commit again */\n  const skipBlurCommitRef = React.useRef(false);\n\n  React.useEffect(() => {\n    optionsRef.current = { open, onEnter, onCommit, onRestore, onClose };\n  }, [open, onEnter, onCommit, onRestore, onClose]);\n\n  const leave = React.useCallback(() => {\n    const wasOpen = optionsRef.current.open;\n    optionsRef.current.onClose();\n    const input = inputRef.current;\n    if (!input || document.activeElement !== input) return;\n    leftOpenRef.current = wasOpen;\n    skipBlurCommitRef.current = true;\n    input.blur();\n  }, [inputRef]);\n\n  const escape = React.useCallback(() => {\n    optionsRef.current.onRestore();\n    leave();\n  }, [leave]);\n\n  React.useEffect(() => {\n    if (!open) return;\n    function handleKeyDown(e: KeyboardEvent) {\n      if (e.key !== \"Escape\" || document.activeElement !== inputRef.current) {\n        return;\n      }\n      e.preventDefault();\n      e.stopPropagation();\n      escape();\n    }\n    window.addEventListener(\"keydown\", handleKeyDown, true);\n    return () => window.removeEventListener(\"keydown\", handleKeyDown, true);\n  }, [open, inputRef, escape]);\n\n  const handleFocus = React.useCallback(\n    (e: React.FocusEvent<HTMLInputElement>) => {\n      if (returningFocusRef.current) {\n        returningFocusRef.current = false;\n        return;\n      }\n      if (leftOpenRef.current && e.relatedTarget === null) {\n        leftOpenRef.current = false;\n        skipBlurCommitRef.current = true;\n        e.currentTarget.blur();\n        return;\n      }\n      leftOpenRef.current = false;\n      optionsRef.current.onEnter();\n    },\n    [],\n  );\n\n  const handleBlur = React.useCallback(\n    (e: React.FocusEvent<HTMLInputElement>) => {\n      if (isFieldPopover(e.relatedTarget)) return;\n      if (skipBlurCommitRef.current) {\n        skipBlurCommitRef.current = false;\n        optionsRef.current.onClose();\n        return;\n      }\n      optionsRef.current.onCommit();\n      optionsRef.current.onClose();\n    },\n    [],\n  );\n\n  const notePress = React.useCallback(() => {\n    leftOpenRef.current = false;\n  }, []);\n\n  const noteReturnFocus = React.useCallback(() => {\n    returningFocusRef.current = true;\n  }, []);\n\n  return {\n    inputProps: { onFocus: handleFocus, onBlur: handleBlur },\n    notePress,\n    noteReturnFocus,\n    escape,\n    leave,\n  };\n}\n",
      "type": "registry:hook"
    },
    {
      "path": "src/lib/time-input.ts",
      "content": "import {\n  addDays,\n  addMinutes,\n  differenceInMinutes,\n  format,\n  parse,\n  startOfDay,\n} from \"date-fns\";\nimport type { Locale } from \"date-fns\";\n\nimport type {\n  DetailedCalendarEvent,\n  HourCycle,\n  TimeOption,\n} from \"@/components/week-view-types\";\n\n/** Minutes between two options of the time menu, as in Notion Calendar */\nconst TIME_STEP_MINUTES = 15;\n\n/** Minutes in a day on the wall clock */\nconst MINUTES_PER_DAY = 24 * 60;\n\n/** Options in a day of the time menu: every TIME_STEP_MINUTES from midnight */\nconst TIME_OPTIONS_PER_DAY = MINUTES_PER_DAY / TIME_STEP_MINUTES;\n\n/** A bare hour like \"7\" prefers the reading between 8 AM and 8 PM: 7 PM */\nconst DAYTIME_START_MINUTES = 8 * 60;\n\n/** End of the daytime a bare hour prefers (8 PM) */\nconst DAYTIME_END_MINUTES = 20 * 60;\n\n/**\n * A number typed as a duration below this reads as hours first (\"2\" → 2h,\n * then 2min), from it as minutes first (\"45\" → 45min, then 45h)\n */\nconst DURATION_HOURS_FIRST_BELOW = 15;\n\n/** Longest duration a typed number may stand for: a week */\nconst MAX_TYPED_DURATION_MINUTES = 7 * 24 * 60;\n\n/** Formats a time for the time menu: \"4:15 PM\", or \"16:15\" on a 24-hour clock */\ntype FormatTime = (date: Date) => string;\n\n/** \"45min\", \"2h\" or \"1h 30min\" */\nexport function formatDuration(start: Date, end: Date): string {\n  const totalMinutes = differenceInMinutes(end, start);\n\n  if (totalMinutes < 60) {\n    return `${totalMinutes}min`;\n  }\n\n  const hours = Math.floor(totalMinutes / 60);\n  const minutes = totalMinutes % 60;\n\n  if (minutes === 0) {\n    return `${hours}h`;\n  }\n\n  return `${hours}h ${minutes}min`;\n}\n\n/**\n * Returns a new Date with the same year/month/day as `base`\n * but with hours and minutes replaced.\n */\nexport function applyTimeToDate(\n  base: Date,\n  hours: number,\n  minutes: number,\n): Date {\n  const result = new Date(base);\n  result.setHours(hours, minutes, 0, 0);\n  return result;\n}\n\n/**\n * The time `minutes` after midnight on `day`'s wall clock, or null when the\n * clock skips it (2:30 AM on the day daylight saving time starts). Counting\n * elapsed minutes from midnight instead would land an hour off on that day\n * and on the day it ends.\n */\nfunction clockTime(day: Date, minutes: number): Date | null {\n  const date = applyTimeToDate(day, Math.floor(minutes / 60), minutes % 60);\n  if (date.getHours() * 60 + date.getMinutes() !== minutes) return null;\n  return date;\n}\n\n/** Minutes typed after an hour: \"3\" means 30 (\"7:3\" → 7:30), \"7\" means 07 (\"3:7\" → 3:07) */\nfunction readTypedMinutes(digits: string): number {\n  if (digits.length === 0) return 0;\n  if (digits.length > 1) return Number(digits);\n  const digit = Number(digits);\n  return digit < 6 ? digit * 10 : digit;\n}\n\n/** Text typed in a time field, lowercased, without spaces or dots */\nfunction normalizeTyped(text: string): string {\n  return text.toLowerCase().replace(/[\\s.]/g, \"\");\n}\n\n/**\n * Times of day (minutes from midnight) typed text can mean, best first, as\n * Notion Calendar reads them: \"7\" → 7 PM, 7 AM; \"9\" → 9 AM, 9 PM (a bare\n * hour prefers 8 AM–8 PM); \"12\" → 12 PM, 12 AM, 1:20 PM, 1:20 AM (the first\n * digit as the hour too); \"930\" → 9:30 AM, 9:30 PM; \"7:3p\" → 7:30 PM. On a\n * 24-hour clock a bare hour reads as written first: \"7\" → 07:00, 19:00.\n */\nfunction readTypedTimes(text: string, hourCycle: HourCycle): number[] {\n  const match = /^(\\d{1,4})(?::(\\d{0,2}))?(a|am|p|pm)?$/.exec(\n    normalizeTyped(text),\n  );\n  if (!match) return [];\n  const [, digits, colonMinutes, period] = match;\n\n  const readings: Array<{ hour: number; minute: number }> = [];\n  if (colonMinutes !== undefined) {\n    if (digits.length <= 2) {\n      readings.push({\n        hour: Number(digits),\n        minute: readTypedMinutes(colonMinutes),\n      });\n    }\n  } else {\n    if (digits.length <= 2) {\n      readings.push({ hour: Number(digits), minute: 0 });\n    }\n    if (digits.length >= 2 && digits.length <= 3) {\n      readings.push({\n        hour: Number(digits[0]),\n        minute: readTypedMinutes(digits.slice(1)),\n      });\n    }\n    if (digits.length >= 3) {\n      readings.push({\n        hour: Number(digits.slice(0, 2)),\n        minute: readTypedMinutes(digits.slice(2)),\n      });\n    }\n  }\n\n  const times: number[] = [];\n  for (const { hour, minute } of readings) {\n    if (minute > 59) continue;\n    for (const minutes of readHour(hour, period, hourCycle)) {\n      const time = minutes + minute;\n      if (!times.includes(time)) times.push(time);\n    }\n  }\n  return times;\n}\n\n/**\n * Minutes from midnight an hour can mean, best first: one with \"am\"/\"pm\" or\n * outside 1–12, the daytime one first otherwise\n */\nfunction readHour(\n  hour: number,\n  period: string | undefined,\n  hourCycle: HourCycle,\n): number[] {\n  if (period) {\n    if (hour < 1 || hour > 12) return [];\n    const isPm = period.startsWith(\"p\");\n    return [((hour % 12) + (isPm ? 12 : 0)) * 60];\n  }\n  if (hour > 23) return [];\n  if (hour === 0 || hour > 12) return [hour * 60];\n\n  const morning = (hour % 12) * 60;\n  const evening = morning + 12 * 60;\n  if (hourCycle === 24) return [hour * 60, hour === 12 ? 0 : evening];\n  const isDaytime = (minutes: number) =>\n    minutes >= DAYTIME_START_MINUTES && minutes < DAYTIME_END_MINUTES;\n  if (isDaytime(evening) && !isDaytime(morning)) return [evening, morning];\n  return [morning, evening];\n}\n\n/**\n * Durations (minutes) typed text can mean in the end field, best first:\n * \"2\" → 2h, 2min; \"45\" → 45min, 45h; \"8:30\" → 8h 30min; \"1h30\" → 1h 30min.\n * Text with \"am\" or \"pm\" is a time, never a duration.\n */\nfunction readTypedDurations(text: string): number[] {\n  const typed = normalizeTyped(text);\n  const durations: number[] = [];\n\n  const units = /^(?:(\\d{1,3})h)?(?:(\\d{1,4})(?:m|min|mins)?)?$/.exec(typed);\n  const clock = /^(\\d{1,3})(?::(\\d{0,2}))?$/.exec(typed);\n  if (clock) {\n    const [, digits, colonMinutes] = clock;\n    const number = Number(digits);\n    if (colonMinutes !== undefined) {\n      const minutes = readTypedMinutes(colonMinutes);\n      if (minutes < 60) durations.push(number * 60 + minutes);\n    } else if (number < DURATION_HOURS_FIRST_BELOW) {\n      durations.push(number * 60, number);\n    } else {\n      durations.push(number, number * 60);\n    }\n  } else if (units && (units[1] || units[2])) {\n    durations.push(Number(units[1] ?? 0) * 60 + Number(units[2] ?? 0));\n  }\n\n  return durations.filter(\n    (minutes, index) =>\n      minutes > 0 &&\n      minutes <= MAX_TYPED_DURATION_MINUTES &&\n      durations.indexOf(minutes) === index,\n  );\n}\n\n/** The dates in order, each time once */\nfunction uniqueDates(dates: Date[]): Date[] {\n  return dates.filter(\n    (date, index) =>\n      dates.findIndex((other) => other.getTime() === date.getTime()) === index,\n  );\n}\n\n/** The options' list with `value` in its place, when it's between two steps */\nfunction withValue(options: TimeOption[], value: TimeOption): TimeOption[] {\n  const time = value.date.getTime();\n  if (options.some((option) => option.date.getTime() === time)) {\n    return options;\n  }\n  const index = options.findIndex((option) => option.date.getTime() > time);\n  if (index === -1) return [...options, value];\n  return [...options.slice(0, index), value, ...options.slice(index)];\n}\n\n/**\n * Every 15 minutes of `day` on its wall clock: 96 times, 92 on the day\n * daylight saving time starts (the skipped hour), and each 1 AM–1:45 AM\n * once on the day it ends\n */\nfunction getDayTimes(day: Date): Date[] {\n  const midnight = startOfDay(day);\n  const times: Date[] = [];\n  for (let i = 0; i < TIME_OPTIONS_PER_DAY; i++) {\n    const date = clockTime(midnight, i * TIME_STEP_MINUTES);\n    if (date) times.push(date);\n  }\n  return times;\n}\n\n/** Every 15 minutes after `start` on the wall clock, up to the same time a day later */\nfunction getTimesAfter(start: Date): Date[] {\n  const midnight = startOfDay(start);\n  const startMinutes = start.getHours() * 60 + start.getMinutes();\n  const times: Date[] = [];\n  for (let i = 1; i <= TIME_OPTIONS_PER_DAY; i++) {\n    const minutes = startMinutes + i * TIME_STEP_MINUTES;\n    const day = addDays(midnight, Math.floor(minutes / MINUTES_PER_DAY));\n    const date = clockTime(day, minutes % MINUTES_PER_DAY);\n    if (date && date > start) times.push(date);\n  }\n  return times;\n}\n\n/**\n * Whether an event ends after the midnight that closes its first day, so\n * its end time needs a date (an end at that midnight doesn't)\n */\nexport function endsOnLaterDay(start: Date, end: Date): boolean {\n  return end > addDays(startOfDay(start), 1);\n}\n\n/** The start time menu: every 15 minutes of the start's day, with the start in its place */\nexport function getStartTimeOptions(\n  start: Date,\n  formatTime: FormatTime,\n): TimeOption[] {\n  const options = getDayTimes(start).map((date) => ({\n    date,\n    label: formatTime(date),\n  }));\n  return withValue(options, { date: start, label: formatTime(start) });\n}\n\n/**\n * The end time menu, each option with how long the event lasts: every 15\n * minutes after the start for a day, or every 15 minutes of the end's day\n * for an event that ends on a later day; the end in its place\n */\nexport function getEndTimeOptions(\n  start: Date,\n  end: Date,\n  formatTime: FormatTime,\n): TimeOption[] {\n  const toOption = (date: Date): TimeOption => ({\n    date,\n    label: formatTime(date),\n    hint: formatDuration(start, date),\n  });\n  const dates = endsOnLaterDay(start, end)\n    ? getDayTimes(end).filter((date) => date > start)\n    : getTimesAfter(start);\n  const options = dates.map(toOption);\n  return end > start ? withValue(options, toOption(end)) : options;\n}\n\n/** Start times typed text can mean on the start's day, best first */\nexport function matchStartTimes(\n  text: string,\n  start: Date,\n  hourCycle: HourCycle,\n  formatTime: FormatTime,\n): TimeOption[] {\n  const midnight = startOfDay(start);\n  return readTypedTimes(text, hourCycle).flatMap((minutes) => {\n    const date = clockTime(midnight, minutes);\n    return date ? [{ date, label: formatTime(date) }] : [];\n  });\n}\n\n/**\n * End times typed text can mean, best first, with how long the event lasts:\n * times of the end's day after the start (the next day's when they aren't),\n * then durations from the start\n */\nexport function matchEndTimes(\n  text: string,\n  start: Date,\n  end: Date,\n  hourCycle: HourCycle,\n  formatTime: FormatTime,\n): TimeOption[] {\n  const midnight = startOfDay(endsOnLaterDay(start, end) ? end : start);\n  const dates: Date[] = [];\n  for (const minutes of readTypedTimes(text, hourCycle)) {\n    const sameDay = clockTime(midnight, minutes);\n    const date =\n      sameDay && sameDay > start\n        ? sameDay\n        : clockTime(addDays(midnight, 1), minutes);\n    if (date) dates.push(date);\n  }\n  for (const minutes of readTypedDurations(text)) {\n    dates.push(addMinutes(start, minutes));\n  }\n  return uniqueDates(dates).map((date) => ({\n    date,\n    label: formatTime(date),\n    hint: formatDuration(start, date),\n  }));\n}\n\n/** \"Sat Jun 6\", in the calendar's locale */\nexport function formatDateDisplay(date: Date, locale: Locale): string {\n  return format(date, \"EEE MMM d\", { locale });\n}\n\n/**\n * Parses a user-typed date string into a Date.\n * Strips any leading weekday name and parses \"MMM d\" (e.g., \"Mar 11\") in\n * the calendar's locale. Uses the reference date's year. Returns null if\n * unparseable.\n */\nexport function parseDateInput(\n  input: string,\n  referenceDate: Date,\n  locale: Locale,\n): Date | null {\n  const trimmed = input.trim();\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  // Strip an optional leading weekday (\"Tue \", \"sáb \") when a month name follows\n  const withoutWeekday = trimmed.replace(/^[^\\s\\d]+\\s+(?=[^\\s\\d])/, \"\");\n\n  const parsed = parse(withoutWeekday, \"MMM d\", referenceDate, { locale });\n  if (Number.isNaN(parsed.getTime())) {\n    return null;\n  }\n\n  return parsed;\n}\n\n/** Whether the event has a time of day (an all-day event's are all midnight) */\nexport function hasTimeOfDay(event: DetailedCalendarEvent): boolean {\n  return (\n    event.start.getHours() !== 0 ||\n    event.start.getMinutes() !== 0 ||\n    event.end.getHours() !== 0 ||\n    event.end.getMinutes() !== 0\n  );\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:component"
}