{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"flight-seat-map","type":"registry:block","title":"Flight Seat Map","description":"3D aircraft cabin for picking seats on a booking: the floor tips away like a view down the aisle, every seat stands with a seatback, headrest, screen and tray, and taken seats show heads over the seatbacks. Rows, aisles, exit rows and skipped rows come from a layout prop, and a passenger's head pops up over the seat they pick while it reclines. Arrow keys move across the grid, and a summary totals the seat prices.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":["https://beui.dev/r/theme.json"],"docs":"Flight Seat Map: usage, props and types at https://beui.dev/components/blocks/flight-seat-map.md It uses beUI's theme tokens, added with this install.","files":[{"path":"components/motion/flight-seat-map.tsx","type":"registry:component","target":"@components/motion/flight-seat-map.tsx","content":"\"use client\";\n// beui.dev/components/blocks/flight-seat-map\n\nimport { X } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useInView,\n  useReducedMotion,\n  useSpring,\n} from \"motion/react\";\nimport {\n  type CSSProperties,\n  type KeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_PANEL, SPRING_SWAP } from \"@/lib/ease\";\nimport { useControllable } from \"@/lib/hooks/use-controllable\";\nimport { useLocale, useMessages } from \"@/lib/i18n\";\nimport { useSound } from \"@/lib/sound\";\nimport { buzzSound } from \"@/lib/sounds/buzz\";\nimport { dismissSound } from \"@/lib/sounds/dismiss\";\nimport { popSound } from \"@/lib/sounds/pop\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { cn } from \"@/lib/utils\";\n\nexport const flightSeatMapMessages = {\n  map: \"Seat map\",\n  row: \"Row\",\n  aisleColumn: \"Aisle\",\n  seat: \"Seat {seat}\",\n  window: \"Window\",\n  middle: \"Middle\",\n  aisle: \"Aisle\",\n  standard: \"Standard\",\n  \"extra-legroom\": \"Extra legroom\",\n  premium: \"Premium\",\n  available: \"Available\",\n  taken: \"Taken\",\n  legend: \"Seat types\",\n  selectedFor: \"selected for {name}\",\n  included: \"Included\",\n  passengers: \"Passengers\",\n  noSeat: \"No seat yet\",\n  total: \"Total\",\n  selected: \"Selected\",\n  clear: \"Remove seat for {name}\",\n  announce: \"Seat {seat} selected for {name}\",\n  announceCleared: \"Seat removed for {name}\",\n  hint: \"Pick a seat for {name}\",\n};\n\nexport type FlightSeatMapMessages = typeof flightSeatMapMessages;\n\n/** How a seat is sold: a plain seat, one with more room in front, or a premium cabin seat. */\nexport type SeatType = \"standard\" | \"extra-legroom\" | \"premium\";\n\n/** A run of rows that share a seat type and price. */\nexport interface SeatSection {\n  /** First row number in the section. */\n  from: number;\n  /** Last row number in the section, inclusive. */\n  to: number;\n  /** Seat type for every seat in these rows. Default: \"standard\" */\n  type?: SeatType;\n  /** Price of each seat in these rows, in the `currency` unit. Leave out or pass 0 for seats included in the fare. */\n  price?: number;\n}\n\n/** The cabin's shape: which seat letters sit where, and which rows exist. */\nexport interface SeatMapLayout {\n  /** Seat letters from left to right; an empty string marks an aisle, e.g. [\"A\", \"B\", \"C\", \"\", \"D\", \"E\", \"F\"]. */\n  columns: string[];\n  /** Row ranges from front to back. Rows not covered by a section are not drawn. */\n  sections: SeatSection[];\n  /** Rows with an emergency exit beside them, marked in green at both edges of the cabin floor. */\n  exitRows?: number[];\n  /** Row numbers the airline skips, such as 13. */\n  skipRows?: number[];\n}\n\n/** Someone travelling on the booking who needs a seat. */\nexport interface SeatPassenger {\n  /** Stable id, used as the key in the selection map. */\n  id: string;\n  /** Name shown in the switcher, the summary and seat labels. */\n  name: string;\n}\n\n/** Passenger id to seat id (such as \"12A\"), or null for a passenger without a seat. */\nexport type SeatSelection = Record<string, string | null>;\n\nexport interface FlightSeatMapProps {\n  /** The cabin layout: seat columns, aisles, sections, exit rows and skipped rows. */\n  layout: SeatMapLayout;\n  /** Everyone who needs a seat. One passenger makes it a single-seat picker. */\n  passengers: SeatPassenger[];\n  /** Seat ids that are already taken, such as [\"3C\", \"12A\"]. */\n  taken?: string[];\n  /** Selected seats, for controlled use. */\n  value?: SeatSelection;\n  /** Selected seats at first, when uncontrolled. Default: {} */\n  defaultValue?: SeatSelection;\n  /** Called with the whole selection whenever a passenger's seat changes. */\n  onChange?: (value: SeatSelection) => void;\n  /** ISO 4217 currency code for seat prices. Default: \"USD\" */\n  currency?: string;\n  /** How far the cabin floor tips away from the viewer, in degrees. 0 draws it flat from above. Default: 42 */\n  tilt?: number;\n  /** Play a pop when a head lands in a seat, a flick when a seat is given up, a click when switching passengers and a buzz on a taken seat. Off by default; a `SoundProvider` can mute it app-wide. Default: false */\n  sound?: boolean;\n  /** Override any built-in string. */\n  labels?: Partial<FlightSeatMapMessages>;\n  className?: string;\n}\n\ntype Seat = {\n  id: string;\n  row: number;\n  letter: string;\n  rowIndex: number;\n  col: number;\n  type: SeatType;\n  price: number;\n  position: \"window\" | \"middle\" | \"aisle\";\n};\n\ntype Row = {\n  row: number;\n  type: SeatType;\n  exit: boolean;\n  sectionStart: boolean;\n  seats: (Seat | null)[];\n};\n\nfunction buildCabin(layout: SeatMapLayout) {\n  const { columns } = layout;\n  const skip = new Set(layout.skipRows);\n  const exits = new Set(layout.exitRows);\n  const seatCols = columns.flatMap((c, i) => (c ? [i] : []));\n  const first = seatCols[0];\n  const last = seatCols[seatCols.length - 1];\n  const rows: Row[] = [];\n  const seats = new Map<string, Seat>();\n  for (const section of layout.sections) {\n    const type = section.type ?? \"standard\";\n    for (let n = section.from; n <= section.to; n++) {\n      if (skip.has(n)) continue;\n      const rowIndex = rows.length;\n      const cells = columns.map((letter, i) => {\n        if (!letter) return null;\n        const position =\n          i === first || i === last\n            ? \"window\"\n            : columns[i - 1] === \"\" || columns[i + 1] === \"\"\n              ? \"aisle\"\n              : \"middle\";\n        const seat: Seat = {\n          id: `${n}${letter}`,\n          row: n,\n          letter,\n          rowIndex,\n          col: seatCols.indexOf(i),\n          type,\n          price: section.price ?? 0,\n          position,\n        };\n        seats.set(seat.id, seat);\n        return seat;\n      });\n      rows.push({\n        row: n,\n        type,\n        exit: exits.has(n),\n        sectionStart: n === section.from && rowIndex > 0,\n        seats: cells,\n      });\n    }\n  }\n  const grid = rows.map((r) => r.seats.filter((s): s is Seat => s !== null));\n  return { rows, seats, grid };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Geometry (px). The cabin is laid out flat, then tipped back in 3D.         */\n/* -------------------------------------------------------------------------- */\n\n/** Seat footprint on the floor: width across the cabin, depth along it. */\nconst SEAT_W = 58;\nconst SEAT_D = 52;\n/** Seatback height, and how far a head peeks over it. */\nconst BACK_H = 46;\nconst PEEK = 19;\nconst HEAD = 25;\nconst AISLE_W = 42;\n/** Floor margin between the seats and the cabin's edge. */\nconst PAD = 30;\n/** How far the rounding at each end of the cabin reaches along it. */\nconst END = 110;\n/** Camera distance for the stage's perspective. */\nconst PERSPECTIVE = 2400;\n/** Space between rows: more in front of extra legroom rows, which is the point of them. */\nconst PITCH: Record<SeatType, number> = { standard: 10, \"extra-legroom\": 26, premium: 16 };\n\n/** The cabin settling into its tilt on entry: a heavy, unhurried, critically\n * damped glide, slower than any UI spring because it moves the whole scene. */\nconst CABIN_SETTLE = { stiffness: 90, damping: 19, mass: 1 };\n\n/** Hair colours for travellers already seated, picked per seat so the cabin looks lived in. */\nconst HAIR = [\"#2f2a26\", \"#5b4030\", \"#a7804f\", \"#8f8f8f\", \"#1f1f1f\", \"#6e3b2a\"];\n\nfunction hash(value: string) {\n  let h = 0;\n  for (let i = 0; i < value.length; i++) h = (h * 31 + value.charCodeAt(i)) | 0;\n  return Math.abs(h);\n}\n\nfunction initials(name: string) {\n  const parts = name.trim().split(/\\s+/);\n  return ((parts[0]?.[0] ?? \"\") + (parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? \"\") : \"\")).toUpperCase();\n}\n\n/** Seat fabrics, as CSS colours built from the theme so both modes stay in key. */\nconst FABRIC: Record<SeatType | \"taken\" | \"picked\", string> = {\n  standard: \"color-mix(in oklab, var(--color-foreground) 22%, var(--color-background))\",\n  \"extra-legroom\": \"color-mix(in oklab, var(--color-success) 55%, var(--color-background))\",\n  premium: \"color-mix(in oklab, var(--color-warning) 62%, var(--color-background))\",\n  taken: \"color-mix(in oklab, var(--color-foreground) 11%, var(--color-background))\",\n  picked: \"var(--color-primary)\",\n};\n\nconst NAV_KEYS = new Set([\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\", \"Home\", \"End\", \"PageUp\", \"PageDown\"]);\n\n/** The seat a navigation key lands on from `at`, or undefined at an edge. */\nfunction stepSeat(grid: Seat[][], at: Seat, key: string, ctrlKey: boolean) {\n  const row = grid[at.rowIndex];\n  // Up and down keep the seat letter when the next row has it, else the\n  // nearest column, so cabins with narrower rows still step cleanly.\n  const sameColumn = (r: Seat[] | undefined) =>\n    r?.find((s) => s.letter === at.letter) ??\n    r?.reduce<Seat | undefined>(\n      (best, s) => (!best || Math.abs(s.col - at.col) < Math.abs(best.col - at.col) ? s : best),\n      undefined,\n    );\n  switch (key) {\n    case \"ArrowLeft\":\n      return row[row.indexOf(at) - 1];\n    case \"ArrowRight\":\n      return row[row.indexOf(at) + 1];\n    case \"ArrowUp\":\n      return sameColumn(grid[at.rowIndex - 1]);\n    case \"ArrowDown\":\n      return sameColumn(grid[at.rowIndex + 1]);\n    case \"Home\":\n      return ctrlKey ? grid[0]?.[0] : row[0];\n    case \"End\":\n      return ctrlKey ? grid[grid.length - 1]?.at(-1) : row.at(-1);\n    case \"PageUp\":\n      return sameColumn(grid[Math.max(at.rowIndex - 5, 0)]);\n    case \"PageDown\":\n      return sameColumn(grid[Math.min(at.rowIndex + 5, grid.length - 1)]);\n    default:\n      return undefined;\n  }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Scenery                                                                    */\n/* -------------------------------------------------------------------------- */\n\n\n\n/** An emergency exit beside a row, marked on the floor at the cabin's edge. */\nfunction ExitMark({ side, offset }: { side: \"left\" | \"right\"; offset: number }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"absolute w-[6px] rounded-full bg-success/80 shadow-[0_0_10px_color-mix(in_oklab,var(--color-success)_60%,transparent)]\"\n      style={{ top: offset + 4, height: SEAT_D - 8, [side]: -PAD + 10 }}\n    />\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Seat                                                                       */\n/* -------------------------------------------------------------------------- */\n\ntype SeatState = \"available\" | \"taken\" | \"mine\" | \"other\";\n\ninterface SeatViewProps {\n  seat: Seat;\n  state: SeatState;\n  holder?: string;\n  label: string;\n  tip: ReactNode;\n  tabIndex: number;\n  risen: boolean;\n  introDelay: number | null;\n  reduce: boolean;\n  onPick: () => void;\n  onFocus: () => void;\n}\n\n/** Skin tones for the ears of travellers already seated. */\nconst SKIN = [\"#e3b48f\", \"#c68d64\", \"#8d5a3b\", \"#f0c9a8\", \"#5f3a26\"];\n\n/** A traveller already seated, seen from behind: hair and a little of each ear. */\nfunction StrangerHead({ seed }: { seed: number }) {\n  const hair = HAIR[seed % HAIR.length];\n  const skin = SKIN[(seed >> 3) % SKIN.length];\n  return (\n    <span className=\"absolute left-1/2 top-0 block -translate-x-1/2\" style={{ width: HEAD + 6, height: HEAD }}>\n      <span className=\"absolute left-0 top-[44%] block size-[7px] rounded-full\" style={{ background: skin }} />\n      <span className=\"absolute right-0 top-[44%] block size-[7px] rounded-full\" style={{ background: skin }} />\n      <span\n        className=\"absolute inset-x-[3px] inset-y-0 block rounded-[46%_46%_42%_42%]\"\n        style={{\n          background: `radial-gradient(circle at 50% 28%, color-mix(in oklab, ${hair} 72%, white), ${hair} 62%, color-mix(in oklab, ${hair} 80%, black))`,\n        }}\n      />\n    </span>\n  );\n}\n\n/**\n * The seatback seen from behind. The upholstered backrest, in the seat's\n * colour, rises above a moulded shell and ends in a winged headrest with its\n * cover. The shell carries the seatback screen, a stowed tray table with its\n * latch and the seat pocket.\n */\nfunction SeatBackShell({ fabric, premium, lit, uid }: { fabric: string; premium: boolean; lit: boolean; uid: string }) {\n  const w = SEAT_W - 2;\n  const h = BACK_H;\n  const mid = w / 2;\n  // Upholstered backrest: slightly wider than the shell, so its colour shows\n  // round the top and down both sides.\n  const backrest = `M3.5 ${h} L2 13 C2 4.5 7.5 1 15 1 L${w - 15} 1 C${w - 7.5} 1 ${w - 2} 4.5 ${w - 2} 13 L${w - 3.5} ${h} Z`;\n  // Plastic shell, starting under the headrest.\n  const shell = `M6 ${h} L5 18 C5 14.5 7.5 13 11 13 L${w - 11} 13 C${w - 7.5} 13 ${w - 5} 14.5 ${w - 5} 18 L${w - 6} ${h} Z`;\n  // Headrest with wings that fold forward at each side.\n  const headrest = `M${mid - 19} 4.5 C${mid - 19} 2.8 ${mid - 17.5} 2 ${mid - 15} 2 L${mid + 15} 2 C${mid + 17.5} 2 ${mid + 19} 2.8 ${mid + 19} 4.5 L${mid + 19} 9.5 C${mid + 19} 11.5 ${mid + 17.5} 12 ${mid + 15.5} 11.5 L${mid + 12} 10.5 L${mid - 12} 10.5 L${mid - 15.5} 11.5 C${mid - 17.5} 12 ${mid - 19} 11.5 ${mid - 19} 9.5 Z`;\n  const plastic = `color-mix(in oklab, ${fabric} 38%, var(--color-background))`;\n  return (\n    <svg aria-hidden=\"true\" width={w} height={h} viewBox={`0 0 ${w} ${h}`} className=\"block overflow-visible\">\n      <defs>\n        <linearGradient id={`${uid}-fabric`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={`color-mix(in oklab, ${fabric} 75%, white)`} />\n          <stop offset=\"0.3\" stopColor={fabric} />\n          <stop offset=\"1\" stopColor={`color-mix(in oklab, ${fabric} 62%, black)`} />\n        </linearGradient>\n        <linearGradient id={`${uid}-shell`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={`color-mix(in oklab, ${plastic} 86%, white)`} />\n          <stop offset=\"1\" stopColor={`color-mix(in oklab, ${plastic} 78%, black)`} />\n        </linearGradient>\n        <linearGradient id={`${uid}-side`} x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\n          <stop offset=\"0\" stopColor=\"black\" stopOpacity=\"0.3\" />\n          <stop offset=\"0.14\" stopColor=\"black\" stopOpacity=\"0\" />\n          <stop offset=\"0.86\" stopColor=\"black\" stopOpacity=\"0\" />\n          <stop offset=\"1\" stopColor=\"black\" stopOpacity=\"0.3\" />\n        </linearGradient>\n      </defs>\n      <path d={backrest} fill={`url(#${uid}-fabric)`} />\n      <path d={backrest} fill={`url(#${uid}-side)`} />\n      {/* Light catching the top of the backrest. */}\n      <path\n        d={`M4.5 12 C4.5 5.5 9 3 15 3 L${w - 15} 3 C${w - 9} 3 ${w - 4.5} 5.5 ${w - 4.5} 12`}\n        fill=\"none\"\n        stroke=\"white\"\n        strokeOpacity=\"0.4\"\n      />\n      {/* Headrest, its stitched edge and its cover. */}\n      <path d={headrest} fill={`color-mix(in oklab, ${fabric} 88%, white)`} stroke=\"black\" strokeOpacity=\"0.18\" strokeWidth={0.75} />\n      <rect x={mid - 11} y={3.4} width={22} height={6} rx={2} fill=\"white\" fillOpacity={premium ? 0.92 : 0.55} />\n      {/* Moulded shell with a lip along its top. */}\n      <path d={shell} fill={`url(#${uid}-shell)`} />\n      <path d={shell} fill={`url(#${uid}-side)`} />\n      <path d={`M5.5 16.5 C5.5 14.5 8 13.5 11 13.5 L${w - 11} 13.5 C${w - 8} 13.5 ${w - 5.5} 14.5 ${w - 5.5} 16.5`} fill=\"none\" stroke=\"white\" strokeOpacity=\"0.3\" />\n      {/* Screen in its bezel: dark with a glare, or lit up for the seat you picked. */}\n      <rect x={mid - 10.5} y={16} width={21} height={13} rx={2.4} fill=\"#16181d\" stroke=\"black\" strokeOpacity=\"0.35\" strokeWidth={0.75} />\n      {lit ? (\n        <>\n          <rect x={mid - 9} y={17.4} width={18} height={10.2} rx={1.4} fill=\"var(--color-primary)\" />\n          <rect x={mid - 9} y={17.4} width={18} height={4} rx={1.4} fill=\"white\" fillOpacity=\"0.25\" />\n        </>\n      ) : (\n        <>\n          <rect x={mid - 9} y={17.4} width={18} height={10.2} rx={1.4} fill=\"#0a0c10\" />\n          <path d={`M${mid - 6} ${27.2} L${mid + 1.5} ${17.8} L${mid + 4.5} ${17.8} L${mid - 3} ${27.2} Z`} fill=\"white\" fillOpacity=\"0.09\" />\n        </>\n      )}\n      {/* Stowed tray table and its latch. */}\n      <rect x={mid - 16} y={31} width={32} height={8.5} rx={2} fill=\"black\" fillOpacity=\"0.07\" stroke=\"black\" strokeOpacity=\"0.24\" strokeWidth={0.75} />\n      <rect x={mid - 3.5} y={30} width={7} height={2.6} rx={1} fill=\"black\" fillOpacity=\"0.5\" />\n      {/* Seat pocket. */}\n      <path d={`M${mid - 15} ${h - 4.5} Q${mid} ${h - 2.5} ${mid + 15} ${h - 4.5}`} fill=\"none\" stroke=\"black\" strokeOpacity=\"0.28\" strokeWidth={0.9} />\n      <path d={`M${mid - 15} ${h - 3.5} Q${mid} ${h - 1.5} ${mid + 15} ${h - 3.5}`} fill=\"none\" stroke=\"white\" strokeOpacity=\"0.18\" strokeWidth={0.75} />\n    </svg>\n  );\n}\n\nfunction SeatView({\n  seat,\n  state,\n  holder,\n  label,\n  tip,\n  tabIndex,\n  risen,\n  introDelay,\n  reduce,\n  onPick,\n  onFocus,\n}: SeatViewProps) {\n  const uid = useId().replace(/:/g, \"\");\n  const fabric =\n    state === \"taken\" ? FABRIC.taken : state === \"mine\" ? FABRIC.picked : FABRIC[seat.type];\n  // Seats lie flat until the cabin comes into view, then stand row by row.\n  // Your own seat reclines a little.\n  const upright = state === \"mine\" ? -102 : -90;\n  const backTransition =\n    introDelay !== null ? { ...SPRING_PANEL, delay: introDelay } : reduce ? { duration: 0 } : SPRING_SWAP;\n  const head = state === \"taken\" ? <StrangerHead seed={hash(seat.id)} /> : null;\n\n  return (\n    <Tooltip content={tip} sideOffset={14} arrow className=\"rounded-xl px-3 py-2 whitespace-nowrap\">\n    <motion.button\n      type=\"button\"\n      data-seat={seat.id}\n      tabIndex={tabIndex}\n      aria-label={label}\n      aria-disabled={state === \"taken\" || undefined}\n      onClick={onPick}\n      onFocus={onFocus}\n      className={cn(\n        \"group relative block shrink-0 outline-none transform-3d\",\n        state === \"taken\" ? \"cursor-not-allowed\" : \"cursor-pointer\",\n      )}\n      style={{ width: SEAT_W, height: SEAT_D }}\n    >\n      {/* Soft shadow the seat casts on the floor. */}\n      <span aria-hidden=\"true\" className=\"absolute inset-x-[2px] top-[6px] -bottom-[3px] rounded-[10px] bg-black/30 blur-[3px]\" />\n      {/* Cushion, on the floor, with its stitched seam. */}\n      <span\n        aria-hidden=\"true\"\n        className=\"absolute inset-x-[5px] top-[3px] bottom-[2px] overflow-hidden rounded-[10px] transition-[background] duration-200\"\n        style={{\n          background: `linear-gradient(180deg, color-mix(in oklab, ${fabric} 78%, white), ${fabric} 60%, color-mix(in oklab, ${fabric} 82%, black))`,\n        }}\n      >\n        <span className=\"absolute inset-x-[4px] top-[38%] block h-px bg-black/15\" />\n        <span className=\"absolute inset-x-[4px] top-[2px] block h-px bg-white/40\" />\n      </span>\n      {/* A ring spreads across the floor when a passenger lands in the seat. */}\n      <AnimatePresence>\n        {state === \"mine\" && !reduce ? (\n          <motion.span\n            key={holder}\n            aria-hidden=\"true\"\n            initial={{ opacity: 0.9, scale: 0.7 }}\n            animate={{ opacity: 0, scale: 1.9 }}\n            exit={{ opacity: 0, transition: { duration: 0 } }}\n            transition={{ duration: 0.7, ease: EASE_OUT }}\n            className=\"pointer-events-none absolute inset-0 rounded-[10px] border-2 border-primary\"\n          />\n        ) : null}\n      </AnimatePresence>\n      {/* Armrests, raised off the floor: a padded top and a darker cap at the front. */}\n      {([\"left-0\", \"right-0\"] as const).map((edge) => (\n        <span\n          key={edge}\n          aria-hidden=\"true\"\n          className={cn(\"absolute top-[6px] bottom-[1px] block w-[6px] overflow-hidden rounded-full shadow-[0_2px_3px_rgb(0_0_0/0.3)]\", edge)}\n          style={{\n            transform: \"translateZ(10px)\",\n            background:\n              \"linear-gradient(90deg, color-mix(in oklab, var(--color-foreground) 34%, var(--color-background)), color-mix(in oklab, var(--color-foreground) 52%, var(--color-background)) 50%, color-mix(in oklab, var(--color-foreground) 30%, var(--color-background)))\",\n          }}\n        >\n          <span className=\"absolute inset-x-0 top-0 block h-[9px] rounded-full bg-black/35\" />\n        </span>\n      ))}\n      {/* Seatback, standing at the cushion's rear edge, with the head behind it. */}\n      <motion.span\n        aria-hidden=\"true\"\n        initial={false}\n        animate={{ rotateX: risen ? upright : 0 }}\n        transition={backTransition}\n        className=\"absolute inset-x-[1px] bottom-0 block origin-bottom\"\n        style={{ height: BACK_H + PEEK }}\n      >\n        {head}\n        <AnimatePresence initial={false}>\n          {holder ? (\n            <motion.span\n              key={holder}\n              initial={reduce ? { opacity: 0 } : { y: HEAD + 4 }}\n              animate={reduce ? { opacity: 1 } : { y: 0 }}\n              exit={reduce ? { opacity: 0 } : { y: HEAD + 4, transition: { duration: 0.16, ease: EASE_OUT } }}\n              transition={reduce ? { duration: 0.15 } : SPRING_SWAP}\n              className={cn(\n                \"absolute left-1/2 top-0 -ml-[12.5px] flex items-center justify-center rounded-full text-[9px] font-bold leading-none\",\n                state === \"mine\"\n                  ? \"bg-background text-primary ring-2 ring-primary\"\n                  : \"bg-primary text-primary-foreground\",\n              )}\n              style={{ width: HEAD, height: HEAD }}\n            >\n              {holder}\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n        <span\n          className={cn(\n            \"absolute inset-x-0 bottom-0 block rounded-t-[14px] rounded-b-[4px] transition-shadow duration-200\",\n            state === \"mine\" && \"shadow-[0_0_20px_color-mix(in_oklab,var(--color-primary)_50%,transparent)]\",\n            \"group-focus-visible:ring-2 group-focus-visible:ring-muted-foreground group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-background\",\n          )}\n          style={{ height: BACK_H }}\n        >\n          <SeatBackShell fabric={fabric} premium={seat.type === \"premium\"} lit={state === \"mine\"} uid={uid} />\n        </span>\n      </motion.span>\n    </motion.button>\n    </Tooltip>\n  );\n}\n\nconst EMPTY: SeatSelection = {};\nconst NO_TAKEN: string[] = [];\n\n/**\n * A 3D aircraft cabin for picking seats on a booking. The floor tips away\n * from the viewer, every seat stands as a cushion and seatback, and a\n * passenger's head pops up over the seat they pick. The grid is one tab stop\n * with arrow key movement, and a summary totals the chosen seats.\n */\nexport function FlightSeatMap({\n  layout,\n  passengers,\n  taken = NO_TAKEN,\n  value,\n  defaultValue = EMPTY,\n  onChange,\n  currency = \"USD\",\n  tilt = 42,\n  sound = false,\n  labels,\n  className,\n}: FlightSeatMapProps) {\n  const t = useMessages(\"flightSeatMap\", flightSeatMapMessages, labels);\n  const { locale } = useLocale();\n  const reduce = Boolean(useReducedMotion());\n  const [selection, setSelection] = useControllable(value, defaultValue, onChange);\n  const cabin = useMemo(() => buildCabin(layout), [layout]);\n  const takenSet = useMemo(() => new Set(taken), [taken]);\n  const playPick = useSound(popSound, { enabled: sound });\n  const playClear = useSound(dismissSound, { enabled: sound });\n  const playSwitch = useSound(selectSound, { enabled: sound });\n  const playTaken = useSound(buzzSound, { enabled: sound, volume: 0.6 });\n\n  const formatMoney = useMemo(() => {\n    const format = new Intl.NumberFormat(locale ?? \"en-US\", {\n      style: \"currency\",\n      currency,\n      maximumFractionDigits: 0,\n    });\n    return (price: number) => format.format(price);\n  }, [locale, currency]);\n  const money = (price: number) => (price > 0 ? formatMoney(price) : t(\"included\"));\n\n  // Seat id to the passenger sitting there.\n  const occupant = useMemo(() => {\n    const map = new Map<string, SeatPassenger>();\n    for (const p of passengers) {\n      const seat = selection[p.id];\n      if (seat) map.set(seat, p);\n    }\n    return map;\n  }, [passengers, selection]);\n\n  // Who is being seated. Falls back to the first passenger without a seat\n  // when the chosen one leaves the list.\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const active =\n    passengers.find((p) => p.id === activeId) ??\n    passengers.find((p) => !selection[p.id]) ??\n    passengers[0];\n\n  // The roving tab stop, held as the seat id. Resolved during render: the\n  // cursor, else the active passenger's seat, else the first free seat.\n  const [cursor, setCursor] = useState<string | null>(null);\n  if (cursor !== null && !cabin.seats.has(cursor)) setCursor(null);\n  const firstFree =\n    cabin.grid.flat().find((s) => !takenSet.has(s.id) && !occupant.has(s.id)) ?? cabin.grid[0]?.[0];\n  const activeSeat = active ? selection[active.id] : null;\n  const tabStop =\n    cursor && cabin.seats.has(cursor)\n      ? cursor\n      : activeSeat && cabin.seats.has(activeSeat)\n        ? activeSeat\n        : (firstFree?.id ?? null);\n\n  const [announcement, setAnnouncement] = useState(\"\");\n  const gridRef = useRef<HTMLDivElement>(null);\n  const stageRef = useRef<HTMLDivElement>(null);\n  const planeRef = useRef<HTMLDivElement>(null);\n  const hullRef = useRef<HTMLDivElement>(null);\n\n  // 3D transforms leave layout alone, so the stage takes the height the\n  // tipped plane really covers on screen, worked out from its flat size:\n  // with the camera at the stage's bottom edge, a floor of length h tipped by\n  // θ spans h·cosθ·p / (p + h·sinθ). The plane also shrinks to fit narrow\n  // stages.\n  const [frame, setFrame] = useState<{ fit: number; height: number } | null>(null);\n  useLayoutEffect(() => {\n    const stage = stageRef.current;\n    const plane = planeRef.current;\n    const hull = hullRef.current;\n    if (!stage || !plane || !hull) return;\n    const measure = () => {\n      const fit = hull.offsetWidth > 0 ? Math.min(1, (stage.clientWidth - 16) / hull.offsetWidth) : 1;\n      const h = plane.offsetHeight;\n      const theta = (tilt * Math.PI) / 180;\n      // `scale` shrinks the plane across the screen but not in depth, so the\n      // fit applies to the rise on screen and the full length to the depth.\n      const height = Math.ceil((h * fit * Math.cos(theta) * PERSPECTIVE) / (PERSPECTIVE + h * Math.sin(theta))) + 36;\n      setFrame((f) => (f && f.fit === fit && f.height === height ? f : { fit, height }));\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(stage);\n    observer.observe(plane);\n    return () => observer.disconnect();\n  }, [tilt]);\n\n  // The cabin tips into place and the seats stand up once it is on screen.\n  const inView = useInView(stageRef, { once: true, amount: 0.25 });\n  const [intro, setIntro] = useState<\"waiting\" | \"running\" | \"done\">(reduce ? \"done\" : \"waiting\");\n  if (reduce && intro !== \"done\") setIntro(\"done\");\n  if (!reduce && inView && intro === \"waiting\") setIntro(\"running\");\n  const introSpan = cabin.rows.length * 0.045 + 0.7;\n  useEffect(() => {\n    if (intro !== \"running\") return;\n    const id = window.setTimeout(() => setIntro(\"done\"), introSpan * 1000);\n    return () => window.clearTimeout(id);\n  }, [intro, introSpan]);\n\n  // The cabin settles from a steeper angle while its seats stand up.\n  const rotateX = useSpring(reduce ? tilt : tilt + 20, CABIN_SETTLE);\n  useEffect(() => {\n    if (intro !== \"waiting\") rotateX.set(tilt);\n  }, [intro, tilt, rotateX]);\n\n  const focusNext = useRef(false);\n  const latest = useRef({ cabin, tabStop });\n  useLayoutEffect(() => {\n    latest.current = { cabin, tabStop };\n  });\n\n  // A key moved the cursor: move focus to its seat after the commit.\n  useLayoutEffect(() => {\n    if (!focusNext.current || !tabStop || !gridRef.current?.contains(document.activeElement)) return;\n    focusNext.current = false;\n    gridRef.current?.querySelector<HTMLButtonElement>(`[data-seat=\"${CSS.escape(tabStop)}\"]`)?.focus();\n  }, [tabStop]);\n\n  const assign = (seat: Seat) => {\n    if (!active) return;\n    if (takenSet.has(seat.id)) {\n      playTaken();\n      return;\n    }\n    const holder = occupant.get(seat.id);\n    if (holder && holder.id !== active.id) {\n      playSwitch();\n      setActiveId(holder.id);\n      return;\n    }\n    if (holder?.id === active.id) {\n      playClear();\n      setSelection({ ...selection, [active.id]: null });\n      setAnnouncement(t(\"announceCleared\", { name: active.name }));\n      return;\n    }\n    playPick();\n    const next = { ...selection, [active.id]: seat.id };\n    setSelection(next);\n    setAnnouncement(t(\"announce\", { seat: seat.id, name: active.name }));\n    // Move on to the next passenger still waiting for a seat.\n    const start = passengers.findIndex((p) => p.id === active.id);\n    const waiting = [...passengers.slice(start + 1), ...passengers.slice(0, start)].find((p) => !next[p.id]);\n    setActiveId(waiting?.id ?? active.id);\n  };\n\n  const clear = (passenger: SeatPassenger) => {\n    playClear();\n    setSelection({ ...selection, [passenger.id]: null });\n    setActiveId(passenger.id);\n    setAnnouncement(t(\"announceCleared\", { name: passenger.name }));\n  };\n\n  const onKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {\n    if (!NAV_KEYS.has(event.key)) return;\n    event.preventDefault();\n    const { key, ctrlKey } = event;\n    // The focused seat is where the keys start from.\n    const origin = (event.target as HTMLElement).closest<HTMLElement>(\"[data-seat]\")?.dataset.seat;\n    focusNext.current = true;\n    // Steps inside the update, so two keys landing in one batch move two\n    // seats: the first starts from the focused seat, the next from where the\n    // first left the cursor.\n    setCursor((current) => {\n      const { cabin: live, tabStop } = latest.current;\n      const from = current && current !== tabStop && live.seats.has(current) ? current : (origin ?? tabStop);\n      const at = from ? live.seats.get(from) : undefined;\n      if (!at) return current;\n      return stepSeat(live.grid, at, key, ctrlKey)?.id ?? at.id;\n    });\n  }, []);\n\n  const seatName = (seat: Seat) => {\n    const holder = occupant.get(seat.id);\n    const status = takenSet.has(seat.id)\n      ? t(\"taken\")\n      : holder\n        ? t(\"selectedFor\", { name: holder.name })\n        : t(\"available\");\n    return [t(\"seat\", { seat: seat.id }), t(seat.position), t(seat.type), money(seat.price), status].join(\", \");\n  };\n\n  const total = passengers.reduce((sum, p) => {\n    const seat = selection[p.id];\n    return sum + (seat ? (cabin.seats.get(seat)?.price ?? 0) : 0);\n  }, 0);\n  const types = Array.from(new Set(cabin.rows.map((r) => r.type)));\n  const firstAisle = layout.columns.indexOf(\"\");\n  const risen = intro !== \"waiting\";\n\n  return (\n    <div\n      className={cn(\"@container w-full text-sm\", className)}\n      style={\n        {\n          \"--hull\": \"color-mix(in oklab, var(--color-foreground) 5%, var(--color-background))\",\n          \"--floor\": \"color-mix(in oklab, var(--color-foreground) 9%, var(--color-background))\",\n        } as CSSProperties\n      }\n    >\n      {/* Narrow: passengers above the cabin. Wide: cabin on the left, passengers beside it. */}\n      <div className=\"grid grid-cols-1 items-start gap-4 @3xl:grid-cols-[minmax(0,1fr)_17rem] @3xl:gap-x-6\">\n        <div className=\"flex min-w-0 flex-col items-center gap-3 @3xl:col-start-1 @3xl:row-start-1\">\n          {/* The stage: the camera sits at its bottom edge, behind the rear. */}\n          <div\n            ref={stageRef}\n            className=\"relative w-full overflow-x-clip\"\n            style={{\n              height: frame?.height,\n              perspective: PERSPECTIVE,\n              perspectiveOrigin: \"50% 100%\",\n              visibility: frame ? undefined : \"hidden\",\n            }}\n          >\n            <motion.div\n              ref={planeRef}\n              className=\"absolute bottom-4 left-1/2 transform-3d\"\n              style={{\n                x: \"-50%\",\n                scale: frame?.fit ?? 1,\n                rotateX,\n                transformOrigin: \"50% 100%\",\n              }}\n            >\n              {/* Shadow on the ground far below. */}\n              <span\n                aria-hidden=\"true\"\n                className=\"absolute inset-x-6 inset-y-24 rounded-full bg-foreground/15 blur-[10px]\"\n                style={{ transform: \"translateZ(-70px)\" }}\n              />\n              {/* Hull: the cabin floor, rounded at both ends. */}\n              <div\n                ref={hullRef}\n                className=\"relative border border-foreground/20 transform-3d\"\n                style={{\n                  borderRadius: `50% / ${END}px`,\n                  paddingInline: PAD,\n                  // Deep enough that the outer seats clear the curve.\n                  paddingBlock: Math.round(END * 0.62),\n                  background: \"var(--hull)\",\n                }}\n              >\n\n                {/* biome-ignore lint/a11y/useSemanticElements: A 3D grid needs plain boxes; table parts flatten transforms. */}\n                <div\n                  ref={gridRef}\n                  role=\"grid\"\n                  aria-label={t(\"map\")}\n                  onKeyDown={onKeyDown}\n                  className=\"relative select-none transform-3d\"\n                >\n                  {/* Carpet down the aisle. */}\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"absolute inset-y-0\"\n                    style={{\n                      left: layout.columns.slice(0, firstAisle).filter(Boolean).length * (SEAT_W + 4),\n                      width: AISLE_W,\n                      background: \"var(--floor)\",\n                    }}\n                  />\n                  {/* biome-ignore lint/a11y/useSemanticElements: A 3D grid needs plain boxes; table parts flatten transforms. */}\n                  {/* biome-ignore lint/a11y/useFocusableInteractive: The seats inside take focus. */}\n                  <div role=\"row\" className=\"flex gap-1 pb-1\">\n                    {layout.columns.map((letter, i) => (\n                      // biome-ignore lint/a11y/useSemanticElements: See the grid note above.\n                      // biome-ignore lint/a11y/useFocusableInteractive: Headers are not focus stops in this grid.\n                      <span\n                        // biome-ignore lint/suspicious/noArrayIndexKey: Columns are positional; aisles have no letter of their own.\n                        key={i}\n                        role=\"columnheader\"\n                        className=\"flex shrink-0 items-end justify-center text-[11px] font-semibold text-muted-foreground\"\n                        style={{ width: letter ? SEAT_W : AISLE_W }}\n                      >\n                        {letter || <span className=\"sr-only\">{i === firstAisle ? t(\"row\") : t(\"aisleColumn\")}</span>}\n                      </span>\n                    ))}\n                  </div>\n                  {cabin.rows.map((row) => {\n                    const top = PITCH[row.type] + (row.sectionStart ? 14 : 0);\n                    return (\n                      // biome-ignore lint/a11y/useSemanticElements: See the grid note above.\n                      // biome-ignore lint/a11y/useFocusableInteractive: The seats inside take focus.\n                      <div\n                        key={row.row}\n                        role=\"row\"\n                        data-row={row.row}\n                        className=\"relative flex gap-1 transform-3d\"\n                        style={{ paddingTop: top }}\n                      >\n                        {row.exit ? (\n                          <>\n                            <ExitMark side=\"left\" offset={top} />\n                            <ExitMark side=\"right\" offset={top} />\n                          </>\n                        ) : null}\n                        {row.seats.map((seat, i) => {\n                          if (!seat) {\n                            return i === firstAisle ? (\n                              // biome-ignore lint/a11y/useSemanticElements: See the grid note above.\n                              // biome-ignore lint/a11y/useFocusableInteractive: Headers are not focus stops in this grid.\n                              <span\n                                // biome-ignore lint/suspicious/noArrayIndexKey: Aisles are positional.\n                                key={i}\n                                role=\"rowheader\"\n                                className=\"flex shrink-0 items-center justify-center text-[11px] font-semibold tabular-nums text-muted-foreground\"\n                                style={{ width: AISLE_W, height: SEAT_D }}\n                              >\n                                {row.row}\n                              </span>\n                            ) : (\n                              // biome-ignore lint/a11y/useSemanticElements: See the grid note above.\n                              // biome-ignore lint/a11y/useFocusableInteractive: An aisle holds no seat to focus.\n                              // biome-ignore lint/suspicious/noArrayIndexKey: Aisles are positional.\n                              <span key={i} role=\"gridcell\" className=\"shrink-0\" style={{ width: AISLE_W }} />\n                            );\n                          }\n                          const holder = occupant.get(seat.id);\n                          const state: SeatState = takenSet.has(seat.id)\n                            ? \"taken\"\n                            : holder\n                              ? holder.id === active?.id\n                                ? \"mine\"\n                                : \"other\"\n                              : \"available\";\n                          return (\n                            // biome-ignore lint/a11y/useSemanticElements: See the grid note above.\n                            // biome-ignore lint/a11y/useFocusableInteractive: The seat button inside takes focus.\n                            <div\n                              key={seat.id}\n                              role=\"gridcell\"\n                              aria-selected={Boolean(holder)}\n                              className=\"transform-3d\"\n                            >\n                              <SeatView\n                                seat={seat}\n                                state={state}\n                                holder={holder ? initials(holder.name) : undefined}\n                                label={seatName(seat)}\n                                tip={\n                                  <span className=\"flex flex-col gap-0.5\">\n                                    <span className=\"flex items-baseline justify-between gap-4\">\n                                      <span className=\"font-semibold\">{t(\"seat\", { seat: seat.id })}</span>\n                                      <span className=\"tabular-nums text-muted-foreground\">\n                                        {state === \"taken\" ? t(\"taken\") : holder ? holder.name : money(seat.price)}\n                                      </span>\n                                    </span>\n                                    <span className=\"font-normal text-muted-foreground\">\n                                      {t(seat.position)} · {t(seat.type)}\n                                    </span>\n                                  </span>\n                                }\n                                tabIndex={seat.id === tabStop ? 0 : -1}\n                                risen={risen}\n                                introDelay={intro === \"running\" ? row.seats.indexOf(seat) * 0.015 + seat.rowIndex * 0.045 : null}\n                                reduce={reduce}\n                                onPick={() => {\n                                  setCursor(seat.id);\n                                  assign(seat);\n                                }}\n                                onFocus={() => setCursor(seat.id)}\n                              />\n                            </div>\n                          );\n                        })}\n                      </div>\n                    );\n                  })}\n                </div>\n\n              </div>\n            </motion.div>\n          </div>\n\n          <ul\n            aria-label={t(\"legend\")}\n            className=\"flex flex-wrap justify-center gap-x-3 gap-y-1.5 text-xs text-muted-foreground\"\n          >\n            {types.map((type) => (\n              <li key={type} className=\"flex items-center gap-1.5\">\n                <span aria-hidden=\"true\" className=\"size-3 rounded-[4px]\" style={{ background: FABRIC[type] }} />\n                {t(type)}\n              </li>\n            ))}\n            <li className=\"flex items-center gap-1.5\">\n              <span aria-hidden=\"true\" className=\"size-3 rounded-[4px] bg-primary\" />\n              {t(\"selected\")}\n            </li>\n            <li className=\"flex items-center gap-1.5\">\n              <span aria-hidden=\"true\" className=\"size-3 rounded-[4px]\" style={{ background: FABRIC.taken }} />\n              {t(\"taken\")}\n            </li>\n          </ul>\n        </div>\n\n        <div className=\"min-w-0 @3xl:sticky @3xl:top-4 @3xl:col-start-2 @3xl:row-start-1 @max-3xl:row-start-1\">\n          <div className=\"overflow-hidden rounded-2xl border border-border\">\n            <ul aria-label={t(\"passengers\")} className=\"divide-y divide-border\">\n              {passengers.map((p) => {\n                const seat = selection[p.id] ? cabin.seats.get(selection[p.id] as string) : undefined;\n                const isActive = p.id === active?.id;\n                const switcher = passengers.length > 1;\n                const body = (\n                  <>\n                    <span\n                      aria-hidden=\"true\"\n                      className={cn(\n                        \"flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold transition-colors duration-200\",\n                        isActive && switcher ? \"bg-primary text-primary-foreground\" : \"bg-muted text-muted-foreground\",\n                      )}\n                    >\n                      {initials(p.name)}\n                    </span>\n                    <span className=\"min-w-0 flex-1\">\n                      <span className=\"block truncate font-medium\">{p.name}</span>\n                      <span className=\"block truncate text-xs text-muted-foreground\">\n                        {seat\n                          ? `${t(seat.position)}, ${t(seat.type)}`\n                          : isActive\n                            ? t(\"hint\", { name: p.name.split(\" \")[0] ?? p.name })\n                            : t(\"noSeat\")}\n                      </span>\n                    </span>\n                    <AnimatePresence initial={false} mode=\"popLayout\">\n                      {seat ? (\n                        <motion.span\n                          key={seat.id}\n                          initial={{ opacity: 0, y: reduce ? 0 : 6, filter: reduce ? \"none\" : \"blur(4px)\" }}\n                          animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                          exit={{ opacity: 0, y: reduce ? 0 : -6, filter: reduce ? \"none\" : \"blur(4px)\", transition: { duration: 0.12, ease: EASE_OUT } }}\n                          transition={{ duration: 0.2, ease: EASE_OUT }}\n                          className=\"text-right\"\n                        >\n                          <span className=\"block font-semibold tabular-nums\">{seat.id}</span>\n                          <span className=\"block text-xs tabular-nums text-muted-foreground\">{money(seat.price)}</span>\n                        </motion.span>\n                      ) : null}\n                    </AnimatePresence>\n                  </>\n                );\n                return (\n                  <li\n                    key={p.id}\n                    className={cn(\n                      \"flex h-14 items-center gap-1 pr-2 transition-colors duration-200\",\n                      isActive && switcher && \"bg-primary/[0.06]\",\n                    )}\n                  >\n                    {/* Picking a row makes that passenger the one being seated. */}\n                    {switcher ? (\n                      <button\n                        type=\"button\"\n                        aria-pressed={isActive}\n                        onClick={() => {\n                          if (!isActive) playSwitch();\n                          setActiveId(p.id);\n                        }}\n                        className=\"flex min-w-0 flex-1 items-center gap-2.5 self-stretch pl-3 pr-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-muted-foreground\"\n                      >\n                        {body}\n                      </button>\n                    ) : (\n                      <span className=\"flex min-w-0 flex-1 items-center gap-2.5 pl-3 pr-1\">{body}</span>\n                    )}\n                    {seat ? (\n                      <Tooltip content={t(\"clear\", { name: p.name })}>\n                        <button\n                          type=\"button\"\n                          aria-label={t(\"clear\", { name: p.name })}\n                          onClick={() => clear(p)}\n                          className=\"flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-muted-foreground\"\n                        >\n                          <X aria-hidden=\"true\" className=\"size-3.5\" />\n                        </button>\n                      </Tooltip>\n                    ) : null}\n                  </li>\n                );\n              })}\n            </ul>\n            <div className=\"flex items-center justify-between border-t border-border px-3 py-2.5\">\n              <span className=\"text-muted-foreground\">{t(\"total\")}</span>\n              <span className=\"font-semibold tabular-nums\">{formatMoney(total)}</span>\n            </div>\n          </div>\n        </div>\n      </div>\n      <div aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"registry:component","target":"@components/motion/tooltip.tsx","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from \"./tooltip/grace\";\nimport { TooltipArrow, TooltipPositioner } from \"./tooltip/positioner\";\nimport {\n  type TooltipAlign,\n  type TooltipAnchor,\n  type TooltipPoint,\n  type TooltipSide,\n  useTooltipPointer,\n} from \"./tooltip/use-position\";\n\nexport type { TooltipAlign, TooltipSide };\n\n/* -------------------------------------------------------------------------- */\n/* Provider                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface TooltipTiming {\n  /** Delay before a hover opens a tooltip (ms). */\n  delay: number;\n  /** Delay before a tooltip closes once the pointer has left it (ms). */\n  closeDelay: number;\n  /** After one tooltip closes, others open instantly for this long (ms). */\n  skipDelay: number;\n}\n\nconst TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });\n\nexport interface TooltipProviderProps extends Partial<TooltipTiming> {\n  children: ReactNode;\n}\n\n/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */\nexport function TooltipProvider({ children, ...timing }: TooltipProviderProps) {\n  const parent = useContext(TimingContext);\n  const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =\n    timing;\n  const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);\n  return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\n// Moving along a toolbar should feel instant after the first label, and only\n// one label may show at a time: a keyboard-focused control and a hovered one\n// would otherwise both claim the screen.\nlet lastClosedAt = 0;\nlet current: { close: () => void } | null = null;\n\nfunction isEmpty(content: ReactNode) {\n  return content == null || content === false || content === \"\";\n}\n\ninterface TooltipContextValue {\n  open: boolean;\n  /** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */\n  instant: boolean;\n  contentId: string;\n  labelId: string;\n  asLabel: boolean;\n  empty: boolean;\n  followCursor: boolean;\n  anchor: TooltipAnchor | null;\n  /** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */\n  triggered: boolean;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  pointer: ReturnType<typeof useTooltipPointer>;\n  setTrigger: (element: TooltipAnchor | null) => void;\n  setEmpty: (empty: boolean) => void;\n  close: () => void;\n  onContentEnter: () => void;\n  onContentLeave: (event: ReactPointerEvent) => void;\n}\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nfunction useTooltipContext(part: string) {\n  const context = useContext(TooltipContext);\n  if (!context) throw new Error(`${part} must be used inside <Tooltip>`);\n  return context;\n}\n\nexport interface TooltipRootProps {\n  children?: ReactNode;\n  /** Whether to show the tooltip in controlled use. An inert anchor keeps it hidden. */\n  open?: boolean;\n  /** Whether the tooltip starts shown when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called when the tooltip requests to show or hide, including when its anchor becomes inert. */\n  onOpenChange?: (open: boolean) => void;\n  /** Delay before showing on hover (ms). Keyboard focus shows immediately. */\n  delay?: number;\n  /** Delay before hiding once the pointer has left (ms). */\n  closeDelay?: number;\n  /** Never show, e.g. while the label it carries is already visible. */\n  disabled?: boolean;\n  /**\n   * Use the tooltip as the trigger's accessible name rather than its\n   * description. For icon-only controls whose only label is the tooltip.\n   */\n  asLabel?: boolean;\n  /** Follow real pointer coordinates; keyboard focus still uses the anchor. */\n  followCursor?: boolean;\n  /** Existing anchor for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<TooltipAnchor | null>;\n  /** Id of the tooltip surface, for anchors that reference it themselves. */\n  id?: string;\n}\n\nfunction TooltipRoot({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  delay: delayProp,\n  closeDelay: closeDelayProp,\n  disabled = false,\n  asLabel = false,\n  followCursor = false,\n  anchorRef,\n  id,\n  initialEmpty = false,\n}: TooltipRootProps & { initialEmpty?: boolean }) {\n  const timing = useContext(TimingContext);\n  const delay = delayProp ?? timing.delay;\n  const closeDelay = closeDelayProp ?? timing.closeDelay;\n  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n  const requestedOpen = controlledOpen ?? uncontrolledOpen;\n  const [anchorInert, setAnchorInert] = useState(false);\n  const open = requestedOpen && !anchorInert;\n  // Keyboard focus and a warm toolbar show the label at once; animating\n  // something seen this often only makes it feel slow.\n  const [instant, setInstant] = useState(false);\n  const [empty, setEmpty] = useState(initialEmpty);\n  const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);\n  const [external, setExternal] = useState<TooltipAnchor | null>(null);\n  const anchor = anchorRef ? external : trigger;\n  const generatedId = useId();\n  const contentId = id ?? `${generatedId}-content`;\n  const labelId = `${generatedId}-label`;\n  const floatingRef = useRef<HTMLSpanElement | null>(null);\n  const anchorObject = useRef<TooltipAnchor | null>(null);\n  const pointer = useTooltipPointer(anchor, followCursor);\n\n  // An external ref can attach after this component renders; read it once it has.\n  useLayoutEffect(() => {\n    if (!anchorRef) return;\n    const element = anchorRef.current ?? null;\n    if (element !== external) setExternal(element);\n  });\n\n  // Everything the event listeners read, current without re-binding them.\n  const latest = useRef({\n    open: requestedOpen,\n    delay,\n    closeDelay,\n    disabled,\n    empty,\n    onOpenChange,\n    controlled: false,\n  });\n  useLayoutEffect(() => {\n    anchorObject.current = anchor;\n    latest.current = {\n      open: requestedOpen,\n      delay,\n      closeDelay,\n      disabled,\n      empty,\n      onOpenChange,\n      controlled: controlledOpen !== undefined,\n    };\n  });\n\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const grace = useRef<(() => void) | null>(null);\n  const self = useRef<{ close: () => void }>({ close: () => {} });\n\n  const clearTimers = useCallback(() => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    if (closeTimer.current) clearTimeout(closeTimer.current);\n    openTimer.current = null;\n    closeTimer.current = null;\n  }, []);\n\n  const stopGrace = useCallback(() => {\n    grace.current?.();\n    grace.current = null;\n  }, []);\n\n  // Only a real change reaches the consumer: a pointer leaving a closed\n  // tooltip is not news.\n  const commit = useCallback((next: boolean) => {\n    if (latest.current.open === next) return;\n    if (!latest.current.controlled) setUncontrolledOpen(next);\n    latest.current.onOpenChange?.(next);\n  }, []);\n\n  const openNow = useCallback(\n    (now = false) => {\n      clearTimers();\n      stopGrace();\n      if (\n        latest.current.disabled ||\n        latest.current.empty ||\n        anchorObject.current?.closest(\"[inert]\")\n      ) return;\n      // The label being replaced leaves at once, so two never show together.\n      if (current && current !== self.current) current.close();\n      current = self.current;\n      setInstant(now);\n      commit(true);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n\n  const finish = useCallback(\n    (now: boolean) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.open) lastClosedAt = Date.now();\n      if (current === self.current) current = null;\n      if (latest.current.open) setInstant(now);\n      commit(false);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n  // Also a listener (window blur, outside press), so it takes no arguments.\n  const close = useCallback(() => finish(false), [finish]);\n  useLayoutEffect(() => {\n    self.current.close = () => finish(true);\n  }, [finish]);\n\n  useLayoutEffect(() => {\n    if (!requestedOpen || !anchor) {\n      setAnchorInert(false);\n      return;\n    }\n    // Inerting the anchor need not move the pointer. Close even if a pointer\n    // corridor or close delay would otherwise keep the portaled label visible.\n    let wasInert: boolean | undefined;\n    const check = () => {\n      const isInert = Boolean(anchor.closest(\"[inert]\"));\n      if (isInert === wasInert) return;\n      wasInert = isInert;\n      setAnchorInert(isInert);\n      if (isInert) finish(true);\n    };\n    const observer = new MutationObserver((records) => {\n      if (records.some((record) => record.type === \"childList\")) observeAncestors();\n      check();\n    });\n    const observeAncestors = () => {\n      observer.disconnect();\n      observer.observe(anchor, { attributes: true, attributeFilter: [\"inert\"] });\n      for (let parent = anchor.parentElement; parent; parent = parent.parentElement) {\n        observer.observe(parent, { attributes: true, attributeFilter: [\"inert\"], childList: true });\n      }\n      // A detached external anchor can reattach outside its old ancestry.\n      if (!anchor.isConnected) {\n        observer.observe(anchor.ownerDocument, { childList: true, subtree: true });\n      }\n    };\n    observeAncestors();\n    check();\n    return () => observer.disconnect();\n  }, [anchor, requestedOpen, finish]);\n\n  const requestOpen = useCallback(() => {\n    clearTimers();\n    if (\n      latest.current.open ||\n      latest.current.disabled ||\n      latest.current.empty ||\n      anchorObject.current?.closest(\"[inert]\")\n    ) return;\n    // Warm: another label is still showing (the pointer is crossing to this\n    // one), or one closed a moment ago. Either way, skip the delay and the fade.\n    const warm =\n      (current !== null && current !== self.current) ||\n      Date.now() - lastClosedAt < timing.skipDelay;\n    if (warm) openNow(true);\n    else if (latest.current.delay <= 0) openNow();\n    else openTimer.current = setTimeout(() => openNow(), latest.current.delay);\n  }, [clearTimers, openNow, timing.skipDelay]);\n\n  const requestClose = useCallback(() => {\n    clearTimers();\n    if (latest.current.closeDelay > 0) {\n      closeTimer.current = setTimeout(close, latest.current.closeDelay);\n    } else close();\n  }, [clearTimers, close]);\n\n  // Hold the label open while the pointer crosses from one box toward the other.\n  const startGrace = useCallback(\n    (exit: TooltipPoint, from: Element, to: Element | null) => {\n      stopGrace();\n      if (!to) return requestClose();\n      const target = to.getBoundingClientRect();\n      const origin = from.getBoundingClientRect();\n      const corridor = graceArea(exit, target);\n      const onMove = (event: PointerEvent) => {\n        const point = { x: event.clientX, y: event.clientY };\n        if (inBox(point, target) || inBox(point, origin)) return;\n        if (!inPolygon(point, corridor)) requestClose();\n      };\n      document.addEventListener(\"pointermove\", onMove);\n      grace.current = () => document.removeEventListener(\"pointermove\", onMove);\n    },\n    [stopGrace, requestClose],\n  );\n\n  const hover = useHoverGesture();\n  const tap = useTapGesture<boolean>();\n\n  // Listeners go on the trigger itself rather than on cloned props, so a\n  // component that owns its own handlers keeps them, and no wrapper element\n  // sits between the control and its layout.\n  useEffect(() => {\n    if (anchorRef || !trigger) return;\n    watchModality();\n    // A mouse press dismisses the label and keeps it away until the pointer\n    // leaves; hovering a control you just clicked should not bring it back.\n    let suppressed = false;\n    // Focus that came from the keyboard holds the label open on its own.\n    let keyboardFocus = false;\n\n    const onEnter = (event: PointerEvent) => {\n      if (!hover.enter(event)) return;\n      stopGrace();\n      if (closeTimer.current) clearTimeout(closeTimer.current);\n      if (!suppressed) requestOpen();\n    };\n    const onLeave = (event: PointerEvent) => {\n      if (!hover.leave(event)) return;\n      suppressed = false;\n      if (keyboardFocus) return;\n      if (openTimer.current) {\n        clearTimers();\n        return;\n      }\n      if (latest.current.open && !followCursor) {\n        startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);\n      } else requestClose();\n    };\n    const onDown = (event: PointerEvent) => {\n      tap.start(event, latest.current.open);\n      if (event.pointerType === \"mouse\") {\n        suppressed = true;\n        close();\n      }\n    };\n    // A finger never hovers, and Safari does not focus a button on tap either,\n    // so the label is only reachable if the tap itself toggles it. The click\n    // carries no pointerType; the pointerdown before it says whether it was a\n    // tap, and keyboard activation has none at all.\n    const onClick = () => {\n      const gesture = tap.take();\n      if (!gesture || gesture.pointerType === \"mouse\") return;\n      if (gesture.state) close();\n      else openNow();\n    };\n    const onKey = () => tap.drop();\n    const onFocusIn = () => {\n      if (!focusFromKeyboard()) return;\n      keyboardFocus = true;\n      openNow(true);\n    };\n    const onFocusOut = (event: FocusEvent) => {\n      if (trigger.contains(event.relatedTarget as Node | null)) return;\n      const fromKeyboard = keyboardFocus;\n      keyboardFocus = false;\n      // The inert observer owns this close, even when focus moves first.\n      if (trigger.closest(\"[inert]\")) return;\n      finish(fromKeyboard);\n    };\n\n    // Both element kinds dispatch the same events; one type keeps the listeners typed.\n    const el = trigger as HTMLElement;\n    el.addEventListener(\"pointerenter\", onEnter);\n    el.addEventListener(\"pointerleave\", onLeave);\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointercancel\", tap.drop);\n    el.addEventListener(\"click\", onClick);\n    el.addEventListener(\"keydown\", onKey);\n    el.addEventListener(\"focusin\", onFocusIn);\n    el.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      el.removeEventListener(\"pointerenter\", onEnter);\n      el.removeEventListener(\"pointerleave\", onLeave);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointercancel\", tap.drop);\n      el.removeEventListener(\"click\", onClick);\n      el.removeEventListener(\"keydown\", onKey);\n      el.removeEventListener(\"focusin\", onFocusIn);\n      el.removeEventListener(\"focusout\", onFocusOut);\n    };\n  }, [\n    anchorRef,\n    trigger,\n    followCursor,\n    hover,\n    tap,\n    requestOpen,\n    requestClose,\n    openNow,\n    close,\n    finish,\n    clearTimers,\n    stopGrace,\n    startGrace,\n  ]);\n\n  // While open, a trigger that turns disabled loses focus without a blur event,\n  // and a window that loses focus never reports the pointer leaving.\n  useEffect(() => {\n    if (!open || anchorRef || !trigger) return;\n    const observer = new MutationObserver(() => {\n      if (trigger.matches(\":disabled, [aria-disabled='true']\")) close();\n    });\n    observer.observe(trigger, { attributes: true, attributeFilter: [\"disabled\", \"aria-disabled\"] });\n    window.addEventListener(\"blur\", close);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"blur\", close);\n    };\n  }, [open, anchorRef, trigger, close]);\n\n  // A chart drives its own open state and swaps content as it goes; only a\n  // trigger-owned label closes itself for having nothing to say.\n  useEffect(() => {\n    if (disabled || (empty && !anchorRef)) close();\n  }, [disabled, empty, anchorRef, close]);\n\n  useEffect(\n    () => () => {\n      clearTimers();\n      stopGrace();\n      if (current === self.current) current = null;\n    },\n    [clearTimers, stopGrace],\n  );\n\n  const insideTooltip = useCallback(\n    (target: Element) => Boolean(floatingRef.current?.contains(target)),\n    [],\n  );\n  // ...and closed by the next tap that lands somewhere else, or Escape. The\n  // label covers nothing interactive, so that tap passes through to what it hit.\n  // Escape is a key press, so the label goes at once.\n  const dismiss = useCallback((reason: DismissReason) => finish(reason === \"escape\"), [finish]);\n  // Let other overlays handle presses and Tab on the anchor. The tooltip\n  // still leaves anchor presses to the trigger, which records open on touch.\n  useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip, layerRef: floatingRef });\n\n  const onContentEnter = useCallback(() => {\n    stopGrace();\n    clearTimers();\n  }, [stopGrace, clearTimers]);\n\n  const onContentLeave = useCallback(\n    (event: ReactPointerEvent) => {\n      const floating = floatingRef.current;\n      if (!floating) return;\n      if (anchorRef) {\n        // Bridge the small gap back onto a chart; it reopens on its own terms.\n        clearTimers();\n        closeTimer.current = setTimeout(close, 100);\n        return;\n      }\n      startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);\n    },\n    [anchorRef, clearTimers, close, startGrace],\n  );\n\n  const value = useMemo<TooltipContextValue>(\n    () => ({\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      triggered: !anchorRef,\n      floatingRef,\n      pointer,\n      setTrigger,\n      setEmpty,\n      close,\n      onContentEnter,\n      onContentLeave,\n    }),\n    [\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      anchorRef,\n      pointer,\n      close,\n      onContentEnter,\n      onContentLeave,\n    ],\n  );\n\n  return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nfunction mergeIds(...ids: unknown[]) {\n  return ids.filter((value) => typeof value === \"string\" && value).join(\" \") || undefined;\n}\n\nexport interface TooltipTriggerProps extends ComponentProps<\"button\"> {\n  /** Use the single child element as the trigger instead of rendering a button. */\n  asChild?: boolean;\n}\n\nexport function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {\n  const { open, contentId, labelId, asLabel, empty, setTrigger } =\n    useTooltipContext(\"TooltipTrigger\");\n  const child = asChild && isValidElement(children) ? children : null;\n  const childProps = (child?.props ?? props) as Record<string, unknown>;\n  const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;\n  const attached = useRef<TooltipAnchor | null>(null);\n\n  const setRef = useCallback(\n    (element: TooltipAnchor | null) => {\n      attached.current = element;\n      setTrigger(element);\n      assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);\n    },\n    [setTrigger, childRef, ref],\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"production\" && child && !attached.current) {\n      console.warn(\n        \"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.\",\n      );\n    }\n  }, [child]);\n\n  const aria = asLabel\n    ? {\n        \"aria-labelledby\": empty\n          ? (childProps[\"aria-labelledby\"] as string | undefined)\n          : labelId,\n      }\n    : {\n        \"aria-describedby\": mergeIds(\n          childProps[\"aria-describedby\"],\n          open && !empty ? contentId : undefined,\n        ),\n      };\n\n  if (asChild) {\n    if (!child) return children;\n    return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });\n  }\n\n  return (\n    <button\n      type=\"button\"\n      data-state={open ? \"open\" : \"closed\"}\n      {...props}\n      ref={setRef as Ref<HTMLButtonElement>}\n      {...aria}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipContentProps {\n  children?: ReactNode;\n  /** Preferred side of the anchor. Flips when there is no room. Default: \"top\" */\n  side?: TooltipSide;\n  /** Alignment along the chosen side. Default: \"center\" */\n  align?: TooltipAlign;\n  /** Gap between anchor and tooltip (px). */\n  sideOffset?: number;\n  /** Draw an arrow pointing at the anchor. */\n  arrow?: boolean;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: TooltipPoint;\n  /** Classes merged onto the tooltip surface. */\n  className?: string;\n}\n\nexport function TooltipContent({\n  children,\n  side = \"top\",\n  align = \"center\",\n  sideOffset,\n  arrow = false,\n  anchorPoint,\n  className,\n}: TooltipContentProps) {\n  const {\n    open,\n    instant,\n    contentId,\n    labelId,\n    asLabel,\n    followCursor,\n    anchor,\n    floatingRef,\n    pointer,\n    setEmpty,\n    close,\n    onContentEnter,\n    onContentLeave,\n  } = useTooltipContext(\"TooltipContent\");\n  const empty = isEmpty(children);\n  const arrowRef = useRef<SVGSVGElement | null>(null);\n\n  useLayoutEffect(() => {\n    setEmpty(empty);\n  }, [empty, setEmpty]);\n\n  if (typeof document === \"undefined\") return null;\n\n  return createPortal(\n    <>\n      {/* The name has to exist while the label is closed, so it lives apart from the surface. */}\n      {asLabel && !empty ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {/* `custom` reaches a surface that is already exiting, so a label closed\n          from the keyboard or replaced by a neighbour leaves without animating. */}\n      <AnimatePresence custom={instant}>\n        {open && !empty ? (\n          <TooltipPositioner\n            key=\"tooltip\"\n            anchor={anchor}\n            floatingRef={floatingRef}\n            arrowRef={arrow ? arrowRef : undefined}\n            anchorPoint={anchorPoint}\n            followCursor={followCursor}\n            side={side}\n            align={align}\n            sideOffset={sideOffset}\n            onDismiss={close}\n            pointer={pointer}\n          >\n            {(positioned, isPresent, placedSide) => (\n              <TooltipSurface\n                id={asLabel ? undefined : contentId}\n                aria-hidden={asLabel || undefined}\n                ready={positioned}\n                instant={instant}\n                onPointerEnter={onContentEnter}\n                onPointerLeave={onContentLeave}\n                style={{ pointerEvents: isPresent && !followCursor ? \"auto\" : \"none\" }}\n                className={cn(\n                  \"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words\",\n                  arrow && \"relative\",\n                  className,\n                )}\n              >\n                {children}\n                {arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}\n              </TooltipSurface>\n            )}\n          </TooltipPositioner>\n        ) : null}\n      </AnimatePresence>\n    </>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tooltip (root, or one-line shorthand when given `content`)                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipProps\n  extends TooltipRootProps,\n    Omit<TooltipContentProps, \"children\" | \"className\"> {\n  /**\n   * Shorthand: the tooltip's content. With it, `children` is the trigger\n   * element; without it, compose `TooltipTrigger` and `TooltipContent`.\n   */\n  content?: ReactNode;\n  /** Shorthand only: classes for the tooltip surface. */\n  className?: string;\n}\n\nexport function Tooltip(props: TooltipProps) {\n  if (!(\"content\" in props)) return <TooltipRoot {...props} />;\n  const {\n    content,\n    children,\n    side,\n    align,\n    sideOffset,\n    arrow,\n    anchorPoint,\n    className,\n    ...root\n  } = props;\n  if (!root.anchorRef && !isValidElement(children)) return children ?? null;\n  return (\n    <TooltipRoot {...root} initialEmpty={isEmpty(content)}>\n      {isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}\n      <TooltipContent\n        side={side}\n        align={align}\n        sideOffset={sideOffset}\n        arrow={arrow}\n        anchorPoint={anchorPoint}\n        className={className}\n      >\n        {content}\n      </TooltipContent>\n    </TooltipRoot>\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-controllable.ts","type":"registry:hook","target":"@lib/hooks/use-controllable.ts","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * A value that is controlled when `value` is defined and uncontrolled\n * otherwise. Returns the current value, a setter whose identity never changes,\n * and the raw internal setter for callers that resolve state during render.\n *\n * The setter calls `onChange` only when the value actually changes, so a\n * consumer is never told about a no-op.\n */\nexport function useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (next: T) => void,\n) {\n  const [internal, setInternal] = useState(defaultValue);\n  const latest = useRef({ value, internal, onChange });\n  useLayoutEffect(() => {\n    latest.current = { value, internal, onChange };\n  });\n  const set = useCallback((next: T) => {\n    const current = latest.current;\n    if (current.value === undefined) setInternal(next);\n    if ((current.value === undefined ? current.internal : current.value) !== next)\n      current.onChange?.(next);\n  }, []);\n  return [value === undefined ? internal : value, set, setInternal] as const;\n}\n"},{"path":"lib/i18n.tsx","type":"registry:lib","target":"@lib/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/sound.tsx","type":"registry:lib","target":"@lib/sound.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/buzz.ts","type":"registry:lib","target":"@lib/sounds/buzz.ts","content":"import { defineSound } from \"./engine\";\n\n/** A short low haptic buzz, for rejected input, validation errors or boundary collisions. */\nexport const buzzSound = defineSound({\n  name: \"Buzz\",\n  duration: 0.09,\n  room: 0.05,\n  build: (v) => {\n    v.tone({ type: \"sawtooth\", freq: 125, attack: 0.004, decay: 0.075, gain: 0.35 });\n    v.strike({ freq: 95, material: \"wood\", decay: 0.07, gain: 0.4 });\n  },\n});\n"},{"path":"lib/sounds/dismiss.ts","type":"registry:lib","target":"@lib/sounds/dismiss.ts","content":"import { defineSound } from \"./engine\";\n\n/** A quick airy flick that drops away, for dismissing toasts and notifications. */\nexport const dismissSound = defineSound({\n  name: \"Dismiss\",\n  duration: 0.14,\n  room: 0.1,\n  build: (v) => {\n    v.noise({ filter: \"bandpass\", freq: 2200, to: 500, q: 0.9, decay: 0.09, gain: 0.5 });\n    v.tone({ freq: 620, to: 180, decay: 0.08, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/pop.ts","type":"registry:lib","target":"@lib/sounds/pop.ts","content":"import { defineSound } from \"./engine\";\n\n/** A rounded bubbly pop sweeping quickly upward, for chips, badges and notifications. */\nexport const popSound = defineSound({\n  name: \"Pop\",\n  duration: 0.06,\n  vary: 0.04,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 1800, q: 1, decay: 0.003, gain: 0.3 });\n    v.tone({ freq: 220, to: 750, glide: 0.035, decay: 0.04, gain: 0.65 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"registry:lib","target":"@lib/sounds/select.ts","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/tooltip/grace.ts","type":"registry:component","target":"@components/motion/tooltip/grace.ts","content":"type Point = { x: number; y: number };\ntype Box = { left: number; top: number; right: number; bottom: number };\n\n/**\n * The corridor a pointer may cross between the trigger and the open tooltip\n * without closing it: the convex hull of where it left and the box it is\n * heading for. A fixed timeout either cuts a slow diagonal move short or keeps\n * the label alive after the pointer has plainly gone elsewhere; this follows\n * the path itself.\n */\nexport function graceArea(exit: Point, target: Box): Point[] {\n  // A few pixels either side of the exit point give the corridor some width at\n  // its narrow end, so a hand that drifts sideways while it moves stays inside.\n  const pad = 5;\n  return hull([\n    { x: exit.x - pad, y: exit.y - pad },\n    { x: exit.x + pad, y: exit.y - pad },\n    { x: exit.x - pad, y: exit.y + pad },\n    { x: exit.x + pad, y: exit.y + pad },\n    { x: target.left, y: target.top },\n    { x: target.right, y: target.top },\n    { x: target.right, y: target.bottom },\n    { x: target.left, y: target.bottom },\n  ]);\n}\n\nexport function inBox(point: Point, box: Box) {\n  return (\n    point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom\n  );\n}\n\nexport function inPolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\n// Monotone chain; the corridor is always convex, so a hull is all it needs.\nfunction hull(points: Point[]) {\n  const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n  const cross = (o: Point, a: Point, b: Point) =>\n    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n  const lower: Point[] = [];\n  for (const p of sorted) {\n    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {\n      lower.pop();\n    }\n    lower.push(p);\n  }\n  const upper: Point[] = [];\n  for (let i = sorted.length - 1; i >= 0; i--) {\n    const p = sorted[i];\n    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {\n      upper.pop();\n    }\n    upper.push(p);\n  }\n  lower.pop();\n  upper.pop();\n  return lower.concat(upper);\n}\n\n/**\n * How the user last reached for the page. A focus that a mouse press caused is\n * not a request to read the label: the pointer is already on the control and\n * hovering showed it. A focus that followed a key - Tab, or a roving arrow key\n * moving focus in script - is the only way a keyboard user sees it at all.\n */\nlet modality: \"keyboard\" | \"pointer\" = \"keyboard\";\nlet listening = false;\n\nexport function watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (modality = \"keyboard\"), true);\n  window.addEventListener(\"pointerdown\", () => (modality = \"pointer\"), true);\n}\n\nexport function focusFromKeyboard() {\n  return modality === \"keyboard\";\n}\n"},{"path":"components/motion/tooltip/positioner.tsx","type":"registry:component","target":"@components/motion/tooltip/positioner.tsx","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from \"react\";\nimport { type TooltipSide, useTooltipPosition } from \"./use-position\";\n\ntype PositionProps = Parameters<typeof useTooltipPosition>[0];\n\n/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */\nexport function TooltipPositioner({\n  children,\n  ...position\n}: Omit<PositionProps, \"open\" | \"onPosition\"> & {\n  children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;\n}) {\n  const present = useIsPresent();\n  const [ready, setReady] = useState(false);\n  const [side, setSide] = useState<TooltipSide>(position.side);\n  const onPosition = useCallback((placed: TooltipSide) => {\n    setReady(true);\n    setSide(placed);\n  }, []);\n  useTooltipPosition({ ...position, open: present, onPosition });\n  return (\n    <span\n      ref={position.floatingRef}\n      inert={!present}\n      aria-hidden={!present || undefined}\n      className=\"pointer-events-none fixed left-0 top-0 z-[9999] w-max\"\n      style={{ visibility: \"hidden\", maxWidth: \"calc(100vw - 16px)\" }}\n    >\n      {children(ready, present, side)}\n    </span>\n  );\n}\n\n// Each arrow is a 12px box whose base sits on the surface's inner border edge,\n// so its fill covers the border beneath it and only the two outer edges stroke.\nconst ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {\n  top: { path: \"M0 6L6 12L12 6\", style: { top: \"calc(100% - 6px)\" } },\n  bottom: { path: \"M0 6L6 0L12 6\", style: { bottom: \"calc(100% - 6px)\" } },\n  left: { path: \"M6 0L12 6L6 12\", style: { left: \"calc(100% - 6px)\" } },\n  right: { path: \"M6 0L0 6L6 12\", style: { right: \"calc(100% - 6px)\" } },\n};\n\nexport function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {\n  const { path, style } = ARROW[side];\n  return (\n    <svg\n      ref={ref}\n      aria-hidden=\"true\"\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 12 12\"\n      className=\"pointer-events-none absolute overflow-visible\"\n      style={style}\n    >\n      {/* Redrawn to fit the surface's edge once placed (see arrowShape). */}\n      <path data-arrow-fill=\"\" d={`${path}Z`} style={{ fill: \"var(--tooltip-arrow-fill, transparent)\" }} />\n      <path\n        data-arrow-stroke=\"\"\n        d={path}\n        fill=\"none\"\n        strokeWidth=\"1\"\n        style={{ stroke: \"var(--tooltip-arrow-stroke, transparent)\" }}\n      />\n    </svg>\n  );\n}\n"},{"path":"components/motion/tooltip/use-position.ts","type":"registry:component","target":"@components/motion/tooltip/use-position.ts","content":"\"use client\";\n\nimport {\n  arrow as arrowMiddleware,\n  autoUpdate,\n  computePosition,\n  flip,\n  hide,\n  offset,\n  type Placement,\n  shift,\n  type VirtualElement,\n} from \"@floating-ui/dom\";\nimport { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\n\nexport type TooltipSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type TooltipAlign = \"start\" | \"center\" | \"end\";\nexport type TooltipPoint = {\n  /** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */\n  x: number;\n  /** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */\n  y: number;\n};\nexport type TooltipAnchor = HTMLElement | SVGElement;\n\nconst ORIGIN: Record<TooltipSide, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */\nfunction blend(top: string, bottom: string) {\n  const context = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!context) return top;\n  context.fillStyle = bottom;\n  context.fillRect(0, 0, 1, 1);\n  context.fillStyle = top;\n  context.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;\n  // A see-through background has nothing solid to blend onto.\n  return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;\n}\n\n/** The arrow element's box, which the arrow middleware centres along the edge. */\nconst ARROW_SIZE = 12;\n/** How far the tip reaches past the border's inner edge. */\nconst ARROW_REACH = 6;\n\n/**\n * How far a rounded edge has curved in from its straight line at `position`\n * along an edge of `length`, with corners of `radius`. Zero on the straight\n * stretch between the corners.\n */\nfunction curveDepth(position: number, length: number, radius: number) {\n  const offset =\n    position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;\n  if (offset <= 0) return 0;\n  return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));\n}\n\n/**\n * The arrow's two paths, in the surface's border-box coordinates. Each 45°\n * side runs from the tip until it meets the middle of the surface's border,\n * wherever that is: on a straight stretch, or partway round a pill's curved\n * end. The stroke covers only those two sides, so the border flows straight\n * into them. The fill closes a little inside the surface, hiding the stretch\n * of border the arrow sits on.\n */\nfunction arrowShape({\n  side,\n  center,\n  width,\n  height,\n  radius,\n  border,\n}: {\n  side: TooltipSide;\n  center: number;\n  width: number;\n  height: number;\n  radius: number;\n  border: number;\n}) {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const length = vertical ? width : height;\n  // Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.\n  const tip = { depth: border - ARROW_REACH, along: center };\n  // The border's centre line: the stroke meets it there, so the two line up.\n  const line = border / 2;\n  // Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.\n  const curved =\n    curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||\n    curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;\n  const meet = (direction: -1 | 1) => {\n    // On a straight stretch the 45° side meets the border directly.\n    if (!curved) {\n      for (let t = 0; t <= ARROW_SIZE; t += 0.05) {\n        const along = center + direction * t;\n        const depth = tip.depth + t;\n        if (depth >= line) return { depth, along };\n      }\n    }\n    // On a pill's round end a 45° side passes outside the curve, or meets it\n    // at a kink. Run the side tangent to the curve instead, so the border\n    // flows into it without a corner.\n    const curve = radius - line;\n    const centre = { depth: radius, along: direction < 0 ? radius : length - radius };\n    const dx = tip.depth - centre.depth;\n    const dy = tip.along - centre.along;\n    const distance = Math.hypot(dx, dy);\n    if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };\n    const base = Math.atan2(dy, dx);\n    const spread = Math.acos(curve / distance);\n    const candidates = [base + spread, base - spread].map((angle) => ({\n      depth: centre.depth + curve * Math.cos(angle),\n      along: centre.along + curve * Math.sin(angle),\n    }));\n    // The tangent on this side of the tip.\n    return direction < 0\n      ? candidates[0].along < candidates[1].along\n        ? candidates[0]\n        : candidates[1]\n      : candidates[0].along > candidates[1].along\n        ? candidates[0]\n        : candidates[1];\n  };\n  const start = meet(-1);\n  const end = meet(1);\n  const inside = Math.max(start.depth, end.depth) + border + 1;\n  const point = ({ depth, along }: { depth: number; along: number }) => {\n    const [x, y] =\n      side === \"right\"\n        ? [depth, along]\n        : side === \"left\"\n          ? [width - depth, along]\n          : side === \"bottom\"\n            ? [along, depth]\n            : [along, height - depth];\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  };\n  return {\n    fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,\n    stroke: `M${point(start)}L${point(tip)}L${point(end)}`,\n  };\n}\n\n/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */\nexport function useTooltipPosition({\n  open,\n  anchor,\n  floatingRef,\n  arrowRef,\n  anchorPoint,\n  followCursor,\n  side,\n  align,\n  sideOffset,\n  onDismiss,\n  onPosition,\n  pointer,\n}: {\n  open: boolean;\n  anchor: TooltipAnchor | null;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  arrowRef?: RefObject<SVGSVGElement | null>;\n  anchorPoint?: TooltipPoint;\n  followCursor: boolean;\n  side: TooltipSide;\n  align: TooltipAlign;\n  sideOffset?: number;\n  onDismiss: () => void;\n  onPosition: (side: TooltipSide) => void;\n  pointer: ReturnType<typeof useTooltipPointer>;\n}) {\n  const { cursor, onMove } = pointer;\n  const preferred: Placement = align === \"center\" ? side : `${side}-${align}`;\n  const cursorSide = useRef<Placement | null>(null);\n  useLayoutEffect(() => {\n    cursorSide.current = open ? preferred : null;\n  }, [open, preferred]);\n  const frame = useRef<number | null>(null);\n  const version = useRef(0);\n  const update = useRef<() => void>(() => {});\n  const schedule = useCallback(() => {\n    // Invalidate older async calculations as soon as new geometry is requested.\n    version.current++;\n    if (frame.current !== null) return;\n    frame.current = requestAnimationFrame(() => {\n      frame.current = null;\n      update.current();\n    });\n  }, []);\n  useLayoutEffect(() => {\n    onMove.current = schedule;\n    return () => {\n      onMove.current = null;\n    };\n  }, [onMove, schedule]);\n  const pointX = anchorPoint?.x;\n  const pointY = anchorPoint?.y;\n\n  // Latest committed inputs are read without recreating observers for every period/content update.\n  useLayoutEffect(() => {\n    update.current = () => {\n      const floating = floatingRef.current;\n      if (!open || !anchor || !floating) return;\n      const revision = ++version.current;\n      const currentCursor = followCursor ? cursor.current : null;\n      const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;\n      const reference: Element | VirtualElement = virtual\n        ? {\n            contextElement: anchor,\n            getBoundingClientRect: () => {\n              const rect = anchor.getBoundingClientRect();\n              const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);\n              const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);\n              return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };\n            },\n          }\n        : anchor;\n      const arrowElement = arrowRef?.current ?? null;\n      void computePosition(reference, floating, {\n        strategy: \"fixed\",\n        placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,\n        middleware: [\n          offset(sideOffset ?? (currentCursor ? 12 : 8)),\n          flip({ padding: 8 }),\n          shift({ padding: 8 }),\n          ...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),\n          // A label left floating over whatever scrolled into its trigger's place\n          // describes nothing there. Points inside a chart move with the chart.\n          ...(virtual ? [] : [hide({ strategy: \"referenceHidden\" })]),\n        ],\n      }).then(({ x, y, placement, middlewareData }) => {\n        if (version.current !== revision || !floating.isConnected) return;\n        // Hold the chosen side for this hover session. Crossing a flip threshold\n        // repeatedly must not bounce the surface above and below the pointer.\n        if (currentCursor) cursorSide.current = placement;\n        else cursorSide.current = null;\n        const placedSide = placement.split(\"-\")[0] as TooltipSide;\n        const dpr = window.devicePixelRatio || 1;\n        floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;\n        floating.style.setProperty(\"--tooltip-origin\", ORIGIN[placedSide]);\n        // A box with no size has no clipped state to report, only a missing layout.\n        const box = anchor.getBoundingClientRect();\n        const clipped =\n          Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);\n        floating.style.visibility = clipped ? \"hidden\" : \"visible\";\n        floating.dataset.placement = placement;\n        const surface = arrowElement?.parentElement;\n        if (arrowElement && surface) {\n          // The middleware centres the 12px arrow box along the edge; its\n          // centre is where the tip points. The paths are drawn in the\n          // surface's border-box coordinates, so the svg sits at its corner.\n          const { x: ax, y: ay } = middlewareData.arrow ?? {};\n          const vertical = placedSide === \"top\" || placedSide === \"bottom\";\n          const width = surface.offsetWidth;\n          const height = surface.offsetHeight;\n          const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;\n          const style = getComputedStyle(surface);\n          const shape = arrowShape({\n            side: placedSide,\n            center: along + ARROW_SIZE / 2,\n            width,\n            height,\n            // `rounded-full` resolves to a huge radius; the box clamps it to half its short side.\n            radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),\n            border: surface.clientLeft,\n          });\n          Object.assign(arrowElement.style, {\n            left: `${-surface.clientLeft}px`,\n            top: `${-surface.clientTop}px`,\n            right: \"auto\",\n            bottom: \"auto\",\n          });\n          arrowElement.querySelector(\"[data-arrow-fill]\")?.setAttribute(\"d\", shape.fill);\n          arrowElement.querySelector(\"[data-arrow-stroke]\")?.setAttribute(\"d\", shape.stroke);\n          // Paint with whatever the surface resolved to, so a restyled tooltip\n          // keeps a matching arrow without a second set of classes. A\n          // see-through border is drawn over the surface's own background, so\n          // the stroke takes that blended colour: half of it sits over the\n          // page, and it overlaps the border where the two meet.\n          arrowElement.style.setProperty(\"--tooltip-arrow-fill\", style.backgroundColor);\n          arrowElement.style.setProperty(\n            \"--tooltip-arrow-stroke\",\n            blend(style.borderTopColor, style.backgroundColor),\n          );\n        }\n        onPosition(placedSide);\n      });\n    };\n    if (open) schedule();\n  }, [\n    open,\n    anchor,\n    floatingRef,\n    arrowRef,\n    followCursor,\n    pointX,\n    pointY,\n    preferred,\n    sideOffset,\n    schedule,\n    onPosition,\n    cursor,\n  ]);\n\n  useLayoutEffect(() => {\n    const floating = floatingRef.current;\n    if (!open || !anchor || !floating) return;\n    const stop = autoUpdate(anchor, floating, schedule);\n    const onScroll = () => {\n      // A stationary pointer no longer describes the same chart point after scrolling.\n      if (followCursor && cursor.current) onDismiss();\n    };\n    window.addEventListener(\"scroll\", onScroll, true);\n    return () => {\n      stop();\n      window.removeEventListener(\"scroll\", onScroll, true);\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n    };\n  }, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);\n\n  useLayoutEffect(\n    () => () => {\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n}\n\n/** Pointer lifetime belongs to the anchor, including the opening delay. */\nexport function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {\n  const cursor = useRef<TooltipPoint | null>(null);\n  const onMove = useRef<(() => void) | null>(null);\n  const pointerFocus = useRef(false);\n  useLayoutEffect(() => {\n    if (!anchor || !followCursor) return;\n    const point = (event: PointerEvent) => {\n      if (event.type === \"pointermove\" && event.pointerType === \"touch\" && !event.buttons) return;\n      cursor.current = { x: event.clientX, y: event.clientY };\n      if (event.type === \"pointerdown\") pointerFocus.current = true;\n      onMove.current?.();\n    };\n    const keyboard = () => {\n      cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const focus = () => {\n      if (!pointerFocus.current) cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const leave = () => {\n      cursor.current = null;\n    };\n    anchor.addEventListener(\"pointerenter\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointermove\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerdown\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerleave\", leave);\n    anchor.addEventListener(\"pointercancel\", leave);\n    anchor.addEventListener(\"keydown\", keyboard);\n    anchor.addEventListener(\"focusin\", focus);\n    return () => {\n      cursor.current = null;\n      anchor.removeEventListener(\"pointerenter\", point as EventListener);\n      anchor.removeEventListener(\"pointermove\", point as EventListener);\n      anchor.removeEventListener(\"pointerdown\", point as EventListener);\n      anchor.removeEventListener(\"pointerleave\", leave);\n      anchor.removeEventListener(\"pointercancel\", leave);\n      anchor.removeEventListener(\"keydown\", keyboard);\n      anchor.removeEventListener(\"focusin\", focus);\n    };\n  }, [anchor, followCursor]);\n\n  return useMemo(() => ({ cursor, onMove }), []);\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"registry:component","target":"@components/motion/tooltip-surface.tsx","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ComponentProps, ReactNode, Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nconst ENTER = { duration: 0.18, ease: EASE_OUT };\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\n/**\n * `custom` is the `instant` flag. An exiting surface reads it from its\n * `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once\n * even though it has already left the React tree.\n */\nconst variants = (reduce: boolean): Variants => ({\n  closed: (instant = false) => ({\n    opacity: 0,\n    scale: reduce ? 1 : 0.97,\n    transition: instant ? INSTANT : EXIT,\n  }),\n  open: (instant = false) => ({\n    opacity: 1,\n    scale: 1,\n    transition: instant ? INSTANT : ENTER,\n  }),\n});\n\n/** Presentation only: the unanimated parent owns measurement and positioning. */\nexport function TooltipSurface({\n  children,\n  className,\n  ref,\n  ready = true,\n  instant = false,\n  style,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  /** Start the entrance only after the positioning layer has been measured. */\n  ready?: boolean;\n  /**\n   * Appear and disappear without animating: a label opened from the keyboard,\n   * or one of a row of tooltips the pointer is moving along.\n   */\n  instant?: boolean;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      custom={instant}\n      variants={variants(reduce)}\n      initial=\"closed\"\n      animate={ready ? \"open\" : \"closed\"}\n      exit=\"closed\"\n      style={{ transformOrigin: \"var(--tooltip-origin, center)\", ...style }}\n      className={cn(\n        \"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n  /**\n   * Element other overlays treat as part of this layer for outside presses\n   * and focus traps. When set, the layer uses this element alone.\n   * Default: the elements matched by `ref` and `ignore`.\n   */\n  layerRef?: RefObject<HTMLElement | SVGElement | null>;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n * Pass `layerRef` when other overlays should recognize a different boundary.\n * The hook still uses `ref` and `ignore` for its own dismissal checks.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n    layerRef,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = {\n      contains: layerRef\n        ? (target) => Boolean(layerRef.current?.contains(target))\n        : inside,\n      escape: dismissOnEscape,\n    };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress, layerRef]);\n}\n"},{"path":"lib/hooks/use-hover-gesture.ts","type":"registry:hook","target":"@lib/hooks/use-hover-gesture.ts","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\nimport { isHoveringPointer } from \"@/lib/touch\";\n\ninterface BoundaryEvent {\n  pointerId: number;\n  pointerType: string;\n  buttons: number;\n}\n\nexport interface HoverGesture {\n  /** True when this enter starts a hover: the pointer arrived resting, not pressing. */\n  enter: (event: BoundaryEvent) => boolean;\n  /** True when this leave ends a hover that entered as one. */\n  leave: (event: BoundaryEvent) => boolean;\n}\n\n/**\n * Pairs a surface's enter with its leave, per pointer.\n *\n * `isHoveringPointer` answers the question the *enter* asks - is this pointer\n * resting on the surface or pressing it - and both boundary cases go wrong if\n * the leave is asked the same question again:\n *\n * - A pen with no hover never rests. It arrives in contact, taps, and the spec\n *   then requires its boundary events after `pointerup`, so the leave carries\n *   `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid\n *   the tap - the panel the pen had just opened closed under it.\n * - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.\n *   Skipping teardown there strands the surface open: the release happens\n *   outside, and no second leave ever comes.\n *\n * So the state a hover holds is released by the pointer that took it, whatever\n * the buttons say at the boundary, and a pointer that arrived in contact never\n * took it in the first place. Contact is the exception tracked here, not\n * hover: a leave from a pointer this surface never saw enter - mounted under\n * the cursor, say - still counts, since the alternative is state with no way\n * out.\n */\nexport function useHoverGesture(): HoverGesture {\n  const contact = useRef(new Set<number>());\n\n  return useMemo(\n    () => ({\n      enter: (event) => {\n        if (isHoveringPointer(event)) {\n          contact.current.delete(event.pointerId);\n          return true;\n        }\n        contact.current.add(event.pointerId);\n        return false;\n      },\n      leave: (event) => {\n        const arrivedInContact = contact.current.delete(event.pointerId);\n        return !arrivedInContact && event.pointerType !== \"touch\";\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/hooks/use-tap-gesture.ts","type":"registry:hook","target":"@lib/hooks/use-tap-gesture.ts","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\n\n/** What a pointerdown recorded, read back by the click that ends its gesture. */\nexport interface TapRecord<S> {\n  /** Which input started the gesture. */\n  pointerType: string;\n  /** What the surface was showing when it started. */\n  state: S;\n}\n\nexport interface TapGesture<S> {\n  /** Record the gesture a pointerdown starts, with the state it starts in. */\n  start: (event: { pointerType: string }, state: S) => void;\n  /** Read the record and clear it. `null` when no pointer is behind this click. */\n  take: () => TapRecord<S> | null;\n  /** Drop the record: this gesture will never spend it on a click. */\n  drop: () => void;\n}\n\n/**\n * The pointer gesture behind a click, recorded where the click cannot report\n * it. A `click` carries no `pointerType` in the engines that matter, so the\n * `pointerdown` before it is the only thing that says which input activated\n * the control - and whether one did at all, since keyboard activation\n * synthesizes a click with no pointer behind it.\n *\n * State goes in with the record because a click reports that no better: a\n * browser that focuses a control on contact can open the very panel the tap\n * was meant to open, and reading \"is it open\" at click time then undoes it.\n * What the gesture started against is what it acts on.\n *\n * The record is spent by one click and dropped by everything else, because a\n * record that outlives its gesture is worse than none:\n *\n * - A scroll or an OS gesture takes the touch away - `pointercancel`, no click\n *   ever - and the finger would sit in the record until some later click.\n * - That later click is often `Enter` on a keyboard, which arrives with no\n *   pointerdown of its own and would inherit the abandoned finger. A keydown\n *   is the start of a keyboard activation and never part of a tap, so it drops\n *   the record too.\n *\n * Both ends have to be wired by the surface: `drop` on `onPointerCancel` and\n * on `onKeyDown`.\n */\nexport function useTapGesture<S>(): TapGesture<S> {\n  const record = useRef<TapRecord<S> | null>(null);\n\n  return useMemo(\n    () => ({\n      start: (event, state) => {\n        record.current = { pointerType: event.pointerType, state };\n      },\n      take: () => {\n        const spent = record.current;\n        record.current = null;\n        return spent;\n      },\n      drop: () => {\n        record.current = null;\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/merge-refs.ts","type":"registry:lib","target":"@lib/merge-refs.ts","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"lib/audio-context.ts","type":"registry:lib","target":"@lib/audio-context.ts","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"registry:lib","target":"@lib/sounds/engine.ts","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"lib/layers.ts","type":"registry:lib","target":"@lib/layers.ts","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer for outside presses and focus. */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/touch.ts","type":"registry:lib","target":"@lib/touch.ts","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"}]}