{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "cavemio-video-player",
  "title": "Animated Video Player",
  "description": "Real adaptive streaming with quiet controls, liquid surfaces, and cinematic expansion that keeps the video playing.",
  "dependencies": [
    "gsap@^3.15.0",
    "shaka-player@^5.3.1",
    "hls.js@^1.7.3",
    "lucide-react@^1.57.0"
  ],
  "files": [
    {
      "path": "registry/components/video-player.tsx",
      "content": "\"use client\";\n\nimport {\n  lazy,\n  Suspense,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type KeyboardEvent,\n} from \"react\";\nimport { VideoPlayerContext } from \"./video-player-context\";\nimport { VideoPlayerStore } from \"./video-player-store\";\nimport { VideoControls, VideoStatus } from \"./video-player-controls\";\nimport {\n  useVideoExpansion,\n  useVideoReducedMotion,\n} from \"./video-player-motion\";\nimport type { VideoPlayerProps } from \"./video-player-types\";\n\nexport type {\n  VideoPlayerProps,\n  VideoSource,\n  VideoDrm,\n  VideoQuality,\n  VideoPlayerHandle,\n  PlayerError,\n} from \"./video-player-types\";\nexport { useVideoPlayer, useVideoState } from \"./video-player-context\";\nexport {\n  VideoControls,\n  VideoSeekbar,\n  VideoPlayButton,\n  VideoSettings,\n  VideoVolume,\n} from \"./video-player-controls\";\nconst Diagnostics = lazy(() => import(\"./video-player-diagnostics\"));\n\nexport function VideoPlayer({\n  src,\n  source,\n  type,\n  engine = \"shaka\",\n  poster,\n  title = \"Video\",\n  autoPlay = false,\n  muted = false,\n  loop = false,\n  playing,\n  onPlayingChange,\n  controls = true,\n  enableGooey = true,\n  enableAnimations = true,\n  enableDiagnostics = false,\n  enablePictureInPicture = true,\n  enableFullscreen = true,\n  reducedMotion = false,\n  onReady,\n  onError,\n  className = \"\",\n  style,\n  children,\n}: VideoPlayerProps) {\n  const [store] = useState(() => new VideoPlayerStore());\n  const video = useRef<HTMLVideoElement>(null);\n  const frame = useRef<HTMLDivElement>(null);\n  const placeholder = useRef<HTMLDivElement>(null);\n  const [expanded, setExpanded] = useState(false);\n  const [fullscreen, setFullscreen] = useState(false);\n  const [pip, setPip] = useState(false);\n  const [support, setSupport] = useState({ fullscreen: false, pip: false });\n  const [browserNotice, setBrowserNotice] = useState(\"\");\n  const reduced = useVideoReducedMotion(reducedMotion);\n  const animated = enableAnimations && !reduced;\n  const ready = useSyncExternalStore(\n    store.subscribe,\n    () => store.getSnapshot().ready,\n    () => false,\n  );\n  const callbacks = useRef({\n    playing,\n    autoPlay,\n    onReady,\n    onError,\n    onPlayingChange,\n  });\n  callbacks.current = { playing, autoPlay, onReady, onError, onPlayingChange };\n  store.callbacks = {\n    onReady: (handle) => {\n      callbacks.current.onReady?.(handle);\n      if (callbacks.current.playing ?? callbacks.current.autoPlay)\n        void handle.play().catch(() => {});\n    },\n    onError: (error) => callbacks.current.onError?.(error),\n    onPlayingChange: (value) => callbacks.current.onPlayingChange?.(value),\n  };\n  const mediaSource = useMemo(\n    () => ({\n      src: source?.src ?? src ?? \"\",\n      type: source?.type ?? type,\n      drm: source?.drm,\n    }),\n    [source?.src, source?.type, source?.drm, src, type],\n  );\n  const previousSource = useRef<string | null>(null);\n  useEffect(() => {\n    if (video.current) store.bind(video.current);\n    return () => store.unbind();\n  }, [store]);\n  useEffect(() => {\n    const sameSource = previousSource.current === mediaSource.src;\n    previousSource.current = mediaSource.src;\n    void store.load(mediaSource, engine, sameSource);\n  }, [store, mediaSource, engine]);\n  useEffect(() => {\n    if (!ready || playing === undefined) return;\n    if (playing) void store.play().catch(() => {});\n    else store.pause();\n  }, [playing, ready, store]);\n  useEffect(() => {\n    const el = video.current;\n    if (!el) return;\n    const doc = el.ownerDocument;\n    setSupport({\n      fullscreen: !!doc.fullscreenEnabled && !!frame.current?.requestFullscreen,\n      pip: !!doc.pictureInPictureEnabled && !!el.requestPictureInPicture,\n    });\n    const full = () => setFullscreen(doc.fullscreenElement === frame.current);\n    const picture = () => setPip(doc.pictureInPictureElement === el);\n    const failure = () =>\n      setBrowserNotice(\"Fullscreen was not available. Try cinematic mode.\");\n    doc.addEventListener(\"fullscreenchange\", full);\n    doc.addEventListener(\"fullscreenerror\", failure);\n    el.addEventListener(\"enterpictureinpicture\", picture);\n    el.addEventListener(\"leavepictureinpicture\", picture);\n    return () => {\n      doc.removeEventListener(\"fullscreenchange\", full);\n      doc.removeEventListener(\"fullscreenerror\", failure);\n      el.removeEventListener(\"enterpictureinpicture\", picture);\n      el.removeEventListener(\"leavepictureinpicture\", picture);\n    };\n  }, []);\n  const closeExpanded = useCallback(() => setExpanded(false), []);\n  useVideoExpansion(frame, placeholder, expanded, animated, closeExpanded);\n  const togglePlayback = useCallback(() => {\n    const next = store.getSnapshot().paused;\n    if (callbacks.current.playing !== undefined)\n      callbacks.current.onPlayingChange?.(next);\n    else if (next) void store.play().catch(() => {});\n    else store.pause();\n  }, [store]);\n  const toggleFullscreen = useCallback(() => {\n    const el = frame.current;\n    if (!el || !enableFullscreen || !support.fullscreen) return;\n    setBrowserNotice(\"\");\n    void (\n      el.ownerDocument.fullscreenElement === el\n        ? el.ownerDocument.exitFullscreen()\n        : el.requestFullscreen()\n    ).catch(() =>\n      setBrowserNotice(\"Fullscreen was not available. Try cinematic mode.\"),\n    );\n  }, [enableFullscreen, support.fullscreen]);\n  const togglePip = useCallback(() => {\n    const el = video.current;\n    if (!el || !enablePictureInPicture || !support.pip) return;\n    setBrowserNotice(\"\");\n    void (\n      el.ownerDocument.pictureInPictureElement === el\n        ? el.ownerDocument.exitPictureInPicture()\n        : el.requestPictureInPicture()\n    ).catch(() =>\n      setBrowserNotice(\n        \"Picture-in-picture is unavailable for this video or browser.\",\n      ),\n    );\n  }, [enablePictureInPicture, support.pip]);\n  const toggleExpanded = useCallback(() => {\n    if (!fullscreen) setExpanded((value) => (value ? false : enableFullscreen));\n  }, [fullscreen, enableFullscreen]);\n  const context = useMemo(\n    () => ({\n      store,\n      video,\n      frame,\n      animated,\n      gooey: enableGooey && !reduced,\n      expanded,\n      fullscreen,\n      pip,\n      canExpand: enableFullscreen,\n      canFullscreen: enableFullscreen && support.fullscreen,\n      canPip: enablePictureInPicture && support.pip,\n      togglePlayback,\n      toggleExpanded,\n      toggleFullscreen,\n      togglePip,\n    }),\n    [\n      store,\n      animated,\n      enableGooey,\n      reduced,\n      expanded,\n      fullscreen,\n      pip,\n      enableFullscreen,\n      enablePictureInPicture,\n      support,\n      togglePlayback,\n      toggleExpanded,\n      toggleFullscreen,\n      togglePip,\n    ],\n  );\n  const keyboard = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (\n      event.defaultPrevented ||\n      event.altKey ||\n      event.ctrlKey ||\n      event.metaKey ||\n      event.nativeEvent.isComposing\n    )\n      return;\n    const key = event.key.toLowerCase();\n    const mediaShortcut = key === \"m\" || key === \"f\";\n    if (event.target instanceof HTMLElement && event.target !== frame.current) {\n      if (\n        event.target.closest(\n          'select,textarea,input:not([type=\"range\"]),[contenteditable=\"true\"]',\n        )\n      )\n        return;\n      if (!mediaShortcut && event.target.closest('input,button,[role=\"menu\"]'))\n        return;\n    }\n    if (mediaShortcut && event.repeat) {\n      event.preventDefault();\n      return;\n    }\n    const state = store.getSnapshot();\n    switch (key) {\n      case \" \":\n      case \"k\":\n        togglePlayback();\n        break;\n      case \"arrowleft\":\n        store.seek(state.time - 5);\n        break;\n      case \"arrowright\":\n        store.seek(state.time + 5);\n        break;\n      case \"arrowup\":\n        store.setVolume(state.volume + 0.05);\n        break;\n      case \"arrowdown\":\n        store.setVolume(state.volume - 0.05);\n        break;\n      case \"m\":\n        store.toggleMute();\n        break;\n      case \"f\":\n        if (fullscreen) toggleFullscreen();\n        else toggleExpanded();\n        break;\n      case \"c\":\n        store.setTextTrack(\n          state.captions.some((t) => t.active)\n            ? \"off\"\n            : (state.captions[0]?.id ?? \"off\"),\n        );\n        break;\n      default:\n        return;\n    }\n    event.preventDefault();\n  };\n  useEffect(() => {\n    const el = frame.current;\n    if (!el) return;\n    const doc = el.ownerDocument;\n    const hoverShortcut = (event: globalThis.KeyboardEvent) => {\n      const key = event.key.toLowerCase();\n      if (\n        (key !== \"m\" && key !== \"f\") ||\n        event.defaultPrevented ||\n        event.altKey ||\n        event.ctrlKey ||\n        event.metaKey ||\n        event.isComposing ||\n        !el.matches(\":hover\")\n      )\n        return;\n      // Focused controls use the React handler; only body focus needs hover routing.\n      if (event.target !== doc.body && event.target !== doc.documentElement)\n        return;\n      event.preventDefault();\n      if (event.repeat) return;\n      if (key === \"m\") store.toggleMute();\n      else if (fullscreen) toggleFullscreen();\n      else toggleExpanded();\n    };\n    doc.addEventListener(\"keydown\", hoverShortcut);\n    return () => doc.removeEventListener(\"keydown\", hoverShortcut);\n  }, [store, fullscreen, toggleFullscreen, toggleExpanded]);\n  return (\n    <VideoPlayerContext.Provider value={context}>\n      <div\n        className={`w-full min-w-0 ${className}`}\n        style={style}\n        data-video-player=\"\"\n      >\n        <div\n          ref={placeholder}\n          className=\"@container/player-layout relative aspect-video w-full\"\n        >\n          <div\n            ref={frame}\n            popover=\"manual\"\n            tabIndex={0}\n            role={expanded ? \"dialog\" : \"region\"}\n            aria-modal={expanded || undefined}\n            aria-label={`${title} video player`}\n            onKeyDown={keyboard}\n            className=\"@container absolute inset-0 isolate m-0 block h-full w-full overflow-visible rounded-[20px] border-0 bg-black p-0 text-white outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 [&::backdrop]:bg-black/70 [&::backdrop]:opacity-[var(--video-backdrop,0)]\"\n            style={{ display: \"block\", containerType: \"size\" }}\n            data-expanded={expanded}\n            data-motion={animated ? \"full\" : \"reduced\"}\n          >\n            <video\n              ref={video}\n              poster={source?.poster ?? poster}\n              muted={muted}\n              loop={loop}\n              playsInline\n              preload=\"metadata\"\n              aria-label={title}\n              className=\"absolute inset-0 h-full w-full rounded-[inherit] object-cover\"\n            />\n            <VideoStatus title={title} controls={controls} />\n            {controls && <VideoControls />}\n            {children}\n            {expanded && !controls && (\n              <button\n                type=\"button\"\n                onClick={closeExpanded}\n                className=\"absolute right-4 top-4 rounded-full bg-white/15 backdrop-blur-xl px-4 py-3 focus-visible:outline-2 focus-visible:outline-ring\"\n              >\n                Close cinematic mode\n              </button>\n            )}\n            <p\n              role=\"status\"\n              className={\n                browserNotice\n                  ? \"absolute left-4 top-4 max-w-[80%] rounded-lg bg-white/15 backdrop-blur-xl px-3 py-2 text-xs\"\n                  : \"sr-only\"\n              }\n            >\n              {browserNotice}\n            </p>\n          </div>\n        </div>\n        {enableDiagnostics && (\n          <Suspense\n            fallback={\n              <p className=\"p-3 text-xs text-muted-foreground\">\n                Loading diagnostics…\n              </p>\n            }\n          >\n            <Diagnostics format={mediaSource.type} src={mediaSource.src} />\n          </Suspense>\n        )}\n      </div>\n    </VideoPlayerContext.Provider>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-types.ts",
      "content": "import type { CSSProperties, ReactNode } from \"react\";\nimport type shaka from \"shaka-player\";\n\nexport type VideoFormat = \"hls\" | \"dash\" | \"mp4\";\nexport type VideoEngine = \"shaka\" | \"hls\" | \"native\";\n/** Shaka's installed configuration types, with partial nested configuration. */\nexport type VideoDrm = Omit<\n  Partial<shaka.extern.DrmConfiguration>,\n  \"advanced\"\n> & {\n  advanced?: Record<string, Partial<shaka.extern.AdvancedDrmConfiguration>>;\n};\nexport interface VideoSource {\n  src: string;\n  type?: VideoFormat;\n  poster?: string;\n  drm?: VideoDrm;\n}\nexport interface VideoQuality {\n  id: string;\n  label: string;\n  width: number;\n  height: number;\n  bitrate: number;\n  active: boolean;\n}\nexport interface VideoTrack {\n  id: string;\n  label: string;\n  language: string;\n  active: boolean;\n}\nexport interface PlayerError {\n  code: string;\n  category:\n    \"network\" | \"media\" | \"drm\" | \"permission\" | \"unsupported\" | \"unknown\";\n  message: string;\n  fatal: boolean;\n  retryable: boolean;\n}\nexport interface PlaybackStats {\n  width: number | null;\n  height: number | null;\n  estimatedBandwidth: number | null;\n  variantBitrate: number | null;\n  droppedFrames: number | null;\n  loadLatency: number | null;\n}\nexport interface PlayerCapabilities {\n  quality: boolean;\n  audio: boolean;\n  captions: boolean;\n  drm: boolean;\n}\nexport type PlayerEvent =\n  | { type: \"loading\" | \"manifest\" | \"tracks\" | \"quality\" | \"recovery\" }\n  | { type: \"buffering\"; buffering: boolean }\n  | { type: \"error\"; error: PlayerError };\nexport interface PlayerAdapter {\n  readonly engine: VideoEngine;\n  readonly capabilities: PlayerCapabilities;\n  load(source: VideoSource, startTime?: number): Promise<void>;\n  getQualities(): VideoQuality[];\n  setQuality(id: string): void;\n  getAudioTracks(): VideoTrack[];\n  setAudioTrack(id: string): void;\n  getTextTracks(): VideoTrack[];\n  setTextTrack(id: string): void;\n  getStats(): PlaybackStats;\n  getSeekRange(): { start: number; end: number; live: boolean };\n  destroy(): Promise<void> | void;\n}\nexport interface VideoPlayerHandle {\n  play(): Promise<void>;\n  pause(): void;\n  seek(time: number): void;\n  setQuality(id: string): void;\n  setAudioTrack(id: string): void;\n  setTextTrack(id: string): void;\n  setVolume(volume: number): void;\n  toggleMute(): void;\n  setPlaybackRate(rate: number): void;\n  retry(): void;\n}\nexport interface VideoPlayerProps {\n  src?: string;\n  source?: VideoSource;\n  type?: VideoFormat;\n  engine?: VideoEngine;\n  poster?: string;\n  title?: string;\n  autoPlay?: boolean;\n  muted?: boolean;\n  loop?: boolean;\n  /** Controlled intent. Pair with onPlayingChange; actual state follows media events. */\n  playing?: boolean;\n  onPlayingChange?: (playing: boolean) => void;\n  controls?: boolean;\n  enableGooey?: boolean;\n  enableAnimations?: boolean;\n  enableDiagnostics?: boolean;\n  enablePictureInPicture?: boolean;\n  enableFullscreen?: boolean;\n  /** May force reduced motion, but never overrides the user's OS preference. */\n  reducedMotion?: boolean;\n  onReady?: (player: VideoPlayerHandle) => void;\n  onError?: (error: PlayerError) => void;\n  className?: string;\n  style?: CSSProperties;\n  children?: ReactNode;\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-utils.ts",
      "content": "import type {\n  PlayerError,\n  VideoEngine,\n  VideoFormat,\n  VideoQuality,\n} from \"./video-player-types\";\n\nexport function formatVideoTime(value: number): string {\n  if (!Number.isFinite(value) || value < 0) return \"0:00\";\n  const seconds = Math.floor(value);\n  const minutes = Math.floor(seconds / 60);\n  return minutes >= 60\n    ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, \"0\")}:${String(seconds % 60).padStart(2, \"0\")}`\n    : `${minutes}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\nexport function detectVideoFormat(\n  src: string,\n  explicit?: VideoFormat,\n): VideoFormat {\n  if (explicit) return explicit;\n  const path = src.split(/[?#]/)[0].toLowerCase();\n  if (path.endsWith(\".mpd\")) return \"dash\";\n  if (path.endsWith(\".m3u8\")) return \"hls\";\n  return \"mp4\";\n}\nexport function supportsSource(\n  engine: VideoEngine,\n  format: VideoFormat,\n  drm = false,\n) {\n  if (drm && engine !== \"shaka\") return false;\n  return (\n    engine === \"shaka\" ||\n    (engine === \"hls\" ? format === \"hls\" : format !== \"dash\")\n  );\n}\nexport function readRanges(ranges: TimeRanges): [number, number][] {\n  return Array.from({ length: ranges.length }, (_, i) => [\n    ranges.start(i),\n    ranges.end(i),\n  ]);\n}\nexport function bufferAt(\n  ranges: readonly (readonly [number, number])[],\n  time: number,\n) {\n  const range = ranges.find(([start, end]) => time >= start && time <= end);\n  return {\n    ahead: range ? range[1] - time : 0,\n    behind: range ? time - range[0] : 0,\n  };\n}\nexport function clampSeek(time: number, start: number, end: number) {\n  return Number.isFinite(time) && end > start\n    ? Math.min(end, Math.max(start, time))\n    : start;\n}\nexport function normalizeQualities(qualities: VideoQuality[]): VideoQuality[] {\n  return [...qualities].sort(\n    (a, b) => b.height - a.height || b.bitrate - a.bitrate,\n  );\n}\nexport function finite(value: number | undefined): number | null {\n  return value !== undefined && Number.isFinite(value) ? value : null;\n}\n/** Deliberately discard engine messages, URLs, payloads and stack traces. */\nexport function playerError(error: unknown, fatal = true): PlayerError {\n  const e = (\n    typeof error === \"object\" && error !== null ? error : {}\n  ) as Record<string, unknown>;\n  const category =\n    e.name === \"NotAllowedError\"\n      ? \"permission\"\n      : e.name === \"NotSupportedError\"\n        ? \"unsupported\"\n        : e.category === 1\n          ? \"network\"\n          : e.category === 6\n            ? \"drm\"\n            : e.category === 3 || e.category === 4 || e.category === 5\n              ? \"media\"\n              : \"unknown\";\n  const messages = {\n    permission: \"Playback was blocked. Press play to try again.\",\n    unsupported: \"This browser or playback engine cannot play this source.\",\n    network:\n      \"The video could not be downloaded. Check your connection and retry.\",\n    drm: \"Protected playback could not start. Check device support and license configuration.\",\n    media: \"This video could not be decoded or its manifest is invalid.\",\n    unknown: \"The video could not start. Please try again.\",\n  };\n  return {\n    code: typeof e.code === \"number\" ? String(e.code) : category.toUpperCase(),\n    category,\n    message: messages[category],\n    fatal,\n    retryable: category !== \"unsupported\" && category !== \"permission\",\n  };\n}\nexport function unsupportedError(message: string): PlayerError {\n  return {\n    code: \"UNSUPPORTED\",\n    category: \"unsupported\",\n    message,\n    fatal: true,\n    retryable: false,\n  };\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-store.ts",
      "content": "import type {\n  PlayerAdapter,\n  PlayerCapabilities,\n  PlayerError,\n  PlayerEvent,\n  PlaybackStats,\n  VideoEngine,\n  VideoPlayerHandle,\n  VideoQuality,\n  VideoSource,\n  VideoTrack,\n} from \"./video-player-types\";\nimport {\n  bufferAt,\n  clampSeek,\n  detectVideoFormat,\n  playerError,\n  readRanges,\n  supportsSource,\n  unsupportedError,\n} from \"./video-player-utils\";\n\nexport interface VideoState {\n  ready: boolean;\n  paused: boolean;\n  buffering: boolean;\n  ended: boolean;\n  time: number;\n  duration: number;\n  volume: number;\n  muted: boolean;\n  rate: number;\n  range: { start: number; end: number; live: boolean };\n  buffered: [number, number][];\n  engine: VideoEngine | null;\n  capabilities: PlayerCapabilities;\n  qualities: VideoQuality[];\n  audio: VideoTrack[];\n  captions: VideoTrack[];\n  selectedQuality: string;\n  error: PlayerError | null;\n  notice: string;\n}\nexport interface VideoDiagnostics {\n  stats: PlaybackStats | null;\n  bufferAhead: number;\n  bufferBehind: number;\n  stalls: number;\n  bufferingSeconds: number;\n  startupSeconds: number | null;\n  latestError: PlayerError | null;\n  events: { at: number; event: string; detail?: string }[];\n}\nconst initialState = (): VideoState => ({\n  ready: false,\n  paused: true,\n  buffering: false,\n  ended: false,\n  time: 0,\n  duration: 0,\n  volume: 1,\n  muted: false,\n  rate: 1,\n  range: { start: 0, end: 0, live: false },\n  buffered: [],\n  engine: null,\n  capabilities: { quality: false, audio: false, captions: false, drm: false },\n  qualities: [],\n  audio: [],\n  captions: [],\n  selectedQuality: \"auto\",\n  error: null,\n  notice: \"\",\n});\n\n/** One store per persistent video. All engine ownership changes pass through queue. */\nexport class VideoPlayerStore implements VideoPlayerHandle {\n  private state = initialState();\n  private diagnostics: VideoDiagnostics = {\n    stats: null,\n    bufferAhead: 0,\n    bufferBehind: 0,\n    stalls: 0,\n    bufferingSeconds: 0,\n    startupSeconds: null,\n    latestError: null,\n    events: [],\n  };\n  private listeners = new Set<() => void>();\n  private metricsListeners = new Set<() => void>();\n  private adapter: PlayerAdapter | null = null;\n  private video: HTMLVideoElement | null = null;\n  private queue: Promise<void> = Promise.resolve();\n  private generation = 0;\n  private source?: VideoSource;\n  private requestedEngine: VideoEngine = \"shaka\";\n  private previousVolume = 1;\n  private lastTick = 0;\n  private loadStarted = 0;\n  private bufferStarted: number | null = null;\n  private played = false;\n  private metricsTimer?: ReturnType<typeof setInterval>;\n  private removeMediaListeners?: () => void;\n  callbacks: {\n    onReady?: (handle: VideoPlayerHandle) => void;\n    onError?: (error: PlayerError) => void;\n    onPlayingChange?: (playing: boolean) => void;\n  } = {};\n  getSnapshot = () => this.state;\n  getDiagnostics = () => this.diagnostics;\n  subscribe = (fn: () => void) => {\n    this.listeners.add(fn);\n    return () => {\n      this.listeners.delete(fn);\n    };\n  };\n  subscribeDiagnostics = (fn: () => void) => {\n    this.metricsListeners.add(fn);\n    if (!this.metricsTimer)\n      this.metricsTimer = setInterval(() => {\n        if (typeof document !== \"undefined\" && !document.hidden) this.sample();\n      }, 1000);\n    return () => {\n      this.metricsListeners.delete(fn);\n      if (!this.metricsListeners.size) {\n        clearInterval(this.metricsTimer);\n        this.metricsTimer = undefined;\n      }\n    };\n  };\n  private patch(patch: Partial<VideoState>) {\n    this.state = { ...this.state, ...patch };\n    this.listeners.forEach((fn) => fn());\n  }\n  private log(event: string, detail?: string) {\n    this.diagnostics = {\n      ...this.diagnostics,\n      events: [\n        ...this.diagnostics.events.slice(-59),\n        {\n          at: Math.round(performance.now() - this.loadStarted),\n          event,\n          ...(detail ? { detail } : {}),\n        },\n      ],\n    };\n    this.metricsListeners.forEach((fn) => fn());\n  }\n  private setBuffering(buffering: boolean) {\n    if (buffering === this.state.buffering) return;\n    if (buffering) {\n      this.bufferStarted = performance.now();\n      if (this.played && !this.video?.paused && !this.video?.seeking)\n        this.diagnostics = {\n          ...this.diagnostics,\n          stalls: this.diagnostics.stalls + 1,\n        };\n    } else if (this.bufferStarted !== null) {\n      this.diagnostics = {\n        ...this.diagnostics,\n        bufferingSeconds:\n          this.diagnostics.bufferingSeconds +\n          (performance.now() - this.bufferStarted) / 1000,\n      };\n      this.bufferStarted = null;\n    }\n    this.patch({ buffering });\n    this.log(buffering ? \"Buffering started\" : \"Buffering ended\");\n  }\n  private fail(error: PlayerError) {\n    this.diagnostics = { ...this.diagnostics, latestError: error };\n    this.log(\n      error.fatal\n        ? \"Fatal playback error\"\n        : error.category === \"network\"\n          ? \"Network error\"\n          : \"Playback warning\",\n      error.code,\n    );\n    if (error.fatal) {\n      this.setBuffering(false);\n      this.patch({ error });\n    }\n    this.callbacks.onError?.(error);\n  }\n  private refreshTracks() {\n    if (!this.adapter) return;\n    this.patch({\n      qualities: this.adapter.getQualities(),\n      audio: this.adapter.getAudioTracks(),\n      captions: this.adapter.getTextTracks(),\n    });\n  }\n  private engineEvent = (event: PlayerEvent) => {\n    if (event.type === \"error\") {\n      this.fail(event.error);\n      return;\n    }\n    if (event.type === \"buffering\") {\n      this.setBuffering(event.buffering);\n      return;\n    }\n    if (event.type === \"loading\") this.log(\"Manifest loading\");\n    if (event.type === \"manifest\") this.log(\"Manifest parsed\");\n    if (event.type === \"recovery\") this.log(\"Recovery attempted\");\n    if ([\"manifest\", \"tracks\", \"quality\"].includes(event.type))\n      this.refreshTracks();\n    if (event.type === \"quality\")\n      this.log(\n        \"Quality switched\",\n        this.state.qualities.find((q) => q.active)?.label,\n      );\n  };\n  bind(video: HTMLVideoElement) {\n    this.video = video;\n    const update = () => {\n      const range = this.adapter?.getSeekRange() ?? {\n        start: 0,\n        end: 0,\n        live: false,\n      };\n      this.patch({\n        time: video.currentTime,\n        duration: Number.isFinite(video.duration) ? video.duration : 0,\n        paused: video.paused,\n        ended: video.ended,\n        volume: video.volume,\n        muted: video.muted,\n        rate: video.playbackRate,\n        buffered: readRanges(video.buffered),\n        range,\n      });\n    };\n    const tick = () => {\n      if (performance.now() - this.lastTick > 200) {\n        this.lastTick = performance.now();\n        update();\n      }\n    };\n    const played = () => {\n      this.setBuffering(false);\n      if (!this.played)\n        this.diagnostics = {\n          ...this.diagnostics,\n          startupSeconds: (performance.now() - this.loadStarted) / 1000,\n        };\n      this.played = true;\n      this.patch({ error: null, notice: \"\" });\n      this.log(\"Playback started\");\n      update();\n    };\n    const onPlay = () => {\n      update();\n      this.callbacks.onPlayingChange?.(true);\n    };\n    const onPause = () => {\n      this.setBuffering(false);\n      update();\n      this.callbacks.onPlayingChange?.(false);\n    };\n    const listeners: [string, EventListener][] = [\n      [\"timeupdate\", tick],\n      [\"progress\", tick],\n      [\"durationchange\", update],\n      [\"loadedmetadata\", update],\n      [\"volumechange\", update],\n      [\"ratechange\", update],\n      [\"play\", onPlay],\n      [\"pause\", onPause],\n      [\"playing\", played],\n      [\"ended\", onPause],\n      [\"waiting\", () => this.setBuffering(true)],\n      [\n        \"seeking\",\n        () => {\n          update();\n          if (!video.paused) this.setBuffering(true);\n        },\n      ],\n      [\n        \"seeked\",\n        () => {\n          update();\n          if (video.readyState >= 3) this.setBuffering(false);\n        },\n      ],\n      [\n        \"canplay\",\n        () => {\n          this.setBuffering(false);\n          update();\n        },\n      ],\n      [\n        \"error\",\n        () => {\n          if (video.error && this.adapter?.engine === \"native\")\n            this.fail(playerError({ category: 3, code: video.error.code }));\n        },\n      ],\n    ];\n    listeners.forEach(([name, fn]) => video.addEventListener(name, fn));\n    this.removeMediaListeners = () =>\n      listeners.forEach(([name, fn]) => video.removeEventListener(name, fn));\n    update();\n  }\n  async load(source: VideoSource, engine: VideoEngine, resume = false) {\n    const generation = ++this.generation;\n    const position = resume ? this.video?.currentTime : undefined;\n    const wasPlaying = resume && !this.video?.paused;\n    this.source = source;\n    this.requestedEngine = engine;\n    this.queue = this.queue\n      .then(async () => {\n        // Teardown must settle before a different engine is constructed/attached.\n        if (this.adapter) {\n          const old = this.adapter;\n          this.adapter = null;\n          await old.destroy();\n        }\n        if (generation !== this.generation || !this.video) return;\n        this.state = {\n          ...initialState(),\n          volume: this.video.volume,\n          muted: this.video.muted,\n          rate: this.video.playbackRate,\n        };\n        this.loadStarted = performance.now();\n        this.played = false;\n        this.bufferStarted = null;\n        this.diagnostics = {\n          stats: null,\n          bufferAhead: 0,\n          bufferBehind: 0,\n          stalls: 0,\n          bufferingSeconds: 0,\n          startupSeconds: null,\n          latestError: null,\n          events: [],\n        };\n        this.patch({ buffering: true });\n        this.bufferStarted = performance.now();\n        if (\n          !source.src.trim() ||\n          !supportsSource(\n            engine,\n            detectVideoFormat(source.src, source.type),\n            !!source.drm,\n          )\n        ) {\n          this.fail(\n            unsupportedError(\n              \"Choose Shaka for DASH or protected content; HLS.js accepts HLS sources only.\",\n            ),\n          );\n          return;\n        }\n        const emit = (event: PlayerEvent) => {\n          if (generation === this.generation) this.engineEvent(event);\n        };\n        let factory: () => PlayerAdapter;\n        if (engine === \"shaka\") {\n          const { ShakaAdapter } = await import(\"./video-player-shaka\");\n          factory = () => new ShakaAdapter(this.video!, emit);\n        } else if (engine === \"hls\") {\n          const { createHlsAdapter } = await import(\"./video-player-hls\");\n          factory = () => createHlsAdapter(this.video!, emit);\n        } else {\n          const { NativeAdapter } = await import(\"./video-player-native\");\n          factory = () => new NativeAdapter(this.video!, emit);\n        }\n        if (generation !== this.generation || !this.video) return;\n        const adapter = factory();\n        this.adapter = adapter;\n        this.patch({\n          engine: adapter.engine,\n          capabilities: adapter.capabilities,\n        });\n        // Do not block teardown behind network loading. destroy() cancels load().\n        void adapter\n          .load(source, position)\n          .then(() => {\n            if (generation !== this.generation) return;\n            this.refreshTracks();\n            this.patch({ ready: true });\n            this.callbacks.onReady?.(this);\n            if (wasPlaying) void this.play().catch(() => {});\n          })\n          .catch((error: unknown) => {\n            if (generation === this.generation) this.fail(playerError(error));\n          });\n      })\n      .catch((error: unknown) => {\n        if (generation === this.generation) this.fail(playerError(error));\n      });\n    await this.queue;\n  }\n  unbind() {\n    ++this.generation;\n    this.removeMediaListeners?.();\n    this.removeMediaListeners = undefined;\n    this.video = null;\n    clearInterval(this.metricsTimer);\n    this.metricsTimer = undefined;\n    this.queue = this.queue.then(async () => {\n      if (this.adapter) {\n        const old = this.adapter;\n        this.adapter = null;\n        await old.destroy();\n      }\n    });\n    // Observe cleanup rejections; the queue stays rejected to prevent unsafe reattachment.\n    void this.queue.catch(() => {});\n  }\n  async play() {\n    if (!this.video) return;\n    const generation = this.generation;\n    try {\n      await this.video.play();\n    } catch (error) {\n      if (generation !== this.generation) return;\n      const normalized = playerError(error, false);\n      this.patch({ notice: normalized.message });\n      this.fail(normalized);\n      throw error;\n    }\n  }\n  pause() {\n    this.video?.pause();\n  }\n  seek(time: number) {\n    if (!this.video || !this.adapter) return;\n    const { start, end } = this.adapter.getSeekRange();\n    if (end > start) this.video.currentTime = clampSeek(time, start, end);\n  }\n  setVolume(volume: number) {\n    if (!this.video || !Number.isFinite(volume)) return;\n    try {\n      this.video.volume = Math.min(1, Math.max(0, volume));\n      this.video.muted = volume === 0;\n      if (volume > 0) this.previousVolume = volume;\n    } catch {\n      this.patch({ notice: \"Use your device volume buttons.\" });\n    }\n    if (Math.abs(this.video.volume - Math.min(1, Math.max(0, volume))) > 0.01)\n      this.patch({ notice: \"Use your device volume buttons.\" });\n  }\n  toggleMute() {\n    if (!this.video) return;\n    if (this.video.muted || this.video.volume === 0) {\n      this.setVolume(this.previousVolume);\n      this.video.muted = false;\n    } else {\n      this.previousVolume = this.video.volume;\n      this.video.muted = true;\n    }\n  }\n  setPlaybackRate(rate: number) {\n    if (!this.video || ![0.5, 0.75, 1, 1.25, 1.5, 2].includes(rate)) return;\n    try {\n      this.video.playbackRate = rate;\n    } catch {\n      this.patch({ notice: \"This playback speed is unavailable.\" });\n    }\n  }\n  setQuality(id: string) {\n    if (\n      !this.adapter?.capabilities.quality ||\n      (id !== \"auto\" && !this.state.qualities.some((q) => q.id === id))\n    )\n      return;\n    this.adapter.setQuality(id);\n    this.patch({ selectedQuality: id });\n    this.refreshTracks();\n    this.log(\n      \"Quality requested\",\n      id === \"auto\"\n        ? \"Auto\"\n        : this.state.qualities.find((q) => q.id === id)?.label,\n    );\n  }\n  setAudioTrack(id: string) {\n    this.adapter?.setAudioTrack(id);\n    this.refreshTracks();\n    this.setQuality(\"auto\");\n  }\n  setTextTrack(id: string) {\n    this.adapter?.setTextTrack(id);\n    this.refreshTracks();\n  }\n  retry() {\n    if (this.source) {\n      this.log(\"Recovery attempted\");\n      void this.load(this.source, this.requestedEngine, true);\n    }\n  }\n  private sample() {\n    if (!this.video) return;\n    const buffer = bufferAt(\n      readRanges(this.video.buffered),\n      this.video.currentTime,\n    );\n    this.diagnostics = {\n      ...this.diagnostics,\n      stats: this.adapter?.getStats() ?? null,\n      bufferAhead: buffer.ahead,\n      bufferBehind: buffer.behind,\n    };\n    this.metricsListeners.forEach((fn) => fn());\n  }\n  exportDiagnostics() {\n    this.sample();\n    // Whitelist only normalized values. Never serialize source/config/raw engine errors.\n    return JSON.stringify(\n      {\n        version: 1,\n        engine: this.state.engine,\n        format: this.source\n          ? detectVideoFormat(this.source.src, this.source.type)\n          : null,\n        playbackRate: this.state.rate,\n        abr: this.state.capabilities.quality\n          ? this.state.selectedQuality === \"auto\"\n          : null,\n        ...this.diagnostics,\n        bufferingSeconds: this.bufferingSeconds(),\n      },\n      null,\n      2,\n    );\n  }\n  bufferingSeconds() {\n    return (\n      this.diagnostics.bufferingSeconds +\n      (this.bufferStarted !== null\n        ? (performance.now() - this.bufferStarted) / 1000\n        : 0)\n    );\n  }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-context.tsx",
      "content": "\"use client\";\nimport {\n  createContext,\n  useContext,\n  useSyncExternalStore,\n  type RefObject,\n} from \"react\";\nimport { VideoPlayerStore, type VideoState } from \"./video-player-store\";\n\nexport interface VideoPlayerContextValue {\n  store: VideoPlayerStore;\n  video: RefObject<HTMLVideoElement | null>;\n  frame: RefObject<HTMLDivElement | null>;\n  animated: boolean;\n  gooey: boolean;\n  expanded: boolean;\n  fullscreen: boolean;\n  pip: boolean;\n  canFullscreen: boolean;\n  canExpand: boolean;\n  canPip: boolean;\n  togglePlayback(): void;\n  toggleExpanded(): void;\n  toggleFullscreen(): void;\n  togglePip(): void;\n}\nexport const VideoPlayerContext = createContext<VideoPlayerContextValue | null>(\n  null,\n);\nexport function useVideoPlayer() {\n  const context = useContext(VideoPlayerContext);\n  if (!context)\n    throw new Error(\"Video controls must be rendered inside VideoPlayer.\");\n  return context;\n}\n/** Select a stable value/field; time updates do not re-render unrelated controls. */\nexport function useVideoState<T>(selector: (state: VideoState) => T): T {\n  const { store } = useVideoPlayer();\n  return useSyncExternalStore(\n    store.subscribe,\n    () => selector(store.getSnapshot()),\n    () => selector(store.getSnapshot()),\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-controls.tsx",
      "content": "\"use client\";\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ComponentPropsWithRef,\n} from \"react\";\nimport { gsap } from \"gsap\";\nimport { CustomEase } from \"gsap/CustomEase\";\nimport {\n  Captions,\n  Check,\n  ChevronLeft,\n  ChevronRight,\n  Expand,\n  LoaderCircle,\n  Pause,\n  PictureInPicture2,\n  Play,\n  Settings2,\n  Volume2,\n  VolumeX,\n} from \"lucide-react\";\nimport { useVideoPlayer, useVideoState } from \"./video-player-context\";\nimport { formatVideoTime } from \"./video-player-utils\";\nimport { useVideoTimeline, videoFullscreenMotion } from \"./video-player-motion\";\n\ngsap.registerPlugin(CustomEase);\n// A soft start leaves time to see the neck before the surface separates.\nconst tooltipPourEase = CustomEase.create(\n  \"cavemio-tooltip-pour\",\n  \"M0,0 C0.12,0 0.18,0.15 0.28,0.55 C0.42,1.1 0.55,1.08 0.68,1.02 C0.8,0.98 0.9,1 1,1\",\n);\n\nconst buttonStyle =\n  \"relative z-10 h-11 min-w-11 shrink-0 items-center justify-center rounded-full text-white/85 outline-none hover:text-white focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-35 [&>svg]:size-[14px]\";\nexport function VideoButton({\n  label,\n  children,\n  className = \"inline-flex\",\n  ...props\n}: ComponentPropsWithRef<\"button\"> & { label: string }) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      className={`${buttonStyle} ${className}`}\n      {...props}\n    >\n      {children}\n    </button>\n  );\n}\nexport function VideoPlayButton() {\n  const { togglePlayback, animated } = useVideoPlayer();\n  const paused = useVideoState((s) => s.paused);\n  const icon = useRef<HTMLSpanElement>(null);\n  useLayoutEffect(() => {\n    if (!icon.current || !animated) return;\n    const tween = gsap.fromTo(\n      icon.current,\n      { scale: 0.76, opacity: 0.4 },\n      { scale: 1, opacity: 1, duration: 0.24, ease: \"back.out(1.5)\" },\n    );\n    return () => {\n      tween.kill();\n      gsap.set(icon.current, { clearProps: \"transform,opacity\" });\n    };\n  }, [paused, animated]);\n  return (\n    <VideoButton label={paused ? \"Play\" : \"Pause\"} onClick={togglePlayback}>\n      <span ref={icon} className=\"inline-flex [&>svg]:size-[14px]\">\n        {paused ? <Play fill=\"currentColor\" /> : <Pause fill=\"currentColor\" />}\n      </span>\n    </VideoButton>\n  );\n}\n/** Both corner states stay mounted, so quick reversals blend from the visible frame. */\nfunction VideoFullscreenIcon({\n  active,\n  animated,\n}: {\n  active: boolean;\n  animated: boolean;\n}) {\n  const outward = useRef<SVGSVGElement>(null);\n  const inward = useRef<SVGSVGElement>(null);\n  const initialized = useRef(false);\n  useLayoutEffect(() => {\n    const entering = active ? inward.current : outward.current;\n    const leaving = active ? outward.current : inward.current;\n    const duration =\n      initialized.current && animated ? videoFullscreenMotion.iconDuration : 0;\n    initialized.current = true;\n    const show = gsap.to(entering, {\n      opacity: 1,\n      scale: 1,\n      duration,\n      ease: videoFullscreenMotion.ease,\n      overwrite: true,\n    });\n    const hide = gsap.to(leaving, {\n      opacity: 0,\n      scale: 0.6,\n      duration,\n      ease: videoFullscreenMotion.ease,\n      overwrite: true,\n    });\n    return () => {\n      show.kill();\n      hide.kill();\n    };\n  }, [active, animated]);\n  return (\n    <span\n      aria-hidden\n      className=\"relative inline-flex size-4\"\n      data-fullscreen-icon\n    >\n      <svg\n        ref={outward}\n        data-fullscreen-state=\"enter\"\n        viewBox=\"0 0 16 16\"\n        className=\"absolute inset-0 size-4 origin-center\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        <path d=\"M2.5 6V2.5H6 M10 2.5H13.5V6 M13.5 10V13.5H10 M6 13.5H2.5V10\" />\n      </svg>\n      <svg\n        ref={inward}\n        data-fullscreen-state=\"exit\"\n        viewBox=\"0 0 16 16\"\n        className=\"absolute inset-0 size-4 origin-center opacity-0\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        <path d=\"M6 2.5V6H2.5 M13.5 6H10V2.5 M10 13.5V10H13.5 M2.5 10H6V13.5\" />\n      </svg>\n    </span>\n  );\n}\n\nfunction VideoFullscreenButton() {\n  const context = useVideoPlayer();\n  const active = context.expanded || context.fullscreen;\n  return (\n    <VideoButton\n      label={active ? \"Exit fullscreen\" : \"Fullscreen\"}\n      aria-pressed={active}\n      aria-keyshortcuts=\"f\"\n      data-fullscreen-control\n      disabled={!active && !context.canExpand}\n      onClick={\n        context.fullscreen ? context.toggleFullscreen : context.toggleExpanded\n      }\n    >\n      <VideoFullscreenIcon active={active} animated={context.animated} />\n    </VideoButton>\n  );\n}\n\nexport function VideoVolume() {\n  const { store, animated, gooey } = useVideoPlayer();\n  const muted = useVideoState((s) => s.muted || s.volume === 0);\n  const volume = useVideoState((s) => s.volume);\n  const [open, setOpen] = useState(false);\n  const root = useRef<HTMLDivElement>(null);\n  const decoration = useRef<HTMLDivElement>(null);\n  const panel = useRef<HTMLDivElement>(null);\n  const copy = useRef<HTMLDivElement>(null);\n  const rail = useRef<HTMLDivElement>(null);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const dragging = useRef(false);\n  const geometry = useRef({\n    x: 6,\n    y: 6,\n    width: 32,\n    height: 32,\n    radius: 16,\n    opacity: 0,\n  });\n  const id = `volume-goo-${useId().replace(/:/g, \"\")}`;\n  const reveal = () => {\n    clearTimeout(timer.current);\n    setOpen(true);\n  };\n  const dismiss = () => {\n    clearTimeout(timer.current);\n    timer.current = setTimeout(\n      () => {\n        if (\n          !dragging.current &&\n          !root.current?.matches(\":hover\") &&\n          !root.current?.querySelector(\":focus-visible\")\n        )\n          setOpen(false);\n      },\n      animated ? 120 : 0,\n    );\n  };\n  useEffect(() => () => clearTimeout(timer.current), []);\n  useLayoutEffect(() => {\n    const state = geometry.current;\n    const render = () => {\n      gsap.set([panel.current, copy.current], {\n        x: state.x,\n        y: state.y,\n        width: state.width,\n        height: state.height,\n        borderRadius: state.radius,\n      });\n      gsap.set(decoration.current, { opacity: state.opacity });\n    };\n    gsap.killTweensOf(state);\n    if (open) state.opacity = 1;\n    const tween = gsap.to(state, {\n      x: open ? 2 : 6,\n      y: open ? -114 : 6,\n      width: open ? 40 : 32,\n      height: open ? 112 : 32,\n      radius: open ? 13 : 16,\n      duration: animated ? (open ? 0.45 : 0.29) : 0,\n      ease: open ? tooltipPourEase : \"power3.inOut\",\n      onUpdate: render,\n      onComplete: () => {\n        if (!open) {\n          state.opacity = 0;\n          render();\n        }\n      },\n    });\n    const fade = gsap.to(rail.current, {\n      opacity: open ? 1 : 0,\n      duration: animated ? 0.16 : 0,\n      delay: animated && open ? 0.1 : 0,\n    });\n    render();\n    return () => {\n      tween.kill();\n      fade.kill();\n    };\n  }, [open, animated]);\n  const level = muted ? 0 : volume;\n  return (\n    <div\n      ref={root}\n      className=\"relative z-20 flex items-center\"\n      data-volume-control\n      data-volume-open={open}\n      onPointerEnter={reveal}\n      onPointerLeave={dismiss}\n      onFocus={reveal}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget)) {\n          clearTimeout(timer.current);\n          setOpen(false);\n        }\n      }}\n    >\n      <VideoButton\n        label={muted ? \"Unmute\" : \"Mute\"}\n        aria-pressed={muted}\n        aria-keyshortcuts=\"m\"\n        onClick={() => {\n          reveal();\n          store.toggleMute();\n        }}\n      >\n        {muted ? <VolumeX /> : <Volume2 />}\n      </VideoButton>\n      <svg\n        aria-hidden\n        width=\"0\"\n        height=\"0\"\n        className=\"pointer-events-none absolute\"\n      >\n        <defs>\n          <filter\n            id={id}\n            x=\"-100%\"\n            y=\"-500%\"\n            width=\"300%\"\n            height=\"1000%\"\n            colorInterpolationFilters=\"sRGB\"\n          >\n            <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"5\" result=\"blur\" />\n            <feColorMatrix\n              in=\"blur\"\n              values=\"1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 22 -9\"\n              result=\"goo\"\n            />\n            <feComposite in=\"SourceGraphic\" in2=\"goo\" operator=\"atop\" />\n          </filter>\n        </defs>\n      </svg>\n      <div\n        ref={decoration}\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 opacity-0\"\n      >\n        <div className=\"absolute inset-0 opacity-15\">\n          <div\n            className=\"absolute inset-0\"\n            data-volume-gooey\n            style={{ filter: gooey && animated ? `url(#${id})` : undefined }}\n          >\n            <div className=\"absolute left-[6px] top-[6px] size-8 rounded-full bg-white\" />\n            <div ref={copy} className=\"absolute left-0 top-0 bg-white\" />\n          </div>\n        </div>\n        <div className=\"absolute left-[6px] top-[6px] size-8 rounded-full bg-white/15 backdrop-blur-xl\" />\n        <div\n          ref={panel}\n          data-volume-surface\n          className=\"absolute left-0 top-0 overflow-hidden bg-white/15 backdrop-blur-xl\"\n        >\n          <div\n            ref={rail}\n            className=\"absolute bottom-0 left-1/2 h-28 w-10 -translate-x-1/2 opacity-0\"\n          >\n            <div className=\"absolute bottom-4 left-1/2 top-4 w-1 -translate-x-1/2 rounded-full bg-white/30\">\n              <div\n                className=\"absolute inset-x-0 bottom-0 rounded-full bg-white\"\n                style={{ height: `${level * 100}%` }}\n              />\n              <div\n                className=\"absolute left-1/2 size-2.5 -translate-x-1/2 translate-y-1/2 rounded-full bg-white\"\n                style={{ bottom: `${level * 100}%` }}\n              />\n            </div>\n          </div>\n        </div>\n      </div>\n      <div\n        aria-hidden={!open}\n        inert={!open}\n        className=\"absolute -top-[114px] left-0 h-[114px] w-11 rounded-xl has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring\"\n        style={{ pointerEvents: open ? \"auto\" : \"none\" }}\n      >\n        <input\n          type=\"range\"\n          min={0}\n          max={1}\n          step={0.05}\n          value={level}\n          aria-label=\"Volume\"\n          aria-orientation=\"vertical\"\n          aria-valuetext={`${Math.round(level * 100)} percent`}\n          onChange={(e) => store.setVolume(Number(e.target.value))}\n          onPointerDown={(e) => {\n            dragging.current = true;\n            e.currentTarget.setPointerCapture(e.pointerId);\n          }}\n          onPointerUp={() => {\n            dragging.current = false;\n            dismiss();\n          }}\n          onPointerCancel={() => {\n            dragging.current = false;\n            dismiss();\n          }}\n          onLostPointerCapture={() => {\n            dragging.current = false;\n            dismiss();\n          }}\n          className=\"absolute inset-x-0 bottom-4 top-4 m-0 w-11 cursor-pointer opacity-0\"\n          style={{\n            writingMode: \"vertical-lr\",\n            direction: \"rtl\",\n            touchAction: \"none\",\n          }}\n        />\n      </div>\n    </div>\n  );\n}\nfunction VideoTime({ remaining = false }: { remaining?: boolean }) {\n  const time = useVideoState((s) => s.time);\n  const duration = useVideoState((s) => s.duration);\n  const live = useVideoState((s) => s.range.live);\n  return (\n    <span className=\"relative z-10 shrink-0 whitespace-nowrap px-1 text-[11px] tabular-nums text-white/85\">\n      {remaining && live\n        ? \"LIVE\"\n        : `${remaining ? \"−\" : \"\"}${formatVideoTime(remaining ? duration - time : time).padStart(5, \"0\")}`}\n    </span>\n  );\n}\nexport function VideoSeekbar({\n  onScrubbingChange,\n  onEngagementChange,\n}: {\n  onScrubbingChange?: (scrubbing: boolean) => void;\n  onEngagementChange?: (engaged: boolean) => void;\n}) {\n  const { store, video } = useVideoPlayer();\n  const time = useVideoState((s) => s.time);\n  const range = useVideoState((s) => s.range);\n  const buffered = useVideoState((s) => s.buffered);\n  const [scrub, setScrub] = useState<number | null>(null);\n  const [preview, setPreview] = useState<number | null>(null);\n  const [focused, setFocused] = useState(false);\n  const [hovered, setHovered] = useState(false);\n  const input = useRef<HTMLInputElement>(null);\n  const dragging = useRef(false);\n  const pointer = useRef<number | null>(null);\n  const span = range.end - range.start;\n  const percent = (value: number) =>\n    span > 0\n      ? Math.max(0, Math.min(100, ((value - range.start) / span) * 100))\n      : 0;\n  const finish = () => {\n    dragging.current = false;\n    setScrub(null);\n    onScrubbingChange?.(false);\n  };\n  useEffect(() => {\n    onEngagementChange?.(hovered || focused || scrub !== null);\n  }, [hovered, focused, scrub, onEngagementChange]);\n  const point = (clientX: number) => {\n    const rect = input.current!.getBoundingClientRect();\n    return (\n      range.start +\n      Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * span\n    );\n  };\n  // Re-map the held pointer as the timeline widens underneath it.\n  useEffect(() => {\n    const el = input.current;\n    if (!el) return;\n    const observer = new ResizeObserver(() => {\n      if (pointer.current === null) return;\n      const value = point(pointer.current);\n      if (dragging.current) {\n        setScrub(value);\n        store.seek(value);\n      } else if (hovered) setPreview(value);\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [span, range.start, hovered, store]);\n  const previewTime = scrub ?? preview ?? time;\n  const playedTime = scrub ?? time;\n  const showPreview =\n    span > 0 && (preview !== null || scrub !== null || focused);\n  return (\n    <div\n      data-seek-control\n      className=\"group/seek relative flex h-full min-h-8 w-full items-center\"\n      data-scrubbing={scrub !== null}\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") setHovered(true);\n      }}\n      onPointerLeave={() => {\n        setHovered(false);\n        setPreview(null);\n        if (!dragging.current) pointer.current = null;\n      }}\n    >\n      <div\n        data-seek-track\n        className=\"pointer-events-none absolute inset-x-0 overflow-hidden bg-white/15 backdrop-blur-xl group-has-[:focus-visible]/seek:outline-2 group-has-[:focus-visible]/seek:outline-offset-[3px] group-has-[:focus-visible]/seek:outline-ring\"\n        style={{\n          height: \"var(--timeline-track-height, 4px)\",\n          borderRadius: \"var(--timeline-radius, 2px)\",\n        }}\n      >\n        {buffered.map(([start, end], i) => (\n          <span\n            key={i}\n            data-seek-buffered\n            className=\"absolute h-full bg-white/[0.16]\"\n            style={{\n              left: `${percent(Math.max(start, playedTime))}%`,\n              width: `${Math.max(0, percent(end) - percent(Math.max(start, playedTime)))}%`,\n            }}\n          />\n        ))}\n        <span\n          data-seek-played\n          className=\"absolute inset-y-0 left-0\"\n          style={{\n            width: `${percent(scrub ?? time)}%`,\n            background:\n              \"rgb(255 255 255 / calc(1 - var(--timeline-progress, 0) * 0.6))\",\n          }}\n        />\n      </div>\n      {showPreview && (\n        <span\n          aria-hidden\n          data-seek-marker\n          className=\"pointer-events-none absolute w-px -translate-x-1/2 rounded-full\"\n          style={{\n            left: `${percent(previewTime)}%`,\n            height: \"var(--timeline-marker-height, 36px)\",\n            background:\n              \"color-mix(in srgb, var(--primary) calc(var(--timeline-progress, 0) * 100%), rgb(255 255 255 / 0.48))\",\n          }}\n        />\n      )}\n      {showPreview && (\n        <span\n          aria-hidden\n          data-seek-preview\n          className=\"pointer-events-none absolute -translate-x-1/2 whitespace-nowrap text-xs leading-4 tabular-nums\"\n          style={{\n            left: `clamp(44px, ${percent(previewTime)}%, calc(100% - 44px))`,\n            bottom: \"calc(50% + var(--timeline-label-offset, 32px))\",\n            color:\n              \"color-mix(in srgb, var(--primary) calc(var(--timeline-progress, 0) * 100%), white)\",\n          }}\n        >\n          {formatVideoTime(previewTime).padStart(5, \"0\")}\n          <span className=\"text-white/50\">\n            {\" \"}\n            /{\" \"}\n            {range.live ? \"LIVE\" : formatVideoTime(range.end).padStart(5, \"0\")}\n          </span>\n        </span>\n      )}\n      <input\n        ref={input}\n        type=\"range\"\n        aria-label={range.live ? \"Seek live window\" : \"Seek\"}\n        aria-valuetext={`${formatVideoTime(scrub ?? time)}${range.live ? \", live window\" : ` of ${formatVideoTime(range.end)}`}`}\n        min={range.start}\n        max={Math.max(range.start, range.end)}\n        step={0.1}\n        value={Math.min(range.end, Math.max(range.start, scrub ?? time))}\n        disabled={span <= 0}\n        className=\"absolute inset-0 m-0 h-full min-h-8 w-full cursor-grab touch-none appearance-none opacity-0 disabled:cursor-default [&::-webkit-slider-thumb]:h-8 [&::-webkit-slider-thumb]:w-px [&::-webkit-slider-thumb]:appearance-none [&::-moz-range-thumb]:h-8 [&::-moz-range-thumb]:w-px [&::-moz-range-thumb]:border-0\"\n        style={{ cursor: scrub !== null ? \"grabbing\" : undefined }}\n        onFocus={(e) => setFocused(e.currentTarget.matches(\":focus-visible\"))}\n        onBlur={() => {\n          setFocused(false);\n          setPreview(null);\n        }}\n        onPointerDown={(e) => {\n          if (e.button !== 0 || span <= 0) return;\n          e.preventDefault();\n          e.currentTarget.focus({ preventScroll: true });\n          setFocused(false);\n          e.currentTarget.setPointerCapture(e.pointerId);\n          dragging.current = true;\n          pointer.current = e.clientX;\n          const value = point(e.clientX);\n          setScrub(value);\n          store.seek(value);\n          onScrubbingChange?.(true);\n        }}\n        onPointerUp={(e) => {\n          if (e.pointerType === \"touch\") {\n            pointer.current = null;\n            setHovered(false);\n            setFocused(false);\n            setPreview(null);\n          }\n          finish();\n          if (e.currentTarget.hasPointerCapture(e.pointerId))\n            e.currentTarget.releasePointerCapture(e.pointerId);\n        }}\n        onPointerCancel={() => {\n          pointer.current = null;\n          setHovered(false);\n          setPreview(null);\n          finish();\n        }}\n        onLostPointerCapture={() => {\n          if (dragging.current) {\n            pointer.current = null;\n            setHovered(false);\n            setPreview(null);\n            finish();\n          }\n        }}\n        onPointerMove={(e) => {\n          pointer.current = e.clientX;\n          const value = point(e.clientX);\n          setPreview(value);\n          if (dragging.current) {\n            setScrub(value);\n            store.seek(value);\n          }\n        }}\n        onChange={(e) => {\n          const value = Number(e.target.value);\n          if (scrub !== null) setScrub(value);\n          store.seek(value);\n        }}\n        onKeyDown={(e) => {\n          if ([\"ArrowLeft\", \"ArrowRight\", \"Home\", \"End\"].includes(e.key)) {\n            e.preventDefault();\n            finish();\n            pointer.current = null;\n            setFocused(true);\n            setPreview(null);\n            store.seek(\n              e.key === \"Home\"\n                ? range.start\n                : e.key === \"End\"\n                  ? range.end\n                  : (video.current?.currentTime ?? time) +\n                    (e.key === \"ArrowRight\" ? 5 : -5),\n            );\n          }\n        }}\n      />\n    </div>\n  );\n}\n\nfunction GooeySurface({\n  host,\n  menu,\n  animated,\n  enabled,\n}: {\n  host: React.RefObject<HTMLDivElement | null>;\n  menu: boolean;\n  animated: boolean;\n  enabled: boolean;\n}) {\n  const id = `video-goo-${useId().replace(/:/g, \"\")}`;\n  const surface = useRef<HTMLDivElement>(null);\n  const decoration = useRef<HTMLDivElement>(null);\n  const base = useRef<HTMLDivElement>(null),\n    baseCopy = useRef<HTMLDivElement>(null);\n  const tip = useRef<HTMLDivElement>(null),\n    tipCopy = useRef<HTMLDivElement>(null);\n  const caption = useRef<HTMLDivElement>(null);\n  const firstLabel = useRef<HTMLSpanElement>(null),\n    secondLabel = useRef<HTMLSpanElement>(null);\n  const measure = useRef<HTMLSpanElement>(null);\n  const active = useRef<HTMLButtonElement | null>(null);\n  const phase = useRef<\"hidden\" | \"entering\" | \"shown\" | \"closing\">(\"hidden\");\n  const label = useRef(\"\");\n  const labelIndex = useRef(0);\n  const geometry = useRef({\n    x: 0,\n    y: 0,\n    width: 32,\n    height: 32,\n    radius: 16,\n    baseX: 0,\n    baseY: 0,\n    opacity: 0,\n  });\n\n  useLayoutEffect(() => {\n    const el = host.current;\n    if (!el || !decoration.current || !caption.current || !measure.current)\n      return;\n    const state = geometry.current;\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    let disposed = false;\n    const labels = [firstLabel.current!, secondLabel.current!];\n    gsap.set(labels, { x: 0, xPercent: -50 });\n    const writeLabel = (\n      node: HTMLElement,\n      value: string,\n      shortcut?: string,\n    ) => {\n      node.replaceChildren(document.createTextNode(value));\n      if (shortcut) {\n        const key = document.createElement(\"kbd\");\n        key.className =\n          \"ml-1.5 flex h-[18px] min-w-[18px] items-center justify-center rounded bg-white/20 px-1 font-sans text-[10px]\";\n        key.textContent = shortcut;\n        node.append(key);\n      }\n    };\n    // One persistent surface travels between targets. Filtered copies make the\n    // short liquid join; unfiltered foregrounds keep the settled edges crisp.\n    const render = () => {\n      const frame = {\n        x: state.x,\n        y: state.y,\n        width: state.width,\n        height: state.height,\n        borderRadius: state.radius,\n      };\n      gsap.set([tip.current, tipCopy.current], frame);\n      gsap.set([base.current, baseCopy.current], {\n        x: state.baseX,\n        y: state.baseY,\n      });\n      gsap.set(decoration.current, { opacity: state.opacity });\n      gsap.set(caption.current, {\n        x: state.x,\n        y: state.y,\n        width: state.width,\n        height: state.height,\n      });\n    };\n    const setPhase = (value: typeof phase.current) => {\n      phase.current = value;\n      decoration.current!.dataset.tooltipPhase = value;\n    };\n    const eligible = (target: EventTarget | null): HTMLButtonElement | null => {\n      const button =\n        target instanceof Element\n          ? (target.closest(\"button\") ??\n            target.closest(\"[data-volume-control]\")?.querySelector(\"button\"))\n          : null;\n      return button &&\n        el.contains(button) &&\n        !button.disabled &&\n        !button.closest(\"[data-volume-control]\") &&\n        !button.closest('[role=\"menu\"]') &&\n        button.getClientRects().length &&\n        button.getAttribute(\"aria-label\")\n        ? button\n        : null;\n    };\n    const hide = (immediate = false) => {\n      clearTimeout(timer);\n      active.current = null;\n      gsap.killTweensOf(state);\n      gsap.killTweensOf([caption.current, ...labels]);\n      if (phase.current === \"hidden\" || immediate || !animated) {\n        state.opacity = 0;\n        gsap.set(caption.current, { opacity: 0 });\n        setPhase(\"hidden\");\n        render();\n        return;\n      }\n      setPhase(\"closing\");\n      gsap.to(caption.current, { opacity: 0, duration: 0.1 });\n      gsap.to(state, {\n        x: state.baseX,\n        y: state.baseY,\n        width: 32,\n        height: 32,\n        radius: 16,\n        duration: 0.29,\n        ease: \"power3.inOut\",\n        onUpdate: render,\n        onComplete: () => {\n          state.opacity = 0;\n          setPhase(\"hidden\");\n          render();\n        },\n      });\n    };\n    const show = (button: HTMLButtonElement, instant = false) => {\n      if (menu || !eligible(button)) {\n        hide(true);\n        return;\n      }\n      clearTimeout(timer);\n      const rect = button.getBoundingClientRect(),\n        root = el.getBoundingClientRect();\n      const center = rect.left - root.left + rect.width / 2;\n      const baseX = center - 16,\n        baseY = rect.top - root.top + (rect.height - 32) / 2;\n      const value = button.getAttribute(\"aria-label\")!;\n      writeLabel(measure.current!, value, button.dataset.tooltipShortcut);\n      const textWidth = measure.current!.getBoundingClientRect().width;\n      const width = Math.min(root.width, textWidth + 24);\n      const x = Math.max(0, Math.min(root.width - width, center - width / 2));\n      // Leave a real gap at rest: the filtered neck stretches, then breaks.\n      const y = baseY - 34 - 12;\n      const entering = phase.current === \"hidden\";\n      const changed = label.current !== value;\n      if (\n        !instant &&\n        !entering &&\n        phase.current !== \"closing\" &&\n        active.current === button &&\n        !changed\n      )\n        return;\n      active.current = button;\n      gsap.killTweensOf(state);\n      gsap.killTweensOf([caption.current, ...labels]);\n      if (entering) {\n        Object.assign(state, {\n          x: baseX,\n          y: baseY,\n          width: 32,\n          height: 32,\n          radius: 16,\n          baseX,\n          baseY,\n          opacity: 1,\n        });\n        render();\n      } else state.opacity = 1;\n      const current = labels[labelIndex.current];\n      const next =\n        entering || !changed ? current : labels[1 - labelIndex.current];\n      next.style.width = `${textWidth}px`;\n      if (changed || entering) {\n        writeLabel(next, value, button.dataset.tooltipShortcut);\n        gsap.set(next, {\n          x: 0,\n          xPercent: -50,\n          opacity: 0,\n          y: animated && !instant ? 4 : 0,\n        });\n      }\n      if (next !== current) {\n        gsap.to(current, {\n          opacity: 0,\n          y: animated && !instant ? -4 : 0,\n          duration: animated && !instant ? 0.12 : 0,\n        });\n        labelIndex.current = 1 - labelIndex.current;\n      } else gsap.set(labels[1 - labelIndex.current], { opacity: 0 });\n      label.current = value;\n      gsap.to(next, {\n        opacity: 1,\n        y: 0,\n        duration: animated && !instant ? 0.18 : 0,\n        delay: animated && entering && !instant ? 0.1 : 0,\n      });\n      gsap.to(caption.current, {\n        opacity: 1,\n        duration: animated && !instant ? 0.18 : 0,\n        delay: animated && entering && !instant ? 0.1 : 0,\n      });\n      setPhase(entering ? \"entering\" : \"shown\");\n      gsap.to(state, {\n        baseX,\n        baseY,\n        duration: animated && !instant ? 0.2 : 0,\n        ease: \"power3.out\",\n        onUpdate: render,\n      });\n      gsap.to(state, {\n        x,\n        y,\n        width,\n        height: 34,\n        radius: 10,\n        duration: animated && !instant ? (entering ? 0.45 : 0.32) : 0,\n        ease: entering ? tooltipPourEase : \"power3.out\",\n        onUpdate: render,\n        onComplete: () => setPhase(\"shown\"),\n      });\n    };\n    const leave = () => {\n      clearTimeout(timer);\n      timer = setTimeout(\n        () => {\n          const focused = eligible(el.querySelector(\":focus-visible\"));\n          if (focused) show(focused);\n          else hide();\n        },\n        animated ? 120 : 0,\n      );\n    };\n    const over = (event: PointerEvent) => {\n      if (event.pointerType === \"touch\") return;\n      const button = eligible(event.target);\n      if (button) show(button);\n      else leave();\n    };\n    const focus = (event: FocusEvent) => {\n      const button = eligible(event.target);\n      if (button) show(button);\n      else leave();\n    };\n    const refresh = () => {\n      if (active.current) show(active.current, true);\n    };\n    const observer = new ResizeObserver(refresh);\n    observer.observe(el);\n    const mutations = new MutationObserver(() => {\n      if (active.current) show(active.current);\n    });\n    mutations.observe(el, {\n      subtree: true,\n      attributes: true,\n      attributeFilter: [\"aria-label\", \"disabled\"],\n    });\n    void document.fonts.ready.then(() => {\n      if (!disposed) refresh();\n    });\n    el.addEventListener(\"pointerover\", over);\n    el.addEventListener(\"pointerleave\", leave);\n    el.addEventListener(\"focusin\", focus);\n    el.addEventListener(\"focusout\", leave);\n    if (menu) hide(true);\n    else {\n      const target =\n        active.current ?? eligible(el.querySelector(\":focus-visible\"));\n      if (target) show(target, true);\n      else hide(true);\n    }\n    return () => {\n      disposed = true;\n      clearTimeout(timer);\n      observer.disconnect();\n      mutations.disconnect();\n      el.removeEventListener(\"pointerover\", over);\n      el.removeEventListener(\"pointerleave\", leave);\n      el.removeEventListener(\"focusin\", focus);\n      el.removeEventListener(\"focusout\", leave);\n      gsap.killTweensOf(state);\n      gsap.killTweensOf([caption.current, ...labels]);\n    };\n  }, [host, animated, menu]);\n  useLayoutEffect(() => {\n    if (!surface.current) return;\n    const tween = gsap.to(\n      surface.current.querySelectorAll(\"[data-menu-surface]\"),\n      {\n        opacity: menu ? 1 : 0,\n        scale: menu ? 1 : 0.2,\n        y: menu ? 0 : 32,\n        duration: animated ? (menu ? 0.42 : 0.22) : 0,\n        ease: \"back.out(1.4)\",\n        stagger: animated ? 0.035 : 0,\n      },\n    );\n    return () => {\n      tween.kill();\n    };\n  }, [menu, animated]);\n  return (\n    <>\n      <svg\n        aria-hidden\n        width=\"0\"\n        height=\"0\"\n        className=\"pointer-events-none absolute\"\n      >\n        <defs>\n          <filter\n            id={id}\n            x=\"-50%\"\n            y=\"-300%\"\n            width=\"200%\"\n            height=\"500%\"\n            colorInterpolationFilters=\"sRGB\"\n          >\n            <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"5\" result=\"blur\" />\n            <feColorMatrix\n              in=\"blur\"\n              values=\"1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 22 -9\"\n              result=\"goo\"\n            />\n            <feComposite in=\"SourceGraphic\" in2=\"goo\" operator=\"atop\" />\n          </filter>\n        </defs>\n      </svg>\n      <div\n        ref={decoration}\n        aria-hidden\n        data-tooltip-phase=\"hidden\"\n        className=\"pointer-events-none absolute inset-0 opacity-0\"\n      >\n        <div\n          className=\"absolute inset-0 opacity-15\"\n          style={{ filter: enabled && animated ? `url(#${id})` : undefined }}\n          data-gooey-layer={enabled && animated}\n        >\n          <div\n            ref={baseCopy}\n            className=\"absolute left-0 top-0 size-8 rounded-full bg-white\"\n          />\n          <div ref={tipCopy} className=\"absolute left-0 top-0 bg-white\" />\n        </div>\n        <div\n          ref={base}\n          className=\"absolute left-0 top-0 size-8 rounded-full bg-white/15 backdrop-blur-xl\"\n        />\n        <div\n          ref={tip}\n          data-hover-tooltip-surface\n          className=\"absolute left-0 top-0 bg-white/15 backdrop-blur-xl\"\n        />\n      </div>\n      <div\n        ref={caption}\n        aria-hidden\n        data-hover-tooltip-caption\n        className=\"pointer-events-none absolute left-0 top-0 z-20 overflow-visible text-[11px] text-white opacity-0\"\n      >\n        <span\n          ref={firstLabel}\n          className=\"absolute left-1/2 top-0 flex h-full items-center justify-center whitespace-nowrap opacity-0\"\n        />\n        <span\n          ref={secondLabel}\n          className=\"absolute left-1/2 top-0 flex h-full items-center justify-center whitespace-nowrap opacity-0\"\n        />\n      </div>\n      <span\n        ref={measure}\n        aria-hidden\n        className=\"pointer-events-none invisible absolute left-0 top-0 flex items-center whitespace-nowrap text-[11px]\"\n      />\n      <div\n        ref={surface}\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0 opacity-15\"\n        style={{ filter: enabled && animated ? `url(#${id})` : undefined }}\n      >\n        <div\n          data-menu-surface\n          className=\"absolute right-[54px] bottom-6 h-14 w-6 origin-bottom rounded-full bg-white\"\n          style={{ opacity: 0 }}\n        />\n        <div\n          data-menu-surface\n          className=\"absolute right-0 bottom-[60px] h-[min(280px,50cqh)] w-[min(268px,85cqw)] origin-bottom-right rounded-2xl bg-white\"\n          style={{ opacity: 0 }}\n        />\n      </div>\n    </>\n  );\n}\n\ntype SettingsPage = \"main\" | \"quality\" | \"speed\" | \"audio\" | \"captions\";\nexport function VideoSettings({\n  onOpenChange,\n}: {\n  onOpenChange?: (open: boolean) => void;\n}) {\n  const context = useVideoPlayer();\n  const { store, animated } = context;\n  const qualities = useVideoState((s) => s.qualities);\n  const selected = useVideoState((s) => s.selectedQuality);\n  const audio = useVideoState((s) => s.audio);\n  const captions = useVideoState((s) => s.captions);\n  const rate = useVideoState((s) => s.rate);\n  const range = useVideoState((s) => s.range);\n  const [open, setOpen] = useState(false);\n  const [page, setPage] = useState<SettingsPage>(\"main\");\n  const trigger = useRef<HTMLButtonElement>(null),\n    panel = useRef<HTMLDivElement>(null);\n  const id = useId();\n  const close = () => {\n    setOpen(false);\n    onOpenChange?.(false);\n    trigger.current?.focus({ preventScroll: true });\n  };\n  useLayoutEffect(() => {\n    if (!panel.current) return;\n    const el = panel.current;\n    const tween = gsap.to(el, {\n      opacity: open ? 1 : 0,\n      y: open || !animated ? 0 : 8,\n      duration: animated ? (open ? 0.24 : 0.14) : 0,\n      delay: animated && open ? 0.06 : 0,\n    });\n    if (open)\n      el.querySelector<HTMLElement>('[role^=\"menuitem\"]')?.focus({\n        preventScroll: true,\n      });\n    return () => {\n      tween.kill();\n    };\n  }, [open, page, animated]);\n  useEffect(() => {\n    if (!open) return;\n    const outside = (event: PointerEvent) => {\n      if (\n        event.target instanceof Node &&\n        !panel.current?.contains(event.target) &&\n        !trigger.current?.contains(event.target)\n      ) {\n        setOpen(false);\n        onOpenChange?.(false);\n      }\n    };\n    document.addEventListener(\"pointerdown\", outside);\n    return () => document.removeEventListener(\"pointerdown\", outside);\n  }, [open, onOpenChange]);\n  const choose = (fn: () => void) => {\n    fn();\n    close();\n  };\n  const option = (\n    label: string,\n    checked: boolean,\n    action: () => void,\n    key: string,\n  ) => (\n    <button\n      key={key}\n      type=\"button\"\n      role=\"menuitemradio\"\n      aria-checked={checked}\n      onClick={() => choose(action)}\n      className=\"flex min-h-11 w-full items-center justify-between gap-3 rounded-lg px-3 text-left text-xs hover:bg-white/10 focus-visible:bg-white/15 focus-visible:outline-none\"\n    >\n      <span>{label}</span>\n      {checked && <Check className=\"size-3.5 shrink-0\" />}\n    </button>\n  );\n  return (\n    <>\n      <VideoButton\n        ref={trigger}\n        label=\"Playback settings\"\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        aria-controls={open ? id : undefined}\n        onClick={() => {\n          const next = !open;\n          setOpen(next);\n          setPage(\"main\");\n          onOpenChange?.(next);\n        }}\n      >\n        <Settings2 />\n      </VideoButton>\n      {\n        <div\n          ref={panel}\n          id={id}\n          role=\"menu\"\n          aria-label=\"Playback settings\"\n          aria-hidden={!open}\n          inert={!open}\n          style={{ opacity: 0, pointerEvents: open ? \"auto\" : \"none\" }}\n          className=\"absolute right-0 bottom-[60px] z-30 flex h-[min(280px,50cqh)] w-[min(268px,85cqw)] flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/15 backdrop-blur-xl p-2 text-white\"\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") {\n              e.preventDefault();\n              e.stopPropagation();\n              if (page === \"main\") close();\n              else setPage(\"main\");\n            }\n            if ([\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"].includes(e.key)) {\n              e.preventDefault();\n              e.stopPropagation();\n              const items = Array.from(\n                e.currentTarget.querySelectorAll<HTMLElement>(\n                  '[role^=\"menuitem\"]:not(:disabled)',\n                ),\n              );\n              const index = items.indexOf(\n                document.activeElement as HTMLElement,\n              );\n              items[\n                e.key === \"Home\"\n                  ? 0\n                  : e.key === \"End\"\n                    ? items.length - 1\n                    : (index +\n                        (e.key === \"ArrowDown\" ? 1 : -1) +\n                        items.length) %\n                      items.length\n              ]?.focus();\n            }\n            if (e.key === \"Tab\") {\n              close();\n            }\n          }}\n        >\n          <div className=\"mb-1 flex shrink-0 items-center justify-between border-b border-white/10 pb-1 text-[11px] text-white/60\">\n            <button\n              type=\"button\"\n              role=\"menuitem\"\n              aria-label={\n                page === \"main\" ? \"Close settings\" : \"Back to settings\"\n              }\n              onClick={() => (page === \"main\" ? close() : setPage(\"main\"))}\n              className=\"flex h-10 items-center gap-2 rounded-lg px-2 focus-visible:outline-2 focus-visible:outline-ring\"\n            >\n              {page === \"main\" ? (\n                <Settings2 className=\"size-3.5\" />\n              ) : (\n                <ChevronLeft className=\"size-3.5\" />\n              )}\n              <span className=\"capitalize\">\n                {page === \"main\" ? \"Playback\" : page}\n              </span>\n            </button>\n            <span className=\"pr-2\">\n              {page === \"quality\"\n                ? \"Buffered video may switch later\"\n                : \"Make it yours\"}\n            </span>\n          </div>\n          <div className=\"min-h-0 overflow-y-auto overscroll-contain\">\n            {page === \"main\" && (\n              <>\n                <button\n                  type=\"button\"\n                  role=\"menuitem\"\n                  disabled={\n                    context.fullscreen ||\n                    (!context.expanded && !context.canExpand)\n                  }\n                  onClick={() => choose(context.toggleExpanded)}\n                  className=\"flex min-h-11 w-full items-center justify-between rounded-lg px-3 text-left text-xs hover:bg-white/10 focus-visible:bg-white/15 focus-visible:outline-none disabled:opacity-40\"\n                >\n                  <span>\n                    {context.expanded\n                      ? \"Exit cinematic mode\"\n                      : \"Cinematic mode\"}\n                  </span>\n                  <Expand className=\"size-3.5\" />\n                </button>\n                <button\n                  type=\"button\"\n                  role=\"menuitem\"\n                  disabled={!context.canFullscreen || context.expanded}\n                  onClick={() => choose(context.toggleFullscreen)}\n                  className=\"flex min-h-11 w-full items-center justify-between rounded-lg px-3 text-left text-xs hover:bg-white/10 focus-visible:bg-white/15 focus-visible:outline-none disabled:opacity-40\"\n                >\n                  <span>\n                    {context.fullscreen\n                      ? \"Exit browser fullscreen\"\n                      : \"Browser fullscreen\"}\n                  </span>\n                  <VideoFullscreenIcon\n                    active={context.fullscreen}\n                    animated={animated}\n                  />\n                </button>\n                {(\n                  [\n                    [\n                      \"quality\",\n                      \"Quality\",\n                      qualities.length\n                        ? selected === \"auto\"\n                          ? \"Auto\"\n                          : qualities.find((q) => q.id === selected)?.label\n                        : \"Managed by browser\",\n                    ],\n                    [\"speed\", \"Playback speed\", `${rate}×`],\n                    [\n                      \"audio\",\n                      \"Audio\",\n                      audio.find((t) => t.active)?.label ?? \"Default\",\n                    ],\n                    [\n                      \"captions\",\n                      \"Captions\",\n                      captions.length\n                        ? (captions.find((t) => t.active)?.label ?? \"Off\")\n                        : \"Unavailable\",\n                    ],\n                  ] as const\n                ).map(([key, label, value]) => (\n                  <button\n                    key={key}\n                    type=\"button\"\n                    role=\"menuitem\"\n                    disabled={\n                      (key === \"quality\" && !qualities.length) ||\n                      (key === \"audio\" && !audio.length) ||\n                      (key === \"captions\" && !captions.length)\n                    }\n                    onClick={() => setPage(key)}\n                    className=\"flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-xs hover:bg-white/10 focus-visible:bg-white/15 focus-visible:outline-none disabled:opacity-40\"\n                  >\n                    <span>{label}</span>\n                    <span className=\"ml-auto max-w-28 truncate text-white/50\">\n                      {value}\n                    </span>\n                    <ChevronRight className=\"size-3\" />\n                  </button>\n                ))}\n                <div className=\"@min-[560px]/player-layout:hidden\">\n                  <button\n                    type=\"button\"\n                    role=\"menuitem\"\n                    disabled={!context.canPip}\n                    onClick={() => choose(context.togglePip)}\n                    className=\"min-h-11 w-full rounded-lg px-3 text-left text-xs focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-40\"\n                  >\n                    Picture-in-picture{!context.canPip && \" unavailable\"}\n                  </button>\n                  <label className=\"flex min-h-11 items-center gap-3 px-3 text-xs\">\n                    Volume\n                    <input\n                      aria-label=\"Volume in settings\"\n                      type=\"range\"\n                      min={0}\n                      max={1}\n                      step={0.05}\n                      defaultValue={store.getSnapshot().volume}\n                      onChange={(e) => store.setVolume(Number(e.target.value))}\n                      className=\"w-28 accent-white\"\n                    />\n                  </label>\n                </div>\n                {range.live && (\n                  <button\n                    type=\"button\"\n                    role=\"menuitem\"\n                    onClick={() => choose(() => store.seek(range.end))}\n                    className=\"min-h-11 w-full rounded-lg px-3 text-left text-xs focus-visible:outline-2 focus-visible:outline-ring\"\n                  >\n                    Jump to live edge\n                  </button>\n                )}\n              </>\n            )}\n            {page === \"quality\" && (\n              <>\n                {option(\n                  \"Auto · adaptive\",\n                  selected === \"auto\",\n                  () => store.setQuality(\"auto\"),\n                  \"auto\",\n                )}\n                {qualities.map((q) =>\n                  option(\n                    `${q.label}${q.active ? \" · active\" : \"\"}`,\n                    selected === q.id,\n                    () => store.setQuality(q.id),\n                    q.id,\n                  ),\n                )}\n              </>\n            )}\n            {page === \"speed\" &&\n              [0.5, 0.75, 1, 1.25, 1.5, 2].map((r) =>\n                option(\n                  `${r}×${r === 1 ? \" · Normal\" : \"\"}`,\n                  rate === r,\n                  () => store.setPlaybackRate(r),\n                  String(r),\n                ),\n              )}\n            {page === \"audio\" &&\n              audio.map((t) =>\n                option(\n                  t.label,\n                  t.active,\n                  () => store.setAudioTrack(t.id),\n                  t.id,\n                ),\n              )}\n            {page === \"captions\" && (\n              <>\n                {option(\n                  \"Off\",\n                  !captions.some((t) => t.active),\n                  () => store.setTextTrack(\"off\"),\n                  \"off\",\n                )}\n                {captions.map((t) =>\n                  option(\n                    t.label,\n                    t.active,\n                    () => store.setTextTrack(t.id),\n                    t.id,\n                  ),\n                )}\n              </>\n            )}\n          </div>\n        </div>\n      }\n    </>\n  );\n}\n\nexport function VideoControls() {\n  const context = useVideoPlayer();\n  const { frame, animated, gooey } = context;\n  const paused = useVideoState((s) => s.paused);\n  const error = useVideoState((s) => s.error);\n  const captions = useVideoState((s) => s.captions);\n  const [active, setActive] = useState(true),\n    [menu, setMenu] = useState(false),\n    [scrubbing, setScrubbing] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const dock = useRef<HTMLDivElement>(null),\n    overlay = useRef<HTMLDivElement>(null);\n  const seekSlot = useRef<HTMLDivElement>(null),\n    timeline = useRef<HTMLDivElement>(null);\n  const [timelineExpanded, setTimelineExpanded] = useState(false);\n  const timelineEngaged = useRef(false);\n  const pointerInControls = useRef(false);\n  const touchInteraction = useRef(false);\n  const timelineOpen = useRef(false);\n  timelineOpen.current = timelineExpanded && !menu;\n  const timelineDismiss = useRef(0);\n  const cancelTimelineDismiss = useCallback(() => {\n    timelineDismiss.current++;\n  }, []);\n  const dismissTimeline = useCallback(() => {\n    const request = ++timelineDismiss.current;\n    // Let the same pointer event update the shared hover region first. This\n    // avoids gap flicker without holding the expanded state behind a timer.\n    queueMicrotask(() => {\n      if (\n        request === timelineDismiss.current &&\n        !timelineEngaged.current &&\n        !pointerInControls.current &&\n        (touchInteraction.current || !dock.current?.matches(\":hover\")) &&\n        (touchInteraction.current ||\n          !dock.current?.querySelector(\":focus-visible\"))\n      )\n        setTimelineExpanded(false);\n    });\n  }, []);\n  const engageTimeline = useCallback(\n    (engaged: boolean) => {\n      timelineEngaged.current = engaged;\n      cancelTimelineDismiss();\n      if (engaged) setTimelineExpanded(true);\n      else dismissTimeline();\n    },\n    [dismissTimeline, cancelTimelineDismiss],\n  );\n  useEffect(() => cancelTimelineDismiss, [cancelTimelineDismiss]);\n  useEffect(() => {\n    const el = frame.current;\n    if (!el) return;\n    const move = (event: PointerEvent) => {\n      if (event.pointerType === \"touch\") {\n        touchInteraction.current = true;\n        pointerInControls.current = false;\n        return;\n      }\n      touchInteraction.current = false;\n      const rail = timeline.current?.getBoundingClientRect(),\n        row = dock.current?.getBoundingClientRect();\n      pointerInControls.current = !!(\n        timelineOpen.current &&\n        rail &&\n        row &&\n        event.clientX >= Math.min(rail.left, row.left) - 2 &&\n        event.clientX <= Math.max(rail.right, row.right) + 2 &&\n        event.clientY >= Math.min(rail.top, row.top) - 2 &&\n        event.clientY <= Math.max(rail.bottom, row.bottom) + 2\n      );\n      if (pointerInControls.current) cancelTimelineDismiss();\n      else if (timelineOpen.current) dismissTimeline();\n    };\n    const leave = () => {\n      pointerInControls.current = false;\n      dismissTimeline();\n    };\n    el.addEventListener(\"pointermove\", move);\n    el.addEventListener(\"pointerleave\", leave);\n    return () => {\n      el.removeEventListener(\"pointermove\", move);\n      el.removeEventListener(\"pointerleave\", leave);\n    };\n  }, [frame, dismissTimeline, cancelTimelineDismiss]);\n  useVideoTimeline(\n    overlay,\n    dock,\n    seekSlot,\n    timeline,\n    timelineExpanded && !menu,\n    animated,\n  );\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const pointerFocus = useRef(false);\n  const visible =\n    active ||\n    paused ||\n    !!error ||\n    menu ||\n    scrubbing ||\n    focused ||\n    timelineExpanded;\n  useEffect(() => {\n    const el = frame.current;\n    if (!el) return;\n    const reveal = (event?: PointerEvent) => {\n      setActive(true);\n      clearTimeout(timer.current);\n      if (event?.pointerType === \"touch\")\n        timer.current = setTimeout(() => setActive(false), 2400);\n    };\n    const leave = (event: PointerEvent) => {\n      if (event.pointerType === \"touch\") return;\n      clearTimeout(timer.current);\n      timer.current = setTimeout(() => setActive(false), 120);\n    };\n    const focus = () => {\n      setFocused(\n        !pointerFocus.current &&\n          (el.matches(\":focus-visible\") ||\n            !!el.querySelector(\":focus-visible\")),\n      );\n      setActive(true);\n    };\n    const pointerDown = (event: PointerEvent) => {\n      touchInteraction.current = event.pointerType === \"touch\";\n      pointerFocus.current = true;\n      setFocused(false);\n      reveal(event);\n    };\n    const keyboard = () => {\n      touchInteraction.current = false;\n      pointerFocus.current = false;\n      if (el.contains(el.ownerDocument.activeElement)) setFocused(true);\n    };\n    const blur = (e: FocusEvent) => {\n      if (!(e.relatedTarget instanceof Node) || !el.contains(e.relatedTarget))\n        setFocused(false);\n    };\n    el.addEventListener(\"pointerenter\", reveal);\n    el.addEventListener(\"pointermove\", reveal);\n    el.addEventListener(\"pointerdown\", pointerDown, true);\n    el.addEventListener(\"pointerleave\", leave);\n    el.addEventListener(\"focusin\", focus);\n    el.addEventListener(\"focusout\", blur);\n    el.ownerDocument.addEventListener(\"keydown\", keyboard, true);\n    if (!el.matches(\":hover\"))\n      timer.current = setTimeout(() => setActive(false), 2400);\n    return () => {\n      clearTimeout(timer.current);\n      el.removeEventListener(\"pointerenter\", reveal);\n      el.removeEventListener(\"pointermove\", reveal);\n      el.removeEventListener(\"pointerdown\", pointerDown, true);\n      el.removeEventListener(\"pointerleave\", leave);\n      el.removeEventListener(\"focusin\", focus);\n      el.removeEventListener(\"focusout\", blur);\n      el.ownerDocument.removeEventListener(\"keydown\", keyboard, true);\n    };\n  }, [frame]);\n  useLayoutEffect(() => {\n    if (!overlay.current) return;\n    const tween = gsap.to(overlay.current, {\n      opacity: visible ? 1 : 0,\n      y: visible ? 0 : 8,\n      duration: animated ? 0.32 : 0,\n      ease: \"power3.out\",\n      overwrite: true,\n    });\n    return () => {\n      tween.kill();\n    };\n  }, [visible, animated]);\n  return (\n    <div\n      ref={overlay}\n      data-timeline-expanded={timelineExpanded && !menu}\n      aria-hidden={!visible}\n      inert={!visible}\n      className=\"absolute inset-x-0 bottom-0 z-20 rounded-b-[inherit] bg-gradient-to-t from-black/65 to-transparent px-3 pb-3 pt-12 @min-[640px]/player-layout:px-8 @min-[640px]/player-layout:pb-5\"\n      style={{ pointerEvents: \"none\" }}\n    >\n      <div\n        ref={dock}\n        data-video-dock\n        onPointerEnter={cancelTimelineDismiss}\n        onPointerLeave={dismissTimeline}\n        onBlur={dismissTimeline}\n        style={{ pointerEvents: \"none\" }}\n        className=\"relative z-20 flex flex-nowrap items-center gap-x-1\"\n      >\n        <GooeySurface\n          host={dock}\n          menu={menu}\n          animated={animated}\n          enabled={gooey}\n        />\n        <div\n          data-controls-group\n          className=\"relative flex shrink-0 items-center\"\n          style={{ pointerEvents: visible ? \"auto\" : \"none\" }}\n        >\n          <VideoPlayButton />\n          <VideoVolume />\n          <VideoTime />\n        </div>\n        <div ref={seekSlot} aria-hidden className=\"mx-1 h-8 min-w-0 flex-1\" />\n        <div\n          data-controls-group\n          className=\"ml-auto flex shrink-0 items-center @min-[640px]/player-layout:ml-0\"\n          style={{ pointerEvents: visible ? \"auto\" : \"none\" }}\n        >\n          <span className=\"hidden @min-[640px]/player-layout:contents\">\n            <VideoTime remaining />\n          </span>\n          {captions.length > 0 && (\n            <VideoButton\n              label={\n                captions.some((t) => t.active)\n                  ? \"Turn captions off\"\n                  : \"Turn captions on\"\n              }\n              className=\"hidden @min-[640px]/player-layout:inline-flex\"\n              aria-pressed={captions.some((t) => t.active)}\n              onClick={() =>\n                context.store.setTextTrack(\n                  captions.some((t) => t.active) ? \"off\" : captions[0].id,\n                )\n              }\n            >\n              <Captions />\n            </VideoButton>\n          )}\n          <VideoButton\n            label={\n              context.pip\n                ? \"Exit picture-in-picture\"\n                : context.canPip\n                  ? \"Picture-in-picture\"\n                  : \"Picture-in-picture unavailable\"\n            }\n            disabled={!context.canPip}\n            className=\"hidden @min-[560px]/player-layout:inline-flex\"\n            onClick={context.togglePip}\n          >\n            <PictureInPicture2 />\n          </VideoButton>\n          <VideoSettings onOpenChange={setMenu} />\n          <VideoFullscreenButton />\n        </div>\n      </div>\n      <div\n        ref={timeline}\n        data-video-timeline\n        className=\"absolute z-10\"\n        style={{ pointerEvents: visible ? \"auto\" : \"none\" }}\n      >\n        <VideoSeekbar\n          onScrubbingChange={setScrubbing}\n          onEngagementChange={engageTimeline}\n        />\n      </div>\n    </div>\n  );\n}\n\nexport function VideoStatus({\n  title,\n  controls,\n}: {\n  title: string;\n  controls: boolean;\n}) {\n  const { store, togglePlayback, animated } = useVideoPlayer();\n  const paused = useVideoState((s) => s.paused),\n    buffering = useVideoState((s) => s.buffering),\n    error = useVideoState((s) => s.error),\n    notice = useVideoState((s) => s.notice),\n    ready = useVideoState((s) => s.ready);\n  if (error)\n    return (\n      <div className=\"absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 rounded-[inherit] bg-black/60 backdrop-blur-xl px-6 text-center\">\n        <p role=\"alert\" className=\"max-w-sm text-sm\">\n          {error.message}\n        </p>\n        {error.retryable && (\n          <button\n            type=\"button\"\n            onClick={() => store.retry()}\n            className=\"min-h-11 rounded-full border border-white/25 px-5 text-xs focus-visible:outline-2 focus-visible:outline-ring\"\n          >\n            Retry video\n          </button>\n        )}\n      </div>\n    );\n  return (\n    <>\n      {controls && (\n        <button\n          type=\"button\"\n          aria-label={`${paused ? \"Play\" : \"Pause\"} ${title}`}\n          disabled={!ready}\n          onClick={togglePlayback}\n          className=\"absolute inset-0 z-10 rounded-[inherit] bg-transparent outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\"\n        />\n      )}\n      {buffering && (\n        <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center\">\n          <span\n            role=\"status\"\n            className=\"flex items-center gap-2 rounded-full bg-white/15 backdrop-blur-xl px-4 py-2 text-xs\"\n          >\n            <LoaderCircle\n              className={`size-4 ${animated ? \"animate-spin\" : \"\"}`}\n            />\n            Loading video\n          </span>\n        </div>\n      )}\n      <p\n        role=\"status\"\n        className={\n          notice\n            ? \"absolute left-4 top-4 z-30 rounded-lg bg-white/15 backdrop-blur-xl px-3 py-2 text-xs\"\n            : \"sr-only\"\n        }\n      >\n        {notice}\n      </p>\n    </>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-motion.ts",
      "content": "\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type RefObject,\n} from \"react\";\nimport { gsap } from \"gsap\";\nimport { CustomEase } from \"gsap/CustomEase\";\n\ngsap.registerPlugin(CustomEase);\n// Slow departure, decisive middle, long settle. Geometry and icons use\n// the same curve at different durations.\nexport const videoFullscreenMotion = {\n  duration: 0.9,\n  iconDuration: 0.45,\n  ease: CustomEase.create(\"cavemio-video-fullscreen\", \"0.7,0,0.16,1\"),\n};\n// Use the same 300ms curve for entry and exit, without a hover-out hold.\nconst timelineEase = CustomEase.create(\n  \"cavemio-video-timeline\",\n  \"0.25,0.1,0.35,1\",\n);\n\n/** Keep a single seek input while its measured slot opens into a separate row. */\nexport function useVideoTimeline(\n  overlay: RefObject<HTMLDivElement | null>,\n  dock: RefObject<HTMLDivElement | null>,\n  slot: RefObject<HTMLDivElement | null>,\n  timeline: RefObject<HTMLDivElement | null>,\n  expanded: boolean,\n  animated: boolean,\n) {\n  const state = useRef({ progress: 0 });\n  useLayoutEffect(() => {\n    const host = overlay.current,\n      controls = dock.current,\n      placeholder = slot.current,\n      surface = timeline.current;\n    if (!host || !controls || !placeholder || !surface) return;\n    const geometry = {\n      left: 0,\n      top: 0,\n      width: 0,\n      fullLeft: 0,\n      fullWidth: 0,\n      lift: 44,\n      height: 44,\n      track: 28,\n    };\n    const render = () => {\n      // Keep the rail's center anchored. Its\n      // width, thickness and controls share exactly one progress value, with\n      // no lead or delayed interval in either direction. Controls stay above\n      // the decorative rail while their hit targets pass through its bounds.\n      const p = state.current.progress;\n      const mix = (a: number, b: number) => a + (b - a) * p;\n      gsap.set(controls, {\n        y: -geometry.lift * (1 - p),\n      });\n      gsap.set(surface, {\n        autoRound: false,\n        left: mix(geometry.left, geometry.fullLeft),\n        top: geometry.top - geometry.lift + 16 - mix(32, geometry.height) / 2,\n        width: mix(geometry.width, geometry.fullWidth),\n        height: mix(32, geometry.height),\n        \"--timeline-progress\": p,\n        \"--timeline-track-height\": `${mix(4, geometry.track)}px`,\n        \"--timeline-radius\": `${mix(2, 8)}px`,\n        \"--timeline-marker-height\": `${mix(36, geometry.track + 24)}px`,\n        \"--timeline-label-offset\": `${mix(32, geometry.track / 2 + 20)}px`,\n      });\n    };\n    const measure = () => {\n      const root = host.getBoundingClientRect(),\n        row = controls.getBoundingClientRect(),\n        gap = placeholder.getBoundingClientRect();\n      const y = Number(gsap.getProperty(controls, \"y\")) || 0;\n      Object.assign(geometry, {\n        left: gap.left - root.left,\n        top: gap.top - root.top - y,\n        width: gap.width,\n        fullLeft: row.left - root.left,\n        fullWidth: row.width,\n        // Idle rail and buttons share a center. Reserve enough travel for the\n        // expanded half-height plus the existing 8px gap, at every viewport.\n        lift: row.height / 2 + geometry.track / 2 + 8,\n        height: 44,\n        track: 28,\n      });\n      render();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(host);\n    observer.observe(placeholder);\n    if (host.parentElement) observer.observe(host.parentElement);\n    const tween = gsap.to(state.current, {\n      progress: expanded ? 1 : 0,\n      duration: animated\n        ? 0.3 * Math.abs((expanded ? 1 : 0) - state.current.progress)\n        : 0,\n      // Apply the forward curve toward either target. Playing its timeline\n      // backward would start exit at the flat settling tail and feel delayed.\n      ease: timelineEase,\n      onUpdate: render,\n    });\n    return () => {\n      tween.kill();\n      observer.disconnect();\n    };\n  }, [overlay, dock, slot, timeline, expanded, animated]);\n}\n\nexport function useVideoReducedMotion(force = false) {\n  const [reduced, setReduced] = useState(true);\n  useEffect(() => {\n    const query = matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const update = () => setReduced(query.matches);\n    update();\n    query.addEventListener(\"change\", update);\n    return () => query.removeEventListener(\"change\", update);\n  }, []);\n  return force || reduced;\n}\n\nconst locks = new WeakMap<Document, { count: number; overflow: string }>();\nfunction lockScroll(doc: Document) {\n  const entry = locks.get(doc) ?? {\n    count: 0,\n    overflow: doc.documentElement.style.overflow,\n  };\n  entry.count++;\n  locks.set(doc, entry);\n  doc.documentElement.style.overflow = \"hidden\";\n  return () => {\n    if (--entry.count === 0) {\n      doc.documentElement.style.overflow = entry.overflow;\n      locks.delete(doc);\n    }\n  };\n}\n\n/** GSAP layout interpolation: animate geometry, never scale readable controls.\n * A manual top-layer popover keeps the same video node above transformed ancestors.\n */\nexport function useVideoExpansion(\n  frame: RefObject<HTMLDivElement | null>,\n  placeholder: RefObject<HTMLDivElement | null>,\n  expanded: boolean,\n  animated: boolean,\n  close: () => void,\n) {\n  const animation = useRef<gsap.core.Tween | null>(null);\n  const expandedRef = useRef(false);\n  const closeRef = useRef(close);\n  closeRef.current = close;\n  const savedFocus = useRef<HTMLElement | null>(null);\n  const release = useRef<(() => void) | null>(null);\n\n  useLayoutEffect(() => {\n    const el = frame.current;\n    const slot = placeholder.current;\n    if (!el || !slot) return;\n    const wasExpanded = expandedRef.current;\n    if (!expanded && !wasExpanded && !animation.current) return;\n    const rect = el.getBoundingClientRect(); // Capture before cancelling an interrupted tween.\n    animation.current?.kill();\n    expandedRef.current = expanded;\n    if (expanded && !wasExpanded) {\n      // A reversal still owns the original focus and scroll lock.\n      if (!release.current) {\n        savedFocus.current = el.ownerDocument.activeElement as HTMLElement;\n        release.current = lockScroll(el.ownerDocument);\n      }\n      try {\n        el.showPopover?.();\n      } catch {\n        /* fixed-position fallback */\n      }\n    }\n    const inline = slot.getBoundingClientRect();\n    const target = expanded\n      ? {\n          x: 0,\n          y: 0,\n          width: window.innerWidth,\n          height: window.innerHeight,\n          borderRadius: 0,\n          \"--video-backdrop\": 1,\n        }\n      : {\n          x: inline.left,\n          y: inline.top,\n          width: inline.width,\n          height: inline.height,\n          borderRadius: 20,\n          \"--video-backdrop\": 0,\n        };\n    gsap.set(el, {\n      position: \"fixed\",\n      inset: \"auto\",\n      margin: 0,\n      zIndex: 1000,\n    });\n    // Set the inset shorthand first: rendering it in the same GSAP set as\n    // left/top can reset those longhands to auto and jump to the origin.\n    gsap.set(el, {\n      left: 0,\n      top: 0,\n      x: rect.left,\n      y: rect.top,\n      force3D: true,\n      width: rect.width,\n      height: rect.height,\n    });\n    const finish = () => {\n      animation.current = null;\n      if (!expandedRef.current) {\n        try {\n          el.hidePopover?.();\n        } catch {\n          /* no top-layer API */\n        }\n        gsap.set(el, {\n          clearProps:\n            \"position,inset,margin,zIndex,left,top,width,height,transform,borderRadius,--video-backdrop\",\n        });\n        release.current?.();\n        release.current = null;\n        savedFocus.current?.focus({ preventScroll: true });\n      }\n    };\n    if (animated)\n      animation.current = gsap.to(el, {\n        ...target,\n        duration: videoFullscreenMotion.duration,\n        ease: videoFullscreenMotion.ease,\n        overwrite: true,\n        onComplete: finish,\n      });\n    else {\n      gsap.set(el, target);\n      finish();\n    }\n  }, [expanded, animated, frame, placeholder]);\n\n  useEffect(() => {\n    const el = frame.current;\n    if (!el || !expanded) return;\n    const doc = el.ownerDocument;\n    // Inert siblings along the ancestor path without reparenting the video.\n    const inert: { el: HTMLElement; value: boolean }[] = [];\n    let branch: HTMLElement = el;\n    while (branch.parentElement) {\n      for (const sibling of Array.from(branch.parentElement.children)) {\n        if (sibling !== branch && sibling instanceof HTMLElement) {\n          inert.push({ el: sibling, value: sibling.inert });\n          sibling.inert = true;\n        }\n      }\n      branch = branch.parentElement;\n      if (branch === doc.body) break;\n    }\n    const key = (event: KeyboardEvent) => {\n      if (event.defaultPrevented) return;\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        closeRef.current();\n      }\n      if (event.key === \"Tab\") {\n        const nodes = Array.from(\n          el.querySelectorAll<HTMLElement>(\n            'button:not(:disabled),input:not(:disabled),select:not(:disabled),[tabindex=\"0\"]',\n          ),\n        ).filter(\n          (node) =>\n            !node.closest(\"[inert]\") && node.getClientRects().length > 0,\n        );\n        const first = nodes[0],\n          last = nodes.at(-1);\n        if (\n          event.shiftKey &&\n          (doc.activeElement === first || doc.activeElement === el)\n        ) {\n          event.preventDefault();\n          last?.focus();\n        } else if (!event.shiftKey && doc.activeElement === last) {\n          event.preventDefault();\n          first?.focus();\n        }\n      }\n    };\n    const resize = () => {\n      animation.current?.kill();\n      animation.current = null;\n      gsap.set(el, {\n        x: 0,\n        y: 0,\n        width: window.innerWidth,\n        height: window.innerHeight,\n        borderRadius: 0,\n        \"--video-backdrop\": 1,\n      });\n    };\n    el.focus({ preventScroll: true });\n    doc.addEventListener(\"keydown\", key);\n    window.addEventListener(\"resize\", resize);\n    return () => {\n      doc.removeEventListener(\"keydown\", key);\n      window.removeEventListener(\"resize\", resize);\n      inert.forEach(({ el, value }) => {\n        el.inert = value;\n      });\n    };\n  }, [expanded, frame]);\n  useEffect(\n    () => () => {\n      animation.current?.kill();\n      release.current?.();\n      release.current = null;\n      savedFocus.current?.focus({ preventScroll: true });\n    },\n    [],\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-diagnostics.tsx",
      "content": "\"use client\";\nimport { useState, useSyncExternalStore } from \"react\";\nimport { useVideoPlayer, useVideoState } from \"./video-player-context\";\nimport { detectVideoFormat } from \"./video-player-utils\";\nimport type { VideoFormat } from \"./video-player-types\";\n\nconst number = (value: number | null | undefined, unit = \"\", decimals = 1) =>\n  value == null || !Number.isFinite(value)\n    ? \"N/A\"\n    : `${value.toFixed(decimals)}${unit}`;\nexport default function PlaybackDiagnostics({\n  src,\n  format,\n}: {\n  src: string;\n  format?: VideoFormat;\n}) {\n  const [open, setOpen] = useState(true);\n  return (\n    <section className=\"mt-4 rounded-xl border border-border bg-background text-foreground\">\n      <button\n        type=\"button\"\n        aria-expanded={open}\n        onClick={() => setOpen(!open)}\n        className=\"flex min-h-11 w-full items-center justify-between px-4 text-left text-xs font-medium focus-visible:outline-2 focus-visible:outline-ring\"\n      >\n        Streaming diagnostics\n        <span className=\"text-muted-foreground\">{open ? \"Hide\" : \"Show\"}</span>\n      </button>\n      {open && <Metrics format={detectVideoFormat(src, format)} />}\n    </section>\n  );\n}\nfunction Metrics({ format }: { format: VideoFormat }) {\n  const { store } = useVideoPlayer();\n  const metrics = useSyncExternalStore(\n    store.subscribeDiagnostics,\n    store.getDiagnostics,\n    store.getDiagnostics,\n  );\n  const engine = useVideoState((s) => s.engine),\n    quality = useVideoState((s) => s.selectedQuality),\n    rate = useVideoState((s) => s.rate),\n    capabilities = useVideoState((s) => s.capabilities);\n  const [copied, setCopied] = useState(\"\");\n  const s = metrics.stats;\n  const fields = [\n    [\"Engine / format\", `${engine ?? \"Loading\"} / ${format.toUpperCase()}`],\n    [\"Resolution\", s?.width && s.height ? `${s.width} × ${s.height}` : \"N/A\"],\n    [\n      \"Bandwidth estimate\",\n      number(\n        s?.estimatedBandwidth == null ? null : s.estimatedBandwidth / 1e6,\n        \" Mbps\",\n      ),\n    ],\n    [\n      \"Rendition bitrate\",\n      number(\n        s?.variantBitrate == null ? null : s.variantBitrate / 1e6,\n        \" Mbps\",\n      ),\n    ],\n    [\n      \"Buffer ahead / behind\",\n      `${number(metrics.bufferAhead, \"s\")} / ${number(metrics.bufferBehind, \"s\")}`,\n    ],\n    [\"Rebuffers\", String(metrics.stalls)],\n    [\"Buffering time\", number(store.bufferingSeconds(), \"s\")],\n    [\"Load latency\", number(s?.loadLatency, \"s\")],\n    [\"First play latency\", number(metrics.startupSeconds, \"s\")],\n    [\"Dropped frames\", number(s?.droppedFrames, \"\", 0)],\n    [\"Playback rate\", `${rate}×`],\n    [\n      \"ABR\",\n      capabilities.quality\n        ? quality === \"auto\"\n          ? \"Enabled\"\n          : \"Manual\"\n        : \"N/A\",\n    ],\n  ];\n  return (\n    <div className=\"border-t border-border px-4 pb-4\">\n      <dl className=\"grid grid-cols-2 gap-x-5 gap-y-4 py-4 @min-[640px]:grid-cols-3\">\n        {fields.map(([label, value]) => (\n          <div key={label}>\n            <dt className=\"text-[10px] text-muted-foreground\">{label}</dt>\n            <dd className=\"mt-1 font-mono text-xs tabular-nums\">{value}</dd>\n          </div>\n        ))}\n      </dl>\n      <p className=\"mb-3 text-[11px] text-muted-foreground\">\n        Requested quality and active rendition may differ while buffered\n        segments finish. N/A means unavailable. First play latency includes time\n        waiting for user input.\n      </p>\n      {metrics.latestError && (\n        <p className=\"mb-3 text-xs\">\n          Latest error: {metrics.latestError.category} /{\" \"}\n          {metrics.latestError.code} · {metrics.latestError.message}\n        </p>\n      )}\n      <ol\n        aria-label=\"Playback event timeline\"\n        className=\"max-h-40 overflow-auto rounded-lg bg-muted p-3 font-mono text-[10px] leading-5\"\n      >\n        {metrics.events.map((event, i) => (\n          <li key={`${event.at}-${i}`}>\n            <span className=\"mr-3 text-muted-foreground\">\n              {number(event.at / 1000, \"s\")}\n            </span>\n            {event.event}\n            {event.detail && ` · ${event.detail}`}\n          </li>\n        ))}\n      </ol>\n      <div className=\"mt-3 flex items-center gap-3\">\n        <button\n          type=\"button\"\n          className=\"min-h-11 rounded-lg border border-border px-3 text-xs focus-visible:outline-2 focus-visible:outline-ring\"\n          onClick={() => {\n            void navigator.clipboard?.writeText(store.exportDiagnostics()).then(\n              () => setCopied(\"Copied\"),\n              () => setCopied(\"Clipboard unavailable\"),\n            );\n            if (!navigator.clipboard) setCopied(\"Clipboard unavailable\");\n          }}\n        >\n          Copy diagnostics\n        </button>\n        <span role=\"status\" className=\"text-xs text-muted-foreground\">\n          {copied}\n        </span>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-native.ts",
      "content": "import type {\n  PlayerAdapter,\n  PlayerEvent,\n  PlaybackStats,\n  VideoSource,\n  VideoTrack,\n} from \"./video-player-types\";\nimport { detectVideoFormat, finite, readRanges } from \"./video-player-utils\";\n\nexport class NativeAdapter implements PlayerAdapter {\n  readonly engine = \"native\" as const;\n  readonly capabilities = {\n    quality: false,\n    audio: false,\n    captions: true,\n    drm: false,\n  };\n  private cancelLoad?: () => void;\n  constructor(\n    private video: HTMLVideoElement,\n    private emit: (event: PlayerEvent) => void,\n  ) {}\n  load(source: VideoSource, startTime?: number): Promise<void> {\n    const type = detectVideoFormat(source.src, source.type);\n    if (\n      source.drm ||\n      type === \"dash\" ||\n      (type === \"hls\" &&\n        !this.video.canPlayType(\"application/vnd.apple.mpegurl\"))\n    ) {\n      return Promise.reject(\n        new DOMException(\"Unsupported source\", \"NotSupportedError\"),\n      );\n    }\n    this.emit({ type: \"loading\" });\n    return new Promise((resolve, reject) => {\n      const cleanup = () => {\n        this.video.removeEventListener(\"loadedmetadata\", ready);\n        this.video.removeEventListener(\"error\", fail);\n        clearTimeout(timeout);\n        this.cancelLoad = undefined;\n      };\n      const ready = () => {\n        cleanup();\n        if (startTime && Number.isFinite(this.video.duration))\n          this.video.currentTime = Math.min(startTime, this.video.duration);\n        this.emit({ type: \"manifest\" });\n        resolve();\n      };\n      const fail = () => {\n        cleanup();\n        reject({ category: 3, code: this.video.error?.code });\n      };\n      const timeout = setTimeout(() => {\n        cleanup();\n        reject({ category: 1 });\n      }, 30000);\n      this.cancelLoad = () => {\n        cleanup();\n        reject(new DOMException(\"Cancelled\", \"AbortError\"));\n      };\n      this.video.addEventListener(\"loadedmetadata\", ready);\n      this.video.addEventListener(\"error\", fail);\n      this.video.src = source.src;\n      this.video.load();\n    });\n  }\n  getQualities() {\n    return [];\n  }\n  setQuality() {}\n  getAudioTracks() {\n    return [];\n  }\n  setAudioTrack() {}\n  getTextTracks(): VideoTrack[] {\n    return Array.from(this.video.textTracks).map((t, i) => ({\n      id: String(i),\n      language: t.language,\n      label: t.label || t.language || `Track ${i + 1}`,\n      active: t.mode === \"showing\",\n    }));\n  }\n  setTextTrack(id: string) {\n    Array.from(this.video.textTracks).forEach((t, i) => {\n      t.mode = String(i) === id ? \"showing\" : \"disabled\";\n    });\n    this.emit({ type: \"tracks\" });\n  }\n  getStats(): PlaybackStats {\n    return {\n      width: this.video.videoWidth || null,\n      height: this.video.videoHeight || null,\n      estimatedBandwidth: null,\n      variantBitrate: null,\n      loadLatency: null,\n      droppedFrames: finite(\n        this.video.getVideoPlaybackQuality?.().droppedVideoFrames,\n      ),\n    };\n  }\n  getSeekRange() {\n    const ranges = readRanges(this.video.seekable);\n    return {\n      start: ranges[0]?.[0] ?? 0,\n      end: ranges.at(-1)?.[1] ?? 0,\n      live: this.video.duration === Infinity,\n    };\n  }\n  destroy() {\n    this.cancelLoad?.();\n    this.video.pause();\n    this.video.removeAttribute(\"src\");\n    this.video.load();\n  }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-shaka.ts",
      "content": "import shaka from \"shaka-player\";\nimport type {\n  PlayerAdapter,\n  PlayerEvent,\n  VideoSource,\n} from \"./video-player-types\";\nimport { finite, normalizeQualities, playerError } from \"./video-player-utils\";\n\n/** Imported only after mount and only for the selected engine. No Shaka UI bundle. */\nexport class ShakaAdapter implements PlayerAdapter {\n  readonly engine = \"shaka\" as const;\n  readonly capabilities = {\n    quality: true,\n    audio: true,\n    captions: true,\n    drm: true,\n  };\n  private player: shaka.Player;\n  private destroyed = false;\n  constructor(\n    private video: HTMLVideoElement,\n    private emit: (event: PlayerEvent) => void,\n  ) {\n    shaka.polyfill.installAll();\n    if (!shaka.Player.isBrowserSupported())\n      throw new DOMException(\"Unsupported browser\", \"NotSupportedError\");\n    this.player = new shaka.Player();\n    this.player.addEventListener(\"error\", (event) => {\n      const detail = (event as CustomEvent<shaka.util.Error>).detail;\n      emit({\n        type: \"error\",\n        error: playerError(\n          detail,\n          detail.severity === shaka.util.Error.Severity.CRITICAL,\n        ),\n      });\n    });\n    this.player.addEventListener(\"buffering\", (event) =>\n      emit({\n        type: \"buffering\",\n        buffering: (event as unknown as { buffering: boolean }).buffering,\n      }),\n    );\n    for (const name of [\"adaptation\", \"variantchanged\"])\n      this.player.addEventListener(name, () => emit({ type: \"quality\" }));\n    for (const name of [\n      \"trackschanged\",\n      \"textchanged\",\n      \"texttrackvisibility\",\n      \"audiochanged\",\n    ])\n      this.player.addEventListener(name, () => emit({ type: \"tracks\" }));\n    this.player.addEventListener(\"retry\", () => emit({ type: \"recovery\" }));\n  }\n  async load(source: VideoSource, startTime?: number) {\n    this.emit({ type: \"loading\" });\n    await this.player.attach(this.video);\n    if (this.destroyed) return;\n    const retry = {\n      maxAttempts: 3,\n      baseDelay: 1000,\n      backoffFactor: 2,\n      timeout: 20000,\n    };\n    this.player.configure({\n      streaming: {\n        bufferingGoal: 30,\n        rebufferingGoal: 2,\n        bufferBehind: 30,\n        retryParameters: retry,\n      },\n      manifest: { retryParameters: retry },\n      drm: {\n        ...source.drm,\n        retryParameters: { ...retry, ...source.drm?.retryParameters },\n      },\n    });\n    await this.player.load(source.src, startTime);\n    if (!this.destroyed) this.emit({ type: \"manifest\" });\n  }\n  getQualities() {\n    const tracks = this.player.getVariantTracks();\n    const active = tracks.find((t) => t.active);\n    // Do not accidentally change language/audio role while selecting a resolution.\n    return normalizeQualities(\n      tracks\n        .filter(\n          (t) =>\n            !active ||\n            (t.language === active.language && t.audioId === active.audioId),\n        )\n        .map((t) => ({\n          id: String(t.id),\n          label: `${t.height ? `${t.height}p` : \"Audio\"} · ${(t.bandwidth / 1e6).toFixed(1)} Mbps`,\n          width: t.width ?? 0,\n          height: t.height ?? 0,\n          bitrate: t.bandwidth,\n          active: t.active,\n        })),\n    );\n  }\n  setQuality(id: string) {\n    if (id === \"auto\") {\n      this.player.configure({ abr: { enabled: true } });\n      return;\n    }\n    const track = this.player\n      .getVariantTracks()\n      .find((t) => String(t.id) === id);\n    if (!track) return;\n    this.player.configure({ abr: { enabled: false } });\n    this.player.selectVariantTrack(track, false);\n  }\n  getAudioTracks() {\n    return this.player.getAudioTracks().map((t) => ({\n      id: String(t.id),\n      label: t.label || t.language || `Audio ${t.id}`,\n      language: t.language,\n      active: t.active,\n    }));\n  }\n  setAudioTrack(id: string) {\n    const track = this.player.getAudioTracks().find((t) => String(t.id) === id);\n    if (track) this.player.selectAudioTrack(track);\n  }\n  getTextTracks() {\n    return this.player.getTextTracks().map((t) => ({\n      id: String(t.id),\n      label: t.label || t.language || `Track ${t.id}`,\n      language: t.language,\n      active: t.active,\n    }));\n  }\n  setTextTrack(id: string) {\n    const track = this.player.getTextTracks().find((t) => String(t.id) === id);\n    this.player.selectTextTrack(id === \"off\" ? null : track);\n  }\n  getSeekRange() {\n    return { ...this.player.seekRange(), live: this.player.isLive() };\n  }\n  getStats() {\n    const s = this.player.getStats();\n    return {\n      width: finite(this.video.videoWidth),\n      height: finite(this.video.videoHeight),\n      estimatedBandwidth: finite(s.estimatedBandwidth),\n      variantBitrate: finite(s.streamBandwidth),\n      droppedFrames: finite(s.droppedFrames),\n      loadLatency: finite(s.loadLatency),\n    };\n  }\n  async destroy() {\n    this.destroyed = true;\n    await this.player.destroy();\n  }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/components/video-player-hls.ts",
      "content": "import Hls from \"hls.js\";\nimport type {\n  PlayerAdapter,\n  PlayerEvent,\n  VideoSource,\n} from \"./video-player-types\";\nimport { NativeAdapter } from \"./video-player-native\";\nimport { finite, normalizeQualities, playerError } from \"./video-player-utils\";\n\nexport function createHlsAdapter(\n  video: HTMLVideoElement,\n  emit: (event: PlayerEvent) => void,\n): PlayerAdapter {\n  if (Hls.isSupported()) return new HlsAdapter(video, emit);\n  if (video.canPlayType(\"application/vnd.apple.mpegurl\"))\n    return new NativeAdapter(video, emit);\n  throw new DOMException(\"HLS is unavailable\", \"NotSupportedError\");\n}\nclass HlsAdapter implements PlayerAdapter {\n  readonly engine = \"hls\" as const;\n  readonly capabilities = {\n    quality: true,\n    audio: true,\n    captions: true,\n    drm: false,\n  };\n  private hls: Hls;\n  private recoveries = 0;\n  private timer?: ReturnType<typeof setTimeout>;\n  private cancelLoad?: () => void;\n  private latency: number | null = null;\n  constructor(\n    private video: HTMLVideoElement,\n    private emit: (event: PlayerEvent) => void,\n  ) {\n    this.hls = new Hls({\n      maxBufferLength: 30,\n      backBufferLength: 30,\n      autoStartLoad: false,\n    });\n    this.hls.on(Hls.Events.LEVEL_SWITCHED, () => emit({ type: \"quality\" }));\n    for (const name of [\n      Hls.Events.AUDIO_TRACKS_UPDATED,\n      Hls.Events.AUDIO_TRACK_SWITCHED,\n      Hls.Events.SUBTITLE_TRACKS_UPDATED,\n      Hls.Events.SUBTITLE_TRACK_SWITCH,\n    ])\n      this.hls.on(name, () => emit({ type: \"tracks\" }));\n    this.hls.on(Hls.Events.ERROR, (_, data) => {\n      const error = playerError(\n        { category: data.type === Hls.ErrorTypes.NETWORK_ERROR ? 1 : 3 },\n        data.fatal,\n      );\n      if (\n        data.fatal &&\n        this.recoveries < 2 &&\n        [Hls.ErrorTypes.NETWORK_ERROR, Hls.ErrorTypes.MEDIA_ERROR].includes(\n          data.type,\n        )\n      ) {\n        this.recoveries++;\n        emit({ type: \"error\", error: { ...error, fatal: false } });\n        clearTimeout(this.timer);\n        this.timer = setTimeout(\n          () => {\n            emit({ type: \"recovery\" });\n            if (data.type === Hls.ErrorTypes.NETWORK_ERROR)\n              this.hls.startLoad();\n            else this.hls.recoverMediaError();\n          },\n          1000 * 2 ** (this.recoveries - 1),\n        );\n      } else emit({ type: \"error\", error });\n    });\n  }\n  load(source: VideoSource, startTime?: number): Promise<void> {\n    this.emit({ type: \"loading\" });\n    const start = performance.now();\n    return new Promise((resolve, reject) => {\n      const cleanup = () => {\n        clearTimeout(timeout);\n        this.hls.off(Hls.Events.MANIFEST_PARSED, ready);\n        this.hls.off(Hls.Events.ERROR, fail);\n        this.cancelLoad = undefined;\n      };\n      const ready = () => {\n        cleanup();\n        this.latency = (performance.now() - start) / 1000;\n        this.emit({ type: \"manifest\" });\n        this.hls.startLoad(startTime ?? -1);\n        resolve();\n      };\n      const fail = (_: unknown, data: { fatal: boolean }) => {\n        if (data.fatal && this.recoveries >= 2) {\n          cleanup();\n          reject({ category: 1 });\n        }\n      };\n      const timeout = setTimeout(() => {\n        cleanup();\n        reject({ category: 1 });\n      }, 45000);\n      this.cancelLoad = () => {\n        cleanup();\n        reject(new DOMException(\"Cancelled\", \"AbortError\"));\n      };\n      this.hls.on(Hls.Events.MANIFEST_PARSED, ready);\n      this.hls.on(Hls.Events.ERROR, fail);\n      this.hls.attachMedia(this.video);\n      this.hls.loadSource(source.src);\n    });\n  }\n  getQualities() {\n    return normalizeQualities(\n      this.hls.levels.map((l, i) => ({\n        id: String(i),\n        label: `${l.height}p · ${(l.bitrate / 1e6).toFixed(1)} Mbps`,\n        width: l.width,\n        height: l.height,\n        bitrate: l.bitrate,\n        active: this.hls.currentLevel === i,\n      })),\n    );\n  }\n  setQuality(id: string) {\n    this.hls.nextLevel = id === \"auto\" ? -1 : Number(id);\n  }\n  getAudioTracks() {\n    return this.hls.audioTracks.map((t, i) => ({\n      id: String(i),\n      label: t.name || t.lang || `Audio ${i + 1}`,\n      language: t.lang ?? \"\",\n      active: this.hls.audioTrack === i,\n    }));\n  }\n  setAudioTrack(id: string) {\n    this.hls.audioTrack = Number(id);\n  }\n  getTextTracks() {\n    return this.hls.subtitleTracks.map((t, i) => ({\n      id: String(i),\n      label: t.name || t.lang || `Track ${i + 1}`,\n      language: t.lang ?? \"\",\n      active: this.hls.subtitleTrack === i && this.hls.subtitleDisplay,\n    }));\n  }\n  setTextTrack(id: string) {\n    this.hls.subtitleTrack = id === \"off\" ? -1 : Number(id);\n    this.hls.subtitleDisplay = id !== \"off\";\n  }\n  getSeekRange() {\n    const ranges = this.video.seekable;\n    return {\n      start: ranges.length ? ranges.start(0) : 0,\n      end: ranges.length ? ranges.end(ranges.length - 1) : 0,\n      live: this.hls.levels[this.hls.currentLevel]?.details?.live ?? false,\n    };\n  }\n  getStats() {\n    return {\n      width: this.video.videoWidth || null,\n      height: this.video.videoHeight || null,\n      estimatedBandwidth: finite(this.hls.bandwidthEstimate),\n      variantBitrate: finite(this.hls.levels[this.hls.currentLevel]?.bitrate),\n      droppedFrames: finite(\n        this.video.getVideoPlaybackQuality?.().droppedVideoFrames,\n      ),\n      loadLatency: this.latency,\n    };\n  }\n  destroy() {\n    clearTimeout(this.timer);\n    this.cancelLoad?.();\n    this.hls.destroy();\n    this.video.removeAttribute(\"src\");\n    this.video.load();\n  }\n}\n",
      "type": "registry:component"
    }
  ],
  "meta": {
    "license": "MIT",
    "cavemio": {
      "component": "video-player",
      "exportName": "VideoPlayer",
      "categories": [
        "display"
      ],
      "usage": "import { VideoPlayer } from \"@/components/video-player\";\n\n<VideoPlayer\n  src=\"https://storage.googleapis.com/shaka-demo-assets/sintel/dash.mpd\"\n  type=\"dash\"\n  title=\"Sintel\"\n  muted\n/>;",
      "accessibility": "Native labeled buttons and sliders, focus-preserving keyboard menus, scoped shortcuts, touch controls, cinematic focus containment and restoration, live reduced motion. On the focused frame: Space/K play, arrows seek/volume, M mute, F fullscreen, C captions. Shortcuts do not consume input fields or button keys.",
      "previewNote": "Seven interactive examples cover formats, quality, diagnostics, engine comparison, motion and authorized DRM tests. Public media loads from its original host. DRM success is shown only after the protected stream plays. Browser fullscreen/PiP and commercial CDMs depend on device support. See the source registry documentation and docs/video-player.md for full integration and verification guidance.",
      "documentation": {
        "props": [
          {
            "name": "src / source",
            "type": "string / VideoSource",
            "description": "URL or typed source including format, poster, and caller-provided Shaka DRM configuration. Explicit type is required for extensionless HLS/DASH URLs. Keep DRM configuration referentially stable."
          },
          {
            "name": "type",
            "type": "hls | dash | mp4",
            "description": "Optional format hint; otherwise detected from the URL extension."
          },
          {
            "name": "engine",
            "type": "shaka | hls | native · shaka",
            "description": "Lazy-load one engine. HLS.js accepts HLS only and falls back to native HLS when MSE is unavailable. Engine changes reload media and restore time for the same URL."
          },
          {
            "name": "poster / title",
            "type": "string",
            "description": "Poster URL and accessible video title. Source poster takes precedence."
          },
          {
            "name": "autoPlay / muted / loop",
            "type": "boolean · false",
            "description": "Browser media preferences. Autoplay can be rejected by browser policy; user play remains available."
          },
          {
            "name": "playing / onPlayingChange",
            "type": "boolean / (playing: boolean) => void",
            "description": "Optional controlled playback intent and actual media-event callback. Omit playing for local control."
          },
          {
            "name": "controls",
            "type": "boolean · true",
            "description": "Show the default control composition. Set false and compose exported controls or use onReady for a custom interface."
          },
          {
            "name": "enableGooey",
            "type": "boolean · true",
            "description": "SVG filtering applies only to decorative surfaces. False uses a static, unfiltered fallback."
          },
          {
            "name": "enableAnimations / reducedMotion",
            "type": "boolean · true / boolean · false",
            "description": "GSAP motion toggle and reduced-motion preview. OS reduced-motion settings always take precedence; changes settle active motion."
          },
          {
            "name": "enableDiagnostics",
            "type": "boolean · false",
            "description": "Lazy-load genuine engine/browser metrics and a bounded event timeline. Polls at 1Hz only while the panel is visible; copy exports sanitized JSON."
          },
          {
            "name": "enablePictureInPicture / enableFullscreen",
            "type": "boolean · true",
            "description": "Enable PiP and fullscreen controls. The main fullscreen button animates viewport expansion; Settings offers browser fullscreen where supported. Unavailable browser actions are disabled and failed requests are announced."
          },
          {
            "name": "onReady",
            "type": "(player: VideoPlayerHandle) => void",
            "description": "Receives normalized play, pause, seek, quality, audio, captions, volume, speed, and retry actions."
          },
          {
            "name": "onError",
            "type": "(error: PlayerError) => void",
            "description": "Sanitized error code/category with fatal and retryable flags. Raw URLs, DRM payloads, and tokens are omitted."
          },
          {
            "name": "className / style / children",
            "type": "string / CSSProperties / ReactNode",
            "description": "Wrapper customization and composable overlay content. useVideoPlayer/useVideoState expose normalized controls and state."
          }
        ],
        "useCases": [
          {
            "title": "HLS and DASH",
            "description": "Use Shaka for adaptive HLS/DASH and protected streams. Select HLS.js explicitly for HLS. Native playback has fewer quality and diagnostic capabilities."
          },
          {
            "title": "Compose a player",
            "description": "Set controls={false} and render VideoControls, VideoPlayButton, VideoSeekbar, VideoVolume, or VideoSettings as children. useVideoState selects stable fields; useVideoPlayer exposes normalized actions."
          },
          {
            "title": "Protected playback",
            "description": "Pass source.drm.servers keyed by com.widevine.alpha, com.microsoft.playready, or com.apple.fps. Advanced Shaka configuration supports certificates and license headers. Use HTTPS, authorized assets, and runtime credentials. FairPlay requires device-specific packaging and certificates; the demo does not certify it."
          }
        ],
        "features": [
          {
            "title": "One persistent video",
            "description": "GSAP interpolates the existing frame geometry into the top layer. No media reload occurs during cinematic expansion. Browser fullscreen is a separate API."
          },
          {
            "title": "Observable playback",
            "description": "Real bandwidth estimates, rendition bitrate, frame drops, buffer ranges and errors. N/A identifies unavailable measurements. Hidden diagnostics stop polling."
          },
          {
            "title": "Source installation",
            "description": "React 19, TypeScript, Tailwind CSS 4 and shadcn theme tokens are required. All helpers ship in this registry item; only the selected streaming engine loads at runtime in a splitting bundler."
          }
        ],
        "states": [
          {
            "title": "Adaptive or fixed quality",
            "description": "Auto enables ABR. Manual requests retain buffered segments, so the active rendition may change later. Changing audio returns to Auto to avoid pinning an incompatible variant."
          },
          {
            "title": "Buffering and recovery",
            "description": "Media/engine events drive loading feedback. Shaka requests retry up to three times with backoff; HLS.js allows two additional fatal recovery attempts. Retry starts a fresh session."
          },
          {
            "title": "Browser limitations and troubleshooting",
            "description": "Check CORS on manifests, segments, captions and licenses, HTTPS, codecs, MSE/EME support, and autoplay policy. Diagnostics omit credentials. Iframe permission policy can block fullscreen/PiP/DRM; test natively."
          }
        ]
      }
    }
  },
  "type": "registry:component"
}