{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-week",
  "type": "registry:block",
  "title": "Calendar Week",
  "description": "A week calendar you can push around: drag events to move or stretch them on a 15-minute snap, drag empty time to create one, nudge with the arrow keys, and watch the now line creep down the day.",
  "categories": [
    "screen",
    "Comms"
  ],
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/calendar.json",
    "https://coss.com/ui/r/kbd.json",
    "https://coss.com/ui/r/popover.json"
  ],
  "files": [
    {
      "path": "registry/devl/calendar-week.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport {\n  CalendarDaysIcon,\n  CheckIcon,\n  ChevronDownIcon,\n  ChevronLeftIcon,\n  ChevronRightIcon,\n  ClockIcon,\n  MapPinIcon,\n  PlusIcon,\n  Trash2Icon,\n  UsersIcon,\n  VideoIcon,\n  XIcon,\n} from \"lucide-react\";\nimport {\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  type RefObject,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Calendar } from \"@/components/ui/calendar\";\nimport { Kbd } from \"@/components/ui/kbd\";\nimport { Popover, PopoverPopup, PopoverTrigger } from \"@/components/ui/popover\";\nimport { cn } from \"@/lib/utils\";\n\nexport type CalendarTone = \"teal\" | \"violet\" | \"sky\" | \"amber\" | \"rose\";\n\nexport interface CalendarSource {\n  id: string;\n  name: string;\n  tone: CalendarTone;\n  visible?: boolean;\n}\n\nexport interface CalendarEvent {\n  id: string;\n  title: string;\n  calendar: string;\n  date: string;\n  start: number;\n  end: number;\n  allDay?: boolean;\n  days?: number;\n  location?: string;\n  video?: boolean;\n  people?: string[];\n}\n\nexport interface CalendarWeekProps {\n  calendars?: CalendarSource[];\n  events?: CalendarEvent[];\n  now?: string;\n  className?: string;\n}\n\nconst toneDot: Record<CalendarTone, string> = {\n  teal: \"bg-teal-500\",\n  violet: \"bg-violet-500\",\n  sky: \"bg-sky-500\",\n  amber: \"bg-amber-500\",\n  rose: \"bg-rose-500\",\n};\n\nconst toneBlock: Record<CalendarTone, string> = {\n  teal: \"bg-[color-mix(in_oklab,var(--color-teal-500)_14%,var(--background))] text-teal-950 before:bg-teal-500 dark:bg-[color-mix(in_oklab,var(--color-teal-400)_16%,var(--background))] dark:text-teal-50\",\n  violet: \"bg-[color-mix(in_oklab,var(--color-violet-500)_14%,var(--background))] text-violet-950 before:bg-violet-500 dark:bg-[color-mix(in_oklab,var(--color-violet-400)_18%,var(--background))] dark:text-violet-50\",\n  sky: \"bg-[color-mix(in_oklab,var(--color-sky-500)_14%,var(--background))] text-sky-950 before:bg-sky-500 dark:bg-[color-mix(in_oklab,var(--color-sky-400)_16%,var(--background))] dark:text-sky-50\",\n  amber: \"bg-[color-mix(in_oklab,var(--color-amber-500)_18%,var(--background))] text-amber-950 before:bg-amber-500 dark:bg-[color-mix(in_oklab,var(--color-amber-400)_16%,var(--background))] dark:text-amber-50\",\n  rose: \"bg-[color-mix(in_oklab,var(--color-rose-500)_14%,var(--background))] text-rose-950 before:bg-rose-500 dark:bg-[color-mix(in_oklab,var(--color-rose-400)_16%,var(--background))] dark:text-rose-50\",\n};\n\nconst toneSolid: Record<CalendarTone, string> = {\n  teal: \"bg-teal-600 text-white before:bg-teal-800 dark:bg-teal-500\",\n  violet: \"bg-violet-600 text-white before:bg-violet-800 dark:bg-violet-500\",\n  sky: \"bg-sky-600 text-white before:bg-sky-800 dark:bg-sky-500\",\n  amber: \"bg-amber-500 text-amber-950 before:bg-amber-700\",\n  rose: \"bg-rose-600 text-white before:bg-rose-800 dark:bg-rose-500\",\n};\n\nconst toneCheck: Record<CalendarTone, string> = {\n  teal: \"border-teal-500 bg-teal-500\",\n  violet: \"border-violet-500 bg-violet-500\",\n  sky: \"border-sky-500 bg-sky-500\",\n  amber: \"border-amber-500 bg-amber-500\",\n  rose: \"border-rose-500 bg-rose-500\",\n};\n\nconst HOUR = 48;\nconst PX = HOUR / 60;\nconst SNAP = 15;\nconst ease = [0.23, 1, 0.32, 1] as const;\nconst settle = { type: \"spring\", stiffness: 640, damping: 46 } as const;\n\nconst MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\nconst DOW = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\nconst DAY_NAMES = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"];\n\nfunction parse(iso: string) {\n  const [y, m, d] = iso.split(\"-\").map(Number);\n  return new Date(Date.UTC(y, m - 1, d));\n}\nfunction iso(d: Date) {\n  return d.toISOString().slice(0, 10);\n}\nfunction addDays(date: string, n: number) {\n  const d = parse(date);\n  d.setUTCDate(d.getUTCDate() + n);\n  return iso(d);\n}\nfunction weekday(date: string) {\n  return (parse(date).getUTCDay() + 6) % 7;\n}\nfunction startOfWeek(date: string) {\n  return addDays(date, -weekday(date));\n}\nfunction isoWeek(date: string) {\n  const d = parse(date);\n  d.setUTCDate(d.getUTCDate() + 3 - ((d.getUTCDay() + 6) % 7));\n  const jan4 = new Date(Date.UTC(d.getUTCFullYear(), 0, 4));\n  return 1 + Math.round(((d.getTime() - jan4.getTime()) / 86400000 - 3 + ((jan4.getUTCDay() + 6) % 7)) / 7);\n}\n\nfunction diffDays(a: string, b: string) {\n  return Math.round((parse(a).getTime() - parse(b).getTime()) / 86400000);\n}\nfunction fmtTime(min: number, withPeriod = true) {\n  const h = Math.floor(min / 60) % 24;\n  const m = min % 60;\n  const h12 = ((h + 11) % 12) + 1;\n  const period = h >= 12 ? \"PM\" : \"AM\";\n  return `${h12}${m ? `:${String(m).padStart(2, \"0\")}` : \"\"}${withPeriod ? ` ${period}` : \"\"}`;\n}\nfunction fmtRange(a: number, b: number) {\n  const samePeriod = a < 720 === b < 720;\n  return `${fmtTime(a, !samePeriod)} – ${fmtTime(b)}`;\n}\nfunction fmtDuration(min: number) {\n  const h = Math.floor(min / 60);\n  const m = min % 60;\n  return h ? `${h}h${m ? ` ${m}m` : \"\"}` : `${m}m`;\n}\nconst snap = (min: number) => Math.round(min / SNAP) * SNAP;\n\nconst defaultCalendars: CalendarSource[] = [\n  { id: \"me\", name: \"Maya Okafor\", tone: \"teal\", visible: true },\n  { id: \"team\", name: \"Team\", tone: \"violet\", visible: true },\n  { id: \"product\", name: \"Product reviews\", tone: \"sky\", visible: true },\n  { id: \"launches\", name: \"Launches\", tone: \"amber\", visible: true },\n  { id: \"holidays\", name: \"Holidays\", tone: \"rose\", visible: true },\n];\n\nfunction buildEvents(): CalendarEvent[] {\n  const wk = \"2026-10-19\";\n  const d = (n: number) => addDays(wk, n);\n  const t = (h: number, m = 0) => h * 60 + m;\n  const standups: CalendarEvent[] = [];\n  for (let w = -1; w <= 1; w++) {\n    for (let i = 0; i < 5; i++) {\n      standups.push({\n        id: `standup-${w}-${i}`,\n        title: \"Standup\",\n        calendar: \"team\",\n        date: addDays(wk, w * 7 + i),\n        start: t(9),\n        end: t(9, 30),\n        video: true,\n      });\n    }\n  }\n  return [\n    ...standups,\n    { id: \"e1\", title: \"Pricing model review\", calendar: \"me\", date: d(0), start: t(11), end: t(12), location: \"Room Atlas\", people: [\"Jonas Weber\", \"Priya Raman\"] },\n    { id: \"e2\", title: \"Onboarding v3 working session\", calendar: \"product\", date: d(0), start: t(14), end: t(15, 30), video: true, people: [\"Priya Raman\", \"Leo Marchetti\"] },\n    { id: \"e3\", title: \"1:1 Jonas\", calendar: \"me\", date: d(0), start: t(16), end: t(16, 30), video: true, people: [\"Jonas Weber\"] },\n    { id: \"e4\", title: \"Research readout\", calendar: \"team\", date: d(1), start: t(10), end: t(11), location: \"Big room\", people: [\"Ana Sousa\"] },\n    { id: \"e5\", title: \"Lunch with Ellie\", calendar: \"me\", date: d(1), start: t(12, 30), end: t(13, 30), location: \"Canal Café\" },\n    { id: \"e6\", title: \"Interview: Staff Engineer\", calendar: \"me\", date: d(1), start: t(15), end: t(16), video: true, people: [\"Sam Whitfield\"] },\n    { id: \"e7\", title: \"Hiring sync\", calendar: \"team\", date: d(1), start: t(15, 30), end: t(16, 15), people: [\"Ana Sousa\", \"Sam Whitfield\"] },\n    { id: \"e8\", title: \"Incident review: webhooks\", calendar: \"team\", date: d(2), start: t(13), end: t(14), video: true, people: [\"Sam Whitfield\"] },\n    { id: \"e9\", title: \"Board prep\", calendar: \"me\", date: d(2), start: t(16), end: t(17, 30), location: \"Room Atlas\" },\n    { id: \"e10\", title: \"Q4 pricing decision\", calendar: \"me\", date: d(3), start: t(10), end: t(10, 45), video: true, people: [\"Jonas Weber\", \"Priya Raman\"] },\n    { id: \"e11\", title: \"Customer call: Fieldnote\", calendar: \"me\", date: d(3), start: t(11, 30), end: t(12), video: true, people: [\"Noor Haddad\"] },\n    { id: \"e12\", title: \"Design crit\", calendar: \"product\", date: d(3), start: t(14), end: t(15), location: \"Studio\", people: [\"Priya Raman\", \"Leo Marchetti\", \"Ana Sousa\"] },\n    { id: \"e13\", title: \"Release notes review\", calendar: \"launches\", date: d(3), start: t(14, 30), end: t(15), people: [\"Jonas Weber\"] },\n    { id: \"e14\", title: \"Climbing\", calendar: \"me\", date: d(3), start: t(18), end: t(19, 30), location: \"Boulder Hall\" },\n    { id: \"e15\", title: \"Focus: Q4 plan\", calendar: \"me\", date: d(4), start: t(10), end: t(12) },\n    { id: \"e16\", title: \"Starter pricing goes live\", calendar: \"launches\", date: d(4), start: t(15), end: t(15, 30) },\n    { id: \"e17\", title: \"Team drinks\", calendar: \"team\", date: d(4), start: t(17), end: t(18, 30), location: \"The Lantern\" },\n    { id: \"e18\", title: \"Run club\", calendar: \"me\", date: d(5), start: t(9), end: t(10) },\n    { id: \"a1\", title: \"Leo out\", calendar: \"team\", date: d(3), start: 0, end: 0, allDay: true, days: 2 },\n    { id: \"a2\", title: \"Clocks go back\", calendar: \"holidays\", date: d(6), start: 0, end: 0, allDay: true },\n    { id: \"n1\", title: \"Roadmap sync\", calendar: \"product\", date: addDays(wk, 7), start: t(11), end: t(12), video: true },\n    { id: \"n2\", title: \"Lisbon offsite\", calendar: \"team\", date: addDays(wk, 9), start: 0, end: 0, allDay: true, days: 2 },\n    { id: \"p1\", title: \"Quarterly planning\", calendar: \"product\", date: addDays(wk, -5), start: t(13), end: t(16) },\n  ];\n}\n\ninterface Placed {\n  ev: CalendarEvent;\n  col: number;\n  cols: number;\n}\n\nfunction placeDay(events: CalendarEvent[]): Placed[] {\n  const sorted = [...events].sort((a, b) => a.start - b.start || b.end - a.end);\n  const out: Placed[] = [];\n  let cluster: Placed[] = [];\n  let clusterEnd = -1;\n  const flush = () => {\n    const cols = Math.max(1, ...cluster.map((p) => p.col + 1));\n    for (const p of cluster) p.cols = cols;\n    out.push(...cluster);\n    cluster = [];\n  };\n  for (const ev of sorted) {\n    if (ev.start >= clusterEnd && cluster.length) flush();\n    const used = new Set(cluster.filter((p) => p.ev.end > ev.start).map((p) => p.col));\n    let col = 0;\n    while (used.has(col)) col++;\n    cluster.push({ ev, col, cols: 1 });\n    clusterEnd = Math.max(clusterEnd, ev.end);\n  }\n  if (cluster.length) flush();\n  return out;\n}\n\nfunction packAllDay(list: CalendarEvent[], first: string, count: number) {\n  const rows: number[][] = [];\n  return [...list]\n    .sort((a, b) => a.date.localeCompare(b.date) || (b.days ?? 1) - (a.days ?? 1))\n    .map((e) => {\n      const startIdx = Math.max(0, diffDays(e.date, first));\n      const endIdx = Math.min(count - 1, diffDays(addDays(e.date, (e.days ?? 1) - 1), first));\n      let row = rows.findIndex((r) => r.every((c) => c < startIdx || c > endIdx));\n      if (row < 0) row = rows.push([]) - 1;\n      for (let c = startIdx; c <= endIdx; c++) rows[row].push(c);\n      return { e, row, startIdx, endIdx };\n    });\n}\n\nfunction toDate(date: string) {\n  const [y, m, d] = date.split(\"-\").map(Number);\n  return new Date(y, m - 1, d);\n}\nfunction fromDate(d: Date) {\n  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}-${String(d.getDate()).padStart(2, \"0\")}`;\n}\n\nfunction MiniMonth({\n  month,\n  onMonth,\n  selected,\n  today,\n  weekStart,\n  wholeWeek,\n  onPick,\n  busy,\n}: {\n  month: string;\n  onMonth: (m: string) => void;\n  selected: string;\n  today: string;\n  weekStart: string;\n  wholeWeek: boolean;\n  onPick: (d: string) => void;\n  busy: Set<string>;\n}) {\n  const range = wholeWeek\n    ? { from: toDate(weekStart), to: toDate(addDays(weekStart, 6)) }\n    : { from: toDate(selected), to: toDate(selected) };\n  return (\n    <Calendar\n      className=\"mx-auto p-0 [--cell-size:--spacing(8)] sm:[--cell-size:--spacing(8)]\"\n      classNames={{ day_button: \"in-data-outside:text-muted-foreground\", weekday: \"text-muted-foreground\" }}\n      mode=\"range\"\n      modifiers={{ busy: [...busy].filter((d) => d !== today).map(toDate) }}\n      modifiersClassNames={{\n        busy: \"*:before:pointer-events-none *:before:absolute *:before:bottom-1 *:before:start-1/2 *:before:size-[3px] *:before:-translate-x-1/2 *:before:rounded-full *:before:bg-muted-foreground/60 [&[data-selected]:not(.range-middle)>*]:before:bg-primary-foreground/72\",\n      }}\n      month={toDate(month)}\n      onDayClick={(day) => onPick(fromDate(day))}\n      onMonthChange={(m) => onMonth(fromDate(m))}\n      onSelect={() => {}}\n      selected={range}\n      today={toDate(today)}\n      weekStartsOn={1}\n    />\n  );\n}\n\ntype DragState = {\n  id: string;\n  mode: \"move\" | \"resize\" | \"create\";\n  x: number;\n  y: number;\n  start: number;\n  end: number;\n  date: string;\n  moved: boolean;\n  anchorMin: number;\n};\n\ntype ViewMode = \"day\" | \"week\";\n\nexport function CalendarWeek({\n  calendars: initialCalendars = defaultCalendars,\n  events: initialEvents,\n  now = \"2026-10-22T10:40\",\n  className,\n}: CalendarWeekProps) {\n  const today = now.slice(0, 10);\n  const [hh, mm] = now.slice(11, 16).split(\":\").map(Number);\n  const [nowMin, setNowMin] = useState(hh * 60 + mm);\n  const [calendars, setCalendars] = useState(initialCalendars);\n  const [events, setEvents] = useState<CalendarEvent[]>(() => initialEvents ?? buildEvents());\n  const [view, setView] = useState<ViewMode>(\"week\");\n  const [focusDay, setFocusDay] = useState(today);\n  const [month, setMonth] = useState(today.slice(0, 8) + \"01\");\n  const [selectedId, setSelectedId] = useState<string | null>(null);\n  const [editing, setEditing] = useState<string | null>(null);\n  const [drag, setDrag] = useState<DragState | null>(null);\n  const [narrow, setNarrow] = useState(false);\n  const [docked, setDocked] = useState(true);\n  const [toast, setToast] = useState<{ key: number; text: string; undo?: () => void } | null>(null);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const titleRef = useRef<HTMLInputElement>(null);\n  const mainRef = useRef<HTMLElement>(null);\n  const [allDayAt, setAllDayAt] = useState({ left: 12, top: 112 });\n\n  useEffect(() => {\n    const id = window.setInterval(() => setNowMin((m) => Math.min(m + 1, 24 * 60 - 1)), 60000);\n    return () => window.clearInterval(id);\n  }, []);\n\n  useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([e]) => {\n      setNarrow(e.contentRect.width < 672);\n      setDocked(e.contentRect.width >= 896);\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  useLayoutEffect(() => {\n    if (scrollRef.current) scrollRef.current.scrollTop = 8 * HOUR - 12;\n  }, []);\n\n  useEffect(() => {\n    if (!toast) return;\n    const id = window.setTimeout(() => setToast(null), 4500);\n    return () => window.clearTimeout(id);\n  }, [toast]);\n\n  const mode: ViewMode = narrow ? \"day\" : view;\n  const weekStart = startOfWeek(focusDay);\n  const days = mode === \"week\" ? Array.from({ length: 7 }, (_, i) => addDays(weekStart, i)) : [focusDay];\n  const visibleCal = new Set(calendars.filter((c) => c.visible !== false).map((c) => c.id));\n  const calOf = (id: string) => calendars.find((c) => c.id === id) ?? calendars[0];\n  const shown = events.filter((e) => visibleCal.has(e.calendar));\n  const timed = shown.filter((e) => !e.allDay);\n  const allDay = shown.filter((e) => e.allDay && diffDays(addDays(e.date, (e.days ?? 1) - 1), days[0]) >= 0 && diffDays(e.date, days[days.length - 1]) <= 0);\n  const busy = new Set(shown.map((e) => e.date));\n  const selected = events.find((e) => e.id === selectedId) ?? null;\n\n  const patch = (id: string, p: Partial<CalendarEvent>) => setEvents((es) => es.map((e) => (e.id === id ? { ...e, ...p } : e)));\n\n  const goto = (d: string) => {\n    setFocusDay(d);\n    setMonth(d.slice(0, 8) + \"01\");\n  };\n  const step = (dir: number) => goto(addDays(focusDay, dir * (mode === \"week\" ? 7 : 1)));\n\n  const header = () => {\n    const a = parse(days[0]);\n    const b = parse(days[days.length - 1]);\n    if (mode === \"day\" && !narrow) return { main: `${MONTHS[a.getUTCMonth()]} ${a.getUTCDate()}`, sub: DAY_NAMES[weekday(days[0])] };\n    if (a.getUTCMonth() === b.getUTCMonth()) return { main: MONTHS[a.getUTCMonth()], sub: String(a.getUTCFullYear()) };\n    return { main: `${MONTHS[a.getUTCMonth()].slice(0, 3)} – ${MONTHS[b.getUTCMonth()].slice(0, 3)}`, sub: String(b.getUTCFullYear()) };\n  };\n  const head = header();\n\n  const columnWidth = () => (gridRef.current ? gridRef.current.getBoundingClientRect().width / days.length : 1);\n\n  const minuteAt = (clientY: number) => {\n    const r = gridRef.current?.getBoundingClientRect();\n    if (!r) return 0;\n    return Math.max(0, Math.min(24 * 60, (clientY - r.top) / PX));\n  };\n\n  const beginDrag = (e: ReactPointerEvent, ev: CalendarEvent, m: \"move\" | \"resize\") => {\n    if (e.button !== 0) return;\n    e.stopPropagation();\n    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n    setDrag({ id: ev.id, mode: m, x: e.clientX, y: e.clientY, start: ev.start, end: ev.end, date: ev.date, moved: false, anchorMin: 0 });\n  };\n\n  const beginCreate = (e: ReactPointerEvent, date: string) => {\n    if (e.button !== 0) return;\n    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n    const at = Math.floor(minuteAt(e.clientY) / SNAP) * SNAP;\n    const ev: CalendarEvent = { id: `new-${Date.now()}`, title: \"\", calendar: calendars[0]?.id ?? \"me\", date, start: at, end: at + 30 };\n    setEvents((es) => [...es, ev]);\n    setSelectedId(null);\n    setEditing(null);\n    setDrag({ id: ev.id, mode: \"create\", x: e.clientX, y: e.clientY, start: at, end: at + 30, date, moved: false, anchorMin: at });\n  };\n\n  const onPointerMove = (e: ReactPointerEvent) => {\n    if (!drag) return;\n    const dy = e.clientY - drag.y;\n    const dx = e.clientX - drag.x;\n    const moved = drag.moved || Math.abs(dy) > 3 || Math.abs(dx) > 3;\n    if (!moved) return;\n    if (!drag.moved) setDrag({ ...drag, moved: true });\n    const deltaMin = snap(dy / PX);\n    if (drag.mode === \"move\") {\n      const len = drag.end - drag.start;\n      const start = Math.max(0, Math.min(24 * 60 - len, drag.start + deltaMin));\n      const dDay = mode === \"week\" ? Math.round(dx / columnWidth()) : 0;\n      const idx = Math.max(0, Math.min(days.length - 1, diffDays(drag.date, days[0]) + dDay));\n      patch(drag.id, { start, end: start + len, date: days[idx] });\n    } else if (drag.mode === \"resize\") {\n      const end = Math.max(drag.start + SNAP, Math.min(24 * 60, drag.end + deltaMin));\n      patch(drag.id, { end });\n    } else {\n      const at = snap(minuteAt(e.clientY));\n      const a = Math.min(drag.anchorMin, at);\n      const b = Math.max(drag.anchorMin + SNAP, at);\n      patch(drag.id, { start: a, end: Math.max(a + SNAP, b) });\n    }\n  };\n\n  const onPointerUp = () => {\n    if (!drag) return;\n    const d = drag;\n    setDrag(null);\n    if (d.mode === \"create\") {\n      setSelectedId(d.id);\n      setEditing(d.id);\n      requestAnimationFrame(() => titleRef.current?.focus());\n      return;\n    }\n    if (!d.moved) {\n      setSelectedId(d.id);\n      setEditing(null);\n      return;\n    }\n    const ev = events.find((x) => x.id === d.id);\n    if (ev && (ev.start !== d.start || ev.end !== d.end || ev.date !== d.date)) {\n      setSelectedId(d.id);\n      setToast({\n        key: Date.now(),\n        text: `${ev.title || \"Event\"} → ${DOW[weekday(ev.date)]} ${fmtRange(ev.start, ev.end)}`,\n        undo: () => {\n          patch(d.id, { start: d.start, end: d.end, date: d.date });\n          setToast(null);\n          rootRef.current?.focus({ preventScroll: true });\n        },\n      });\n    }\n  };\n\n  const remove = (id: string) => {\n    const ev = events.find((e) => e.id === id);\n    if (!ev) return;\n    setEvents((es) => es.filter((e) => e.id !== id));\n    setSelectedId(null);\n    setEditing(null);\n    if (ev.title) {\n      setToast({\n        key: Date.now(),\n        text: `Deleted “${ev.title}”`,\n        undo: () => {\n          setEvents((es) => [...es, ev]);\n          setToast(null);\n          rootRef.current?.focus({ preventScroll: true });\n        },\n      });\n    }\n    rootRef.current?.focus({ preventScroll: true });\n  };\n\n  const closeEditor = () => {\n    if (editing) {\n      const ev = events.find((e) => e.id === editing);\n      if (ev && !ev.title.trim()) setEvents((es) => es.filter((e) => e.id !== editing));\n    }\n    setEditing(null);\n    setSelectedId(null);\n    rootRef.current?.focus({ preventScroll: true });\n  };\n\n  const newEventNow = () => {\n    const date = mode === \"day\" ? focusDay : days.includes(today) ? today : days[0];\n    const start = Math.ceil((date === today ? nowMin : 9 * 60) / 30) * 30;\n    const ev: CalendarEvent = { id: `new-${Date.now()}`, title: \"\", calendar: calendars[0]?.id ?? \"me\", date, start, end: start + 30 };\n    setEvents((es) => [...es, ev]);\n    setSelectedId(ev.id);\n    setEditing(ev.id);\n    if (scrollRef.current) scrollRef.current.scrollTop = Math.max(0, start * PX - 120);\n    requestAnimationFrame(() => titleRef.current?.focus());\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    const t = e.target as HTMLElement;\n    if (t.tagName === \"INPUT\" || t.tagName === \"TEXTAREA\") return;\n    if (e.metaKey || e.ctrlKey || e.altKey) return;\n    if (e.key === \"Escape\") {\n      if (editing || selectedId) closeEditor();\n      return;\n    }\n    if (selected && !selected.allDay) {\n      const len = selected.end - selected.start;\n      if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n        e.preventDefault();\n        const d = e.key === \"ArrowUp\" ? -SNAP : SNAP;\n        if (e.shiftKey) patch(selected.id, { end: Math.max(selected.start + SNAP, Math.min(1440, selected.end + d)) });\n        else {\n          const start = Math.max(0, Math.min(1440 - len, selected.start + d));\n          patch(selected.id, { start, end: start + len });\n        }\n        return;\n      }\n      if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n        e.preventDefault();\n        const date = addDays(selected.date, e.key === \"ArrowLeft\" ? -1 : 1);\n        patch(selected.id, { date });\n        if (!days.includes(date)) goto(date);\n        return;\n      }\n      if (e.key === \"Backspace\" || e.key === \"Delete\") {\n        e.preventDefault();\n        remove(selected.id);\n        return;\n      }\n      if (e.key === \"Enter\") {\n        e.preventDefault();\n        setEditing(selected.id);\n        requestAnimationFrame(() => titleRef.current?.focus());\n        return;\n      }\n    }\n    const k = e.key.toLowerCase();\n    if (e.key === \"ArrowLeft\" || k === \"k\") step(-1);\n    else if (e.key === \"ArrowRight\" || k === \"j\") step(1);\n    else if (k === \"t\") goto(today);\n    else if (k === \"d\") setView(\"day\");\n    else if (k === \"w\") setView(\"week\");\n    else if (k === \"n\" || k === \"c\") {\n      e.preventDefault();\n      newEventNow();\n    }\n  };\n\n  const panel = selected ? { ev: selected, cal: calOf(selected.calendar), dayIndex: days.indexOf(selected.date) } : null;\n\n  const sidebar = (\n    <div className=\"flex h-full flex-col gap-6 px-3 pt-3 pb-4\">\n      <Button className=\"w-full justify-start transition-[box-shadow,scale] duration-150 ease-out active:scale-[0.97]\" onClick={newEventNow}>\n        <PlusIcon />\n        New event\n        <Kbd className=\"ms-auto bg-primary-foreground/16 text-primary-foreground\">N</Kbd>\n      </Button>\n      <MiniMonth\n        busy={busy}\n        month={month}\n        onMonth={setMonth}\n        onPick={(d) => {\n          setFocusDay(d);\n          if (mode === \"day\" || narrow) setView(\"day\");\n        }}\n        selected={focusDay}\n        today={today}\n        weekStart={weekStart}\n        wholeWeek={mode === \"week\"}\n      />\n      <div>\n        <div className=\"mb-1.5 ps-1.5 font-medium text-muted-foreground text-xs\">Calendars</div>\n        <ul className=\"flex flex-col gap-0.5\">\n          {calendars.map((c) => {\n            const on = c.visible !== false;\n            return (\n              <li key={c.id}>\n                <button\n                  aria-pressed={on}\n                  className=\"flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-lg px-1.5 text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n                  onClick={() => setCalendars((cs) => cs.map((x) => (x.id === c.id ? { ...x, visible: !on } : x)))}\n                  type=\"button\"\n                >\n                  <span\n                    className={cn(\n                      \"flex size-4 shrink-0 items-center justify-center rounded-[calc(var(--radius)*0.5)] border-2 transition-colors duration-150\",\n                      on ? toneCheck[c.tone] : \"border-muted-foreground/40 bg-transparent\",\n                    )}\n                  >\n                    <CheckIcon className={cn(\"size-3 text-white transition-opacity duration-150\", on ? \"opacity-100\" : \"opacity-0\")} strokeWidth={3} />\n                  </span>\n                  <span className={cn(\"truncate\", !on && \"text-muted-foreground\")}>{c.name}</span>\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      </div>\n      <div className=\"mt-auto hidden flex-col gap-1.5 text-muted-foreground text-xs @4xl:flex\">\n        <div className=\"flex items-center gap-1.5\">\n          <Kbd>←</Kbd>\n          <Kbd>→</Kbd>\n          <span>week</span>\n          <Kbd className=\"ms-2\">T</Kbd>\n          <span>today</span>\n        </div>\n        <div className=\"flex items-center gap-1.5\">\n          <Kbd>↑</Kbd>\n          <Kbd>↓</Kbd>\n          <span>move event</span>\n          <Kbd className=\"ms-2\">⇧</Kbd>\n          <span>resize</span>\n        </div>\n      </div>\n    </div>\n  );\n\n  const nowTop = nowMin * PX;\n  const todayIdx = days.indexOf(today);\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\n          \"@container relative isolate flex h-[760px] w-full select-none overflow-hidden bg-sidebar text-foreground text-sm outline-none\",\n          className,\n        )}\n        onKeyDown={onKeyDown}\n        ref={rootRef}\n        tabIndex={-1}\n      >\n        <aside aria-label=\"Calendars\" className=\"hidden w-64 shrink-0 overflow-y-auto @4xl:block\">\n          {sidebar}\n        </aside>\n\n        <main\n          className=\"relative flex min-w-0 flex-1 flex-col overflow-hidden bg-background @4xl:my-2 @4xl:me-2 @4xl:rounded-2xl @4xl:border @4xl:shadow-xs/5\"\n          ref={mainRef}\n        >\n          <header className=\"flex h-14 shrink-0 items-center gap-2 border-b px-3 @lg:px-4\">\n            {docked ? (\n              <h2 className=\"flex h-9 items-center gap-1.5\">\n                <span className=\"font-heading font-semibold text-lg tracking-tight\">{head.main}</span>\n                <span className=\"text-lg text-muted-foreground tabular-nums\">{head.sub}</span>\n              </h2>\n            ) : (\n            <Popover>\n              <PopoverTrigger className=\"-ms-1.5 flex h-9 cursor-pointer items-center gap-1.5 rounded-lg px-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring data-popup-open:bg-accent\">\n                <span className=\"font-heading font-semibold text-lg tracking-tight\">{head.main}</span>\n                <span className=\"text-lg text-muted-foreground tabular-nums\">{head.sub}</span>\n                <ChevronDownIcon className=\"size-4 text-muted-foreground\" />\n              </PopoverTrigger>\n              <PopoverPopup align=\"start\" className=\"w-72\">\n                <div className=\"p-1\">\n                  <MiniMonth busy={busy} month={month} onMonth={setMonth} onPick={(d) => setFocusDay(d)} selected={focusDay} today={today} weekStart={weekStart} wholeWeek={mode === \"week\"} />\n                  <div className=\"mt-3 flex flex-wrap gap-1.5 border-t pt-3\">\n                    {calendars.map((c) => {\n                      const on = c.visible !== false;\n                      return (\n                        <button\n                          aria-pressed={on}\n                          className={cn(\n                            \"flex h-7 cursor-pointer items-center gap-1.5 rounded-full border px-2.5 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                            on ? \"bg-accent\" : \"text-muted-foreground\",\n                          )}\n                          key={c.id}\n                          onClick={() => setCalendars((cs) => cs.map((x) => (x.id === c.id ? { ...x, visible: !on } : x)))}\n                          type=\"button\"\n                        >\n                          <span className={cn(\"size-2 rounded-full\", on ? toneDot[c.tone] : \"bg-muted-foreground/40\")} />\n                          {c.name.split(\" \")[0]}\n                        </button>\n                      );\n                    })}\n                  </div>\n                </div>\n              </PopoverPopup>\n            </Popover>\n            )}\n            <div className=\"ms-auto flex items-center gap-1.5\">\n              <Button onClick={() => goto(today)} size=\"sm\" variant=\"outline\">\n                Today\n              </Button>\n              <div className=\"flex\">\n                <Button aria-label={mode === \"week\" ? \"Previous week\" : \"Previous day\"} onClick={() => step(-1)} size=\"icon-sm\" variant=\"ghost\">\n                  <ChevronLeftIcon />\n                </Button>\n                <Button aria-label={mode === \"week\" ? \"Next week\" : \"Next day\"} onClick={() => step(1)} size=\"icon-sm\" variant=\"ghost\">\n                  <ChevronRightIcon />\n                </Button>\n              </div>\n              <div aria-label=\"View\" className=\"hidden rounded-lg bg-muted p-0.5 @2xl:flex\" role=\"group\">\n                {([\"day\", \"week\"] as const).map((v) => (\n                  <button\n                    aria-pressed={view === v}\n                    className={cn(\n                      \"relative h-7 cursor-pointer rounded-md px-2.5 font-medium text-xs capitalize outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                      view === v ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n                    )}\n                    key={v}\n                    onClick={() => setView(v)}\n                    type=\"button\"\n                  >\n                    {view === v && (\n                      <motion.span\n                        className=\"absolute inset-0 rounded-md bg-background shadow-xs/5 dark:bg-accent\"\n                        layoutId=\"cal-view\"\n                        transition={{ type: \"spring\", stiffness: 520, damping: 42 }}\n                      />\n                    )}\n                    <span className=\"relative flex items-center gap-1.5\">\n                      {v}\n                      <span className=\"text-[10px] text-muted-foreground uppercase\">{v[0]}</span>\n                    </span>\n                  </button>\n                ))}\n              </div>\n              <Button aria-label=\"New event\" className=\"@4xl:hidden\" onClick={newEventNow} size=\"icon-sm\">\n                <PlusIcon />\n              </Button>\n            </div>\n          </header>\n\n          {narrow && (\n            <div className=\"grid shrink-0 grid-cols-7 gap-1 border-b px-2 py-2\">\n              {Array.from({ length: 7 }, (_, i) => addDays(weekStart, i)).map((d) => {\n                const on = d === focusDay;\n                const isToday = d === today;\n                return (\n                  <button\n                    aria-label={`${DOW[weekday(d)]} ${parse(d).getUTCDate()}`}\n                    aria-pressed={on}\n                    className=\"relative flex h-12 cursor-pointer flex-col items-center justify-center gap-0.5 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n                    key={d}\n                    onClick={() => setFocusDay(d)}\n                    type=\"button\"\n                  >\n                    {on && (\n                      <motion.span\n                        className=\"absolute inset-0 rounded-xl bg-accent\"\n                        layoutId=\"cal-strip\"\n                        transition={{ type: \"spring\", stiffness: 520, damping: 42 }}\n                      />\n                    )}\n                    <span className={cn(\"relative text-[11px]\", isToday ? \"font-medium text-destructive-foreground\" : \"text-muted-foreground\")}>\n                      {DOW[weekday(d)].slice(0, 2)}\n                    </span>\n                    <span className={cn(\"relative font-medium tabular-nums\", isToday && \"text-destructive-foreground\")}>{parse(d).getUTCDate()}</span>\n                    {busy.has(d) && <span className=\"absolute bottom-1 size-1 rounded-full bg-muted-foreground/60\" />}\n                  </button>\n                );\n              })}\n            </div>\n          )}\n\n          <div className=\"flex shrink-0 overflow-y-hidden border-b [scrollbar-gutter:stable]\">\n            <div className=\"flex w-14 shrink-0 flex-col items-end pe-2 text-[10px] text-muted-foreground\">\n              {!narrow && (\n                <span className=\"flex h-11 flex-col items-end justify-center leading-tight\">\n                  <span className=\"font-medium text-foreground/80 tabular-nums\">W{isoWeek(days[0])}</span>\n                  <span>CEST</span>\n                </span>\n              )}\n              <span className=\"flex h-8 items-center\">All day</span>\n            </div>\n            <div className=\"min-w-0 flex-1\">\n              {!narrow && (\n                <div className=\"grid\" style={{ gridTemplateColumns: `repeat(${days.length}, minmax(0, 1fr))` }}>\n                  {days.map((d) => {\n                    const isToday = d === today;\n                    return (\n                      <button\n                        className=\"flex h-11 cursor-pointer items-center gap-1.5 border-s ps-2.5 text-left outline-none hover:bg-accent/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\"\n                        key={d}\n                        onClick={() => {\n                          setFocusDay(d);\n                          setView(\"day\");\n                        }}\n                        type=\"button\"\n                      >\n                        <span className={cn(\"text-xs\", isToday ? \"font-medium text-destructive-foreground\" : \"text-muted-foreground\")}>{DOW[weekday(d)]}</span>\n                        <span\n                          className={cn(\n                            \"flex h-6 min-w-6 items-center justify-center rounded-full px-1 font-medium tabular-nums\",\n                            isToday && \"bg-red-600 text-white\",\n                          )}\n                        >\n                          {parse(d).getUTCDate()}\n                        </span>\n                      </button>\n                    );\n                  })}\n                </div>\n              )}\n              <div className=\"relative grid min-h-8 py-1\" style={{ gridTemplateColumns: `repeat(${days.length}, minmax(0, 1fr))` }}>\n                {days.map((d) => (\n                  <div className=\"border-s\" key={d} style={{ gridColumn: \"span 1\", gridRow: \"1 / span 3\" }} />\n                ))}\n                {packAllDay(allDay, days[0], days.length).map(({ e, row, startIdx, endIdx }) => {\n                  const cal = calOf(e.calendar);\n                  return (\n                    <button\n                      className={cn(\n                        \"relative z-10 mx-1 my-px flex h-6 cursor-pointer items-center truncate rounded-md ps-2.5 pe-2 text-left font-medium text-xs outline-none before:absolute before:inset-y-1 before:left-1 before:w-0.5 before:rounded-full focus-visible:ring-2 focus-visible:ring-ring\",\n                        selectedId === e.id ? toneSolid[cal.tone] : toneBlock[cal.tone],\n                      )}\n                      key={e.id}\n                      onClick={(evt) => {\n                        const r = evt.currentTarget.getBoundingClientRect();\n                        const m = mainRef.current?.getBoundingClientRect();\n                        if (m) setAllDayAt({ left: Math.max(12, Math.min(r.left - m.left, m.width - 268)), top: r.bottom - m.top + 6 });\n                        setSelectedId(e.id);\n                        setEditing(null);\n                      }}\n                      style={{ gridColumn: `${startIdx + 1} / ${endIdx + 2}`, gridRow: row + 1 }}\n                      type=\"button\"\n                    >\n                      {e.title}\n                    </button>\n                  );\n                })}\n              </div>\n            </div>\n          </div>\n\n          <div className=\"relative min-h-0 flex-1 overflow-y-auto overflow-x-hidden [scrollbar-width:thin]\" ref={scrollRef}>\n            <div className=\"relative flex\" style={{ height: 24 * HOUR }}>\n              <div aria-hidden className=\"relative w-14 shrink-0\">\n                {Array.from({ length: 23 }, (_, i) => i + 1).map((h) => (\n                  <span\n                    className={cn(\n                      \"absolute right-2 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums transition-opacity\",\n                      todayIdx >= 0 && Math.abs(h * 60 - nowMin) < 24 && \"opacity-0\",\n                    )}\n                    key={h}\n                    style={{ top: h * HOUR }}\n                  >\n                    {fmtTime(h * 60)}\n                  </span>\n                ))}\n                {todayIdx >= 0 && (\n                  <span\n                    className=\"absolute right-1 z-20 -translate-y-1/2 rounded-md bg-red-600 px-1 py-px font-medium text-[10px] text-white tabular-nums\"\n                    style={{ top: nowTop }}\n                  >\n                    {fmtTime(nowMin).replace(\" AM\", \"\").replace(\" PM\", \"\")}\n                  </span>\n                )}\n              </div>\n\n              <div\n                className=\"relative grid min-w-0 flex-1\"\n                onPointerCancel={onPointerUp}\n                onPointerMove={onPointerMove}\n                onPointerUp={onPointerUp}\n                ref={gridRef}\n                style={{ gridTemplateColumns: `repeat(${days.length}, minmax(0, 1fr))` }}\n              >\n                <div aria-hidden className=\"pointer-events-none absolute inset-0\">\n                  {Array.from({ length: 24 }, (_, h) => (\n                    <div className=\"absolute inset-x-0 border-t border-border/70\" key={h} style={{ top: h * HOUR }} />\n                  ))}\n                  {Array.from({ length: 24 }, (_, h) => (\n                    <div className=\"absolute inset-x-0 border-t border-border/30 border-dashed\" key={`h${h}`} style={{ top: h * HOUR + HOUR / 2 }} />\n                  ))}\n                  {todayIdx >= 0 && nowMin <= 24 * 60 && <div className=\"absolute inset-x-0 h-px -translate-y-1/2 bg-destructive/25\" style={{ top: nowTop }} />}\n                </div>\n\n                {days.map((d) => {\n                  const placed = placeDay(timed.filter((e) => e.date === d));\n                  const isToday = d === today;\n                  return (\n                    <div\n                      aria-label={`${DOW[weekday(d)]} ${parse(d).getUTCDate()}, drag to create an event`}\n                      className={cn(\"relative border-s\", weekday(d) >= 5 && \"bg-muted/40\")}\n                      key={d}\n                      onPointerDown={(e) => beginCreate(e, d)}\n                      role=\"group\"\n                    >\n                      {isToday && nowMin <= 24 * 60 && (\n                        <div aria-hidden className=\"pointer-events-none absolute inset-x-0 z-20\" style={{ top: nowTop }}>\n                          <div className=\"absolute inset-x-0 h-0.5 -translate-y-1/2 bg-destructive\" />\n                          <div className=\"absolute -left-1.5 size-3 -translate-y-1/2 rounded-full bg-destructive ring-2 ring-background\" />\n                        </div>\n                      )}\n                      <AnimatePresence initial={false}>\n                        {placed.map(({ ev, col, cols }) => {\n                          const cal = calOf(ev.calendar);\n                          const isSel = selectedId === ev.id;\n                          const isDrag = drag?.id === ev.id && (drag.moved || drag.mode === \"create\");\n                          const height = Math.max((ev.end - ev.start) * PX, 18);\n                          const short = height < 40;\n                          const past = d < today || (d === today && ev.end <= nowMin);\n                          const faded = past && !isSel && !isDrag;\n                          return (\n                            <motion.div\n                              animate={{ opacity: 1, scale: 1, y: ev.start * PX }}\n                              aria-label={`${ev.title || \"New event\"}, ${fmtRange(ev.start, ev.end)}`}\n                              className={cn(\n                                \"group/ev @container absolute top-0 z-10 cursor-grab touch-none overflow-hidden rounded-md bg-clip-padding text-left outline-none before:absolute before:inset-y-1 before:left-1 before:w-0.5 before:rounded-full focus-visible:ring-2 focus-visible:ring-ring\",\n                                isSel || isDrag ? toneSolid[cal.tone] : toneBlock[cal.tone],\n                                isDrag && \"z-30 cursor-grabbing shadow-lg/20\",\n                                faded && \"[&>div]:opacity-70 before:opacity-60\",\n                                cols > 1 && \"ring-1 ring-background\",\n                              )}\n                              exit={{ opacity: 0, scale: 0.96 }}\n                              initial={{ opacity: 0, scale: 0.96, y: ev.start * PX }}\n                              key={ev.id}\n                              onDoubleClick={() => {\n                                setSelectedId(ev.id);\n                                setEditing(ev.id);\n                                requestAnimationFrame(() => titleRef.current?.focus());\n                              }}\n                              onKeyDown={(e) => {\n                                if (e.key === \" \") {\n                                  e.preventDefault();\n                                  setSelectedId(ev.id);\n                                }\n                              }}\n                              onPointerDown={(e) => beginDrag(e, ev, \"move\")}\n                              role=\"button\"\n                              style={{\n                                height,\n                                left: `calc(${(col / cols) * 100}% + 2px)`,\n                                width: `calc(${(col === cols - 1 ? 1 / cols : Math.min(1 - col / cols, (mode === \"week\" ? 1.7 : 1) / cols)) * 100}% - 6px)`,\n                                zIndex: isDrag ? 30 : 10 + col,\n                              }}\n                              tabIndex={0}\n                              onFocus={() => setSelectedId(ev.id)}\n                              transition={isDrag ? { duration: 0 } : { y: settle, opacity: { duration: 0.15 }, scale: { duration: 0.15 } }}\n                            >\n                              <div className={cn(\"flex h-full flex-col ps-3 pe-1.5\", short ? \"flex-row items-center gap-1.5 py-0\" : \"py-1\")}>\n                                <span className={cn(\"truncate font-medium text-xs leading-4\", !ev.title && \"italic\", !ev.title && !faded && \"opacity-75\")}>\n                                  {ev.title || \"New event\"}\n                                </span>\n                                <span className={cn(\"truncate text-[11px] tabular-nums leading-4\", !faded && \"opacity-75\", short && \"hidden shrink-0 @[8rem]:inline\")}>\n                                  {short ? fmtTime(ev.start) : fmtRange(ev.start, ev.end)}\n                                </span>\n                                {!short && height > 64 && ev.location && (\n                                  <span className={cn(\"mt-0.5 flex items-center gap-1 truncate text-[11px] leading-4\", !faded && \"opacity-75\")}>\n                                    <MapPinIcon className=\"size-3 shrink-0\" />\n                                    {ev.location}\n                                  </span>\n                                )}\n                              </div>\n                              {isDrag && height >= 40 && (\n                                <span className=\"pointer-events-none absolute right-1.5 bottom-1.5 rounded bg-black/20 px-1 font-medium text-[10px] tabular-nums\">\n                                  {fmtDuration(ev.end - ev.start)}\n                                </span>\n                              )}\n                              <span\n                                aria-hidden\n                                className=\"absolute inset-x-0 bottom-0 h-2.5 cursor-ns-resize\"\n                                onPointerDown={(e) => beginDrag(e, ev, \"resize\")}\n                              >\n                                <span className=\"absolute bottom-0.5 left-1/2 h-0.5 w-5 -translate-x-1/2 rounded-full bg-current opacity-0 transition-opacity group-hover/ev:opacity-40\" />\n                              </span>\n                            </motion.div>\n                          );\n                        })}\n                      </AnimatePresence>\n                    </div>\n                  );\n                })}\n\n                <AnimatePresence>\n                  {panel && !drag && panel.dayIndex >= 0 && !panel.ev.allDay && (\n                    <EventCard\n                      calendars={calendars}\n                      cols={days.length}\n                      dayIndex={panel.dayIndex}\n                      editing={editing === panel.ev.id}\n                      ev={panel.ev}\n                      key={panel.ev.id}\n                      onCalendar={(id) => patch(panel.ev.id, { calendar: id })}\n                      onClose={closeEditor}\n                      onDelete={() => remove(panel.ev.id)}\n                      onEdit={() => {\n                        setEditing(panel.ev.id);\n                        requestAnimationFrame(() => titleRef.current?.focus());\n                      }}\n                      onSave={() => {\n                        if (!panel.ev.title.trim()) patch(panel.ev.id, { title: \"Busy\" });\n                        setEditing(null);\n                        setToast({ key: Date.now(), text: `Saved for ${DOW[weekday(panel.ev.date)]} ${fmtRange(panel.ev.start, panel.ev.end)}` });\n                        rootRef.current?.focus({ preventScroll: true });\n                      }}\n                      onTitle={(title) => patch(panel.ev.id, { title })}\n                      scrollRef={scrollRef}\n                      titleRef={titleRef}\n                    />\n                  )}\n                </AnimatePresence>\n              </div>\n            </div>\n          </div>\n\n          <AnimatePresence>\n            {selected?.allDay && (\n              <motion.div\n                animate={{ opacity: 1, scale: 1 }}\n                className=\"absolute z-40 w-64 origin-top-left rounded-xl border bg-popover p-3 shadow-lg/10\"\n                exit={{ opacity: 0, scale: 0.97 }}\n                initial={{ opacity: 0, scale: 0.97 }}\n                style={allDayAt}\n                transition={{ duration: 0.16, ease }}\n              >\n                <div className=\"flex items-start gap-2\">\n                  <span className={cn(\"mt-1.5 size-2 shrink-0 rounded-full\", toneDot[calOf(selected.calendar).tone])} />\n                  <div className=\"min-w-0 flex-1\">\n                    <div className=\"font-medium\">{selected.title}</div>\n                    <div className=\"text-muted-foreground text-xs\">\n                      All day{selected.days && selected.days > 1 ? ` · ${selected.days} days` : \"\"} · {calOf(selected.calendar).name}\n                    </div>\n                  </div>\n                  <Button aria-label=\"Close\" onClick={closeEditor} size=\"icon-xs\" variant=\"ghost\">\n                    <XIcon />\n                  </Button>\n                </div>\n              </motion.div>\n            )}\n          </AnimatePresence>\n\n          <div aria-live=\"polite\" className=\"pointer-events-none absolute inset-x-0 bottom-4 z-40 flex justify-center px-4 @2xl:justify-start @2xl:ps-[4.5rem]\">\n            <AnimatePresence mode=\"popLayout\">\n              {toast && (\n                <motion.div\n                  animate={{ opacity: 1, y: 0, scale: 1 }}\n                  className=\"pointer-events-auto flex h-10 max-w-full items-center gap-3 rounded-full border bg-popover ps-4 pe-1.5 shadow-lg/10\"\n                  exit={{ opacity: 0, y: 6, scale: 0.98 }}\n                  initial={{ opacity: 0, y: 8, scale: 0.98 }}\n                  key={toast.key}\n                  transition={{ duration: 0.2, ease }}\n                >\n                  <span className=\"truncate text-sm tabular-nums\">{toast.text}</span>\n                  {toast.undo ? (\n                    <Button className=\"rounded-full\" onClick={toast.undo} size=\"xs\" variant=\"secondary\">\n                      Undo\n                    </Button>\n                  ) : (\n                    <span className=\"w-1\" />\n                  )}\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n        </main>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction EventCard({\n  ev,\n  calendars,\n  dayIndex,\n  cols,\n  editing,\n  titleRef,\n  scrollRef,\n  onTitle,\n  onCalendar,\n  onSave,\n  onClose,\n  onDelete,\n  onEdit,\n}: {\n  ev: CalendarEvent;\n  calendars: CalendarSource[];\n  dayIndex: number;\n  cols: number;\n  editing: boolean;\n  titleRef: RefObject<HTMLInputElement | null>;\n  scrollRef: RefObject<HTMLDivElement | null>;\n  onTitle: (t: string) => void;\n  onCalendar: (id: string) => void;\n  onSave: () => void;\n  onClose: () => void;\n  onDelete: () => void;\n  onEdit: () => void;\n}) {\n  const cal = calendars.find((c) => c.id === ev.calendar) ?? calendars[0];\n  const cardRef = useRef<HTMLDivElement>(null);\n  useLayoutEffect(() => {\n    const card = cardRef.current;\n    const box = scrollRef.current;\n    if (!card || !box) return;\n    const top = card.offsetTop;\n    const bottom = top + card.offsetHeight;\n    if (bottom > box.scrollTop + box.clientHeight - 12) box.scrollTo({ top: bottom - box.clientHeight + 12, behavior: \"smooth\" });\n    else if (top < box.scrollTop + 8) box.scrollTo({ top: top - 8, behavior: \"smooth\" });\n  }, [scrollRef, editing]);\n  const toRight = cols === 1 ? false : dayIndex < cols - 2;\n  const single = cols === 1;\n  const top = Math.max(4, ev.start * PX - 8);\n  const style = single\n    ? { top: ev.end * PX + 8, right: 12, width: \"min(22rem, calc(100% - 24px))\" }\n    : toRight\n      ? { top, left: `calc(${((dayIndex + 1) / cols) * 100}% + 6px)` }\n      : { top, right: `calc(${((cols - dayIndex) / cols) * 100}% + 6px)` };\n  return (\n    <motion.div\n      animate={{ opacity: 1, scale: 1 }}\n      className={cn(\n        \"absolute z-40 w-72 cursor-default select-text rounded-xl border bg-popover text-popover-foreground shadow-lg/10\",\n        single ? \"origin-top\" : toRight ? \"origin-top-left\" : \"origin-top-right\",\n      )}\n      exit={{ opacity: 0, scale: 0.97 }}\n      initial={{ opacity: 0, scale: 0.97 }}\n      onPointerDown={(e) => e.stopPropagation()}\n      ref={cardRef}\n      role=\"dialog\"\n      aria-label={editing ? \"Edit event\" : ev.title}\n      style={style}\n      transition={{ duration: 0.16, ease }}\n    >\n      <div className=\"flex items-start gap-2 p-3 pb-2\">\n        <span className={cn(\"mt-1.5 size-2.5 shrink-0 rounded-full\", toneDot[cal.tone])} />\n        {editing ? (\n          <input\n            aria-label=\"Event title\"\n            className=\"min-w-0 flex-1 bg-transparent font-medium text-sm outline-none placeholder:text-muted-foreground/70\"\n            onChange={(e) => onTitle(e.target.value)}\n            onKeyDown={(e) => {\n              if (e.key === \"Enter\") onSave();\n              if (e.key === \"Escape\") onClose();\n            }}\n            placeholder=\"Add a title\"\n            ref={titleRef}\n            value={ev.title}\n          />\n        ) : (\n          <button className=\"min-w-0 flex-1 cursor-text text-left font-medium leading-5 outline-none\" onClick={onEdit} type=\"button\">\n            {ev.title}\n          </button>\n        )}\n        <Button aria-label=\"Close\" className=\"-me-1 -mt-0.5\" onClick={onClose} size=\"icon-xs\" variant=\"ghost\">\n          <XIcon />\n        </Button>\n      </div>\n      <div className=\"flex flex-col gap-1.5 px-3 pb-3 text-muted-foreground text-xs\">\n        <div className=\"flex items-center gap-2\">\n          <ClockIcon className=\"size-3.5 shrink-0\" />\n          <span className=\"tabular-nums\">\n            {DOW[weekday(ev.date)]} {MONTHS[parse(ev.date).getUTCMonth()].slice(0, 3)} {parse(ev.date).getUTCDate()} · {fmtRange(ev.start, ev.end)}\n          </span>\n          <span className=\"ms-auto tabular-nums\">{fmtDuration(ev.end - ev.start)}</span>\n        </div>\n        {ev.location && (\n          <div className=\"flex items-center gap-2\">\n            <MapPinIcon className=\"size-3.5 shrink-0\" />\n            {ev.location}\n          </div>\n        )}\n        {ev.video && (\n          <div className=\"flex items-center gap-2\">\n            <VideoIcon className=\"size-3.5 shrink-0\" />\n            <span className=\"text-info-foreground\">meet.kestrel.dev/{ev.id}</span>\n          </div>\n        )}\n        {ev.people?.length ? (\n          <div className=\"flex items-start gap-2\">\n            <UsersIcon className=\"mt-px size-3.5 shrink-0\" />\n            <span className=\"text-pretty\">{ev.people.join(\", \")}</span>\n          </div>\n        ) : null}\n        <div className=\"flex items-center gap-2\">\n          <CalendarDaysIcon className=\"size-3.5 shrink-0\" />\n          {editing ? (\n            <div className=\"flex flex-wrap gap-1\">\n              {calendars\n                .filter((c) => c.id !== \"holidays\")\n                .map((c) => (\n                  <button\n                    aria-pressed={c.id === ev.calendar}\n                    className={cn(\n                      \"flex h-6 cursor-pointer items-center gap-1 rounded-full border px-2 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                      c.id === ev.calendar ? \"border-foreground/20 bg-accent text-foreground\" : \"hover:text-foreground\",\n                    )}\n                    key={c.id}\n                    onClick={() => onCalendar(c.id)}\n                    type=\"button\"\n                  >\n                    <span className={cn(\"size-1.5 rounded-full\", toneDot[c.tone])} />\n                    {c.name.split(\" \")[0]}\n                  </button>\n                ))}\n            </div>\n          ) : (\n            cal.name\n          )}\n        </div>\n      </div>\n      <div className=\"flex items-center gap-1.5 border-t px-2 py-2\">\n        {editing ? (\n          <>\n            <Button className=\"transition-[box-shadow,scale] duration-150 ease-out active:scale-[0.97]\" onClick={onSave} size=\"xs\">\n              Save\n            </Button>\n            <span className=\"text-muted-foreground text-xs\">\n              <Kbd className=\"h-4 text-[10px]\">↵</Kbd>\n            </span>\n          </>\n        ) : (\n          <span className=\"flex items-center gap-1 ps-1 text-muted-foreground text-xs\">\n            <Kbd className=\"h-4 text-[10px]\">↑↓</Kbd> move\n            <Kbd className=\"ms-1 h-4 text-[10px]\">⇧↑↓</Kbd> resize\n          </span>\n        )}\n        <Button aria-label=\"Delete event\" className=\"ms-auto\" onClick={onDelete} size=\"icon-xs\" variant=\"ghost\">\n          <Trash2Icon />\n        </Button>\n      </div>\n    </motion.div>\n  );\n}\n"
    }
  ]
}