{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "youtube-embed",
  "title": "YouTube Embed",
  "description": "A YouTube video that costs one poster image until it is played, with player controls through its ref.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-in-view"
  ],
  "files": [
    {
      "path": "registry/default/ui/youtube-embed.tsx",
      "content": "\"use client\";\n\nimport { PlayIcon } from \"lucide-react\";\nimport {\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type Ref,\n} from \"react\";\nimport { preconnect } from \"react-dom\";\n\nimport { useInView } from \"@/registry/default/hooks/use-in-view\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\ntype YouTubePoster = \"maxresdefault\" | \"sddefault\" | \"hqdefault\";\n\n/**\n * - `idle`: the poster and play button, no iframe yet.\n * - `loading`: the iframe is on its way.\n * - `ready`: the player is loaded and waiting.\n * - `playing`, `paused`, `ended`: reported by the player.\n */\ntype YouTubeEmbedState = \"idle\" | \"loading\" | \"ready\" | \"playing\" | \"paused\" | \"ended\";\n\n/** Controls for the player, through `ref`. Calls made before it loads wait for it. */\ninterface YouTubeEmbedHandle {\n  /** Loads the player if needed and starts the video. */\n  play(): void;\n  pause(): void;\n  mute(): void;\n  unmute(): void;\n  /** Sets the volume, from 0 to 100. Browsers only play sound after the viewer has interacted with the page. */\n  setVolume(volume: number): void;\n  /** Jumps to a time, in seconds. */\n  seekTo(seconds: number): void;\n  /** Loads the player without starting it (unless `autoplay` is on). */\n  load(): void;\n}\n\ntype PlayerState = Exclude<YouTubeEmbedState, \"idle\">;\n\nconst PLAYER_ORIGIN = /^https:\\/\\/www\\.youtube(-nocookie)?\\.com$/;\n\n// The player's numeric states. Buffering (3) keeps whatever came before.\nconst PLAYER_STATES: Record<number, PlayerState> = {\n  [-1]: \"ready\",\n  0: \"ended\",\n  1: \"playing\",\n  2: \"paused\",\n  5: \"ready\",\n};\n\n/** The player state carried by a message from the iframe, if any. */\nfunction readPlayerState(data: unknown): PlayerState | undefined {\n  if (!data || typeof data !== \"object\") return undefined;\n  const { event, info } = data as { event?: unknown; info?: unknown };\n  if (event === \"onReady\") return \"ready\";\n  if (event === \"onStateChange\" && typeof info === \"number\") return PLAYER_STATES[info];\n  if (\n    (event === \"infoDelivery\" || event === \"initialDelivery\") &&\n    info &&\n    typeof info === \"object\" &&\n    typeof (info as { playerState?: unknown }).playerState === \"number\"\n  ) {\n    return PLAYER_STATES[(info as { playerState: number }).playerState];\n  }\n  return undefined;\n}\n\nfunction parseMessage(data: unknown): unknown {\n  if (typeof data !== \"string\") return data;\n  try {\n    return JSON.parse(data);\n  } catch {\n    return undefined;\n  }\n}\n\n// Embeds that share a `group`: starting one pauses the others.\nconst players = new Set<{ group: string; pause: () => void }>();\n\nconst subscribe = () => () => {};\n\ninterface YouTubeEmbedProps extends Omit<\n  ComponentProps<\"div\">,\n  \"ref\" | \"children\" | \"title\" | \"onPlay\" | \"onPause\"\n> {\n  /** The id in the video's URL: `youtube.com/watch?v=<videoId>`. */\n  videoId: string;\n  /** What the video is: the iframe's title and the play button's name. */\n  title: string;\n  /** Which of YouTube's thumbnails to show before it loads. Not every video has \"maxresdefault\". */\n  poster?: YouTubePoster;\n  /** A poster image of your own, in place of YouTube's thumbnail. */\n  posterSrc?: string;\n  /** Where the video starts, in seconds. */\n  start?: number;\n  /** Extra player parameters, e.g. `{ rel: \"0\" }`. They override the ones set from props. */\n  params?: Record<string, string>;\n  /** Load from youtube-nocookie.com, which sets no cookies until the video plays. */\n  noCookie?: boolean;\n  /** Width to height, as CSS `aspect-ratio`. */\n  aspectRatio?: string;\n  /** Name of the play button. Defaults to \"Play: <title>\". */\n  playLabel?: string;\n  /**\n   * When the player loads: \"click\" waits for the play button, \"in-view\"\n   * loads it once it scrolls near, \"eager\" as soon as the page runs.\n   */\n  load?: \"click\" | \"in-view\" | \"eager\";\n  /**\n   * For \"in-view\" and \"eager\": start playing once loaded. Browsers only\n   * allow that without sound, so it also mutes. A click always plays.\n   */\n  autoplay?: boolean;\n  /** Start without sound. */\n  muted?: boolean;\n  /** Start over at the end. */\n  loop?: boolean;\n  /** Show the player's controls. */\n  controls?: boolean;\n  /** Embeds with the same group pause when another one in it starts. */\n  group?: string;\n  onPlay?: () => void;\n  onPause?: () => void;\n  onEnd?: () => void;\n  /** Receives the player controls: play, pause, mute, unmute, setVolume, seekTo and load. */\n  ref?: Ref<YouTubeEmbedHandle>;\n}\n\n/**\n * A YouTube video that costs one image until it is wanted: a poster and a\n * play button stand in for the player, and the iframe only loads when the\n * button is pressed (or when it scrolls into view, or right away, with\n * `load`). Nothing from YouTube runs before then, and no API script is\n * loaded: `ref` controls the player through messages to the iframe, and its\n * state comes back in `data-state` and the `onPlay` / `onPause` / `onEnd`\n * callbacks.\n *\n * The play button is a real button named after the video. Pressing it moves\n * focus into the player, so keyboard users land on its controls. With\n * `prefers-reduced-motion` the button does not grow on hover.\n *\n * @example\n * <YouTubeEmbed videoId=\"dQw4w9WgXcQ\" title=\"Launch recap\" className=\"max-w-2xl\" />\n */\nfunction YouTubeEmbed({\n  videoId,\n  title,\n  poster = \"hqdefault\",\n  posterSrc,\n  start,\n  params,\n  noCookie = true,\n  aspectRatio = \"16 / 9\",\n  playLabel,\n  load = \"click\",\n  autoplay = false,\n  muted = false,\n  loop = false,\n  controls = true,\n  group,\n  onPlay,\n  onPause,\n  onEnd,\n  className,\n  style,\n  ref,\n  ...props\n}: YouTubeEmbedProps) {\n  const channel = useId();\n  const iframe = useRef<HTMLIFrameElement>(null);\n  const [activation, setActivation] = useState<\"play\" | \"load\" | null>(null);\n  const browser = useSyncExternalStore(\n    subscribe,\n    () => true,\n    () => false\n  );\n  const [observe, inView] = useInView<HTMLDivElement>({\n    once: true,\n    rootMargin: \"200px\",\n  });\n\n  const mounted =\n    activation !== null ||\n    (load === \"eager\" && browser) ||\n    (load === \"in-view\" && browser && inView);\n  const autoplayNow = activation === \"play\" || autoplay;\n  // Autoplay that nobody asked for with a click has to be silent.\n  const muteNow = muted || (autoplayNow && activation !== \"play\");\n\n  const host = noCookie ? \"https://www.youtube-nocookie.com\" : \"https://www.youtube.com\";\n  let src = \"\";\n  if (mounted) {\n    const search = new URLSearchParams({\n      enablejsapi: \"1\",\n      playsinline: \"1\",\n      origin: window.location.origin,\n    });\n    if (autoplayNow) search.set(\"autoplay\", \"1\");\n    if (muteNow) search.set(\"mute\", \"1\");\n    if (loop) {\n      // Looping a single video needs it as its own playlist.\n      search.set(\"loop\", \"1\");\n      search.set(\"playlist\", videoId);\n    }\n    if (!controls) search.set(\"controls\", \"0\");\n    if (start) search.set(\"start\", String(Math.max(0, Math.floor(start))));\n    for (const [key, value] of Object.entries(params ?? {})) search.set(key, value);\n    src = `${host}/embed/${encodeURIComponent(videoId)}?${search.toString()}`;\n  }\n\n  const [player, setPlayer] = useState<{ src: string; state: PlayerState }>({\n    src: \"\",\n    state: \"loading\",\n  });\n  const state: YouTubeEmbedState = !mounted\n    ? \"idle\"\n    : player.src === src\n      ? player.state\n      : \"loading\";\n\n  const callbacks = useRef({ onPlay, onPause, onEnd });\n  useEffect(() => {\n    callbacks.current = { onPlay, onPause, onEnd };\n  });\n\n  // Commands wait here until the iframe has loaded.\n  const queue = useRef<string[]>([]);\n  const loaded = useRef(false);\n  const lastState = useRef<PlayerState>(\"loading\");\n\n  const send = (func: string, args: unknown[] = []) => {\n    const message = JSON.stringify({\n      event: \"command\",\n      func,\n      args,\n      id: channel,\n      channel: \"widget\",\n    });\n    const target = iframe.current?.contentWindow;\n    if (loaded.current && target) target.postMessage(message, host);\n    else queue.current.push(message);\n  };\n  const sendRef = useRef(send);\n  useEffect(() => {\n    sendRef.current = send;\n  });\n\n  // Listen to the player: only messages from this iframe, from YouTube.\n  useEffect(() => {\n    if (!src) return;\n    loaded.current = false;\n    lastState.current = \"loading\";\n    const onMessage = (event: MessageEvent) => {\n      const target = iframe.current?.contentWindow;\n      if (!target || event.source !== target || !PLAYER_ORIGIN.test(event.origin)) return;\n      const next = readPlayerState(parseMessage(event.data));\n      if (!next || next === lastState.current) return;\n      const previous = lastState.current;\n      lastState.current = next;\n      setPlayer({ src, state: next });\n      if (next === \"playing\") {\n        callbacks.current.onPlay?.();\n      } else if (next === \"paused\" && previous === \"playing\") {\n        callbacks.current.onPause?.();\n      } else if (next === \"ended\") {\n        callbacks.current.onEnd?.();\n      }\n    };\n    window.addEventListener(\"message\", onMessage);\n    return () => window.removeEventListener(\"message\", onMessage);\n  }, [src]);\n\n  // Pause the rest of the group when this one starts.\n  const self = useRef({\n    group: \"\",\n    pause: () => {\n      if (loaded.current) sendRef.current(\"pauseVideo\");\n    },\n  });\n  useEffect(() => {\n    if (!group) return;\n    const entry = self.current;\n    entry.group = group;\n    players.add(entry);\n    return () => {\n      players.delete(entry);\n    };\n  }, [group]);\n  useEffect(() => {\n    if (state !== \"playing\" || !group) return;\n    for (const other of players) {\n      if (other !== self.current && other.group === group) other.pause();\n    }\n  }, [state, group]);\n\n  // A click swaps the button for the player: keep focus with it.\n  useEffect(() => {\n    if (mounted && activation === \"play\") iframe.current?.focus();\n  }, [mounted, activation]);\n\n  const onLoad = () => {\n    const target = iframe.current?.contentWindow;\n    if (!target) return;\n    loaded.current = true;\n    // Ask the player to report its state, then send anything that was waiting.\n    target.postMessage(\n      JSON.stringify({ event: \"listening\", id: channel, channel: \"widget\" }),\n      host\n    );\n    for (const message of queue.current.splice(0)) target.postMessage(message, host);\n    if (lastState.current === \"loading\") {\n      lastState.current = \"ready\";\n      setPlayer({ src, state: \"ready\" });\n    }\n  };\n\n  useImperativeHandle(\n    ref,\n    () => ({\n      play: () => {\n        if (mounted) sendRef.current(\"playVideo\");\n        else setActivation(\"play\");\n      },\n      pause: () => sendRef.current(\"pauseVideo\"),\n      mute: () => sendRef.current(\"mute\"),\n      unmute: () => sendRef.current(\"unMute\"),\n      setVolume: (volume: number) =>\n        sendRef.current(\"setVolume\", [Math.round(Math.min(Math.max(volume, 0), 100))]),\n      seekTo: (seconds: number) => sendRef.current(\"seekTo\", [seconds, true]),\n      load: () => {\n        if (!mounted) setActivation(\"load\");\n      },\n    }),\n    [mounted]\n  );\n\n  const warm = () => preconnect(host);\n\n  return (\n    <div\n      ref={observe}\n      data-slot=\"youtube-embed\"\n      data-state={state}\n      className={cn(\"bg-muted relative isolate w-full overflow-hidden rounded-lg\", className)}\n      style={{ aspectRatio, ...style }}\n      {...props}\n    >\n      <img\n        data-slot=\"youtube-embed-poster\"\n        src={posterSrc ?? `https://i.ytimg.com/vi/${encodeURIComponent(videoId)}/${poster}.jpg`}\n        alt=\"\"\n        loading=\"lazy\"\n        decoding=\"async\"\n        className=\"absolute inset-0 size-full object-cover\"\n      />\n      {mounted ? (\n        <iframe\n          ref={iframe}\n          data-slot=\"youtube-embed-iframe\"\n          src={src}\n          title={title}\n          allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\"\n          allowFullScreen\n          referrerPolicy=\"strict-origin-when-cross-origin\"\n          onLoad={onLoad}\n          className=\"absolute inset-0 size-full border-0\"\n        />\n      ) : (\n        <button\n          type=\"button\"\n          data-slot=\"youtube-embed-play\"\n          aria-label={playLabel ?? `Play: ${title}`}\n          onClick={() => setActivation(\"play\")}\n          onPointerEnter={warm}\n          onFocus={warm}\n          className=\"group/youtube-play absolute inset-0 grid cursor-pointer place-items-center outline-none\"\n        >\n          <span\n            aria-hidden=\"true\"\n            className={cn(\n              \"bg-background/90 text-foreground grid size-16 place-items-center rounded-full shadow-lg\",\n              \"transition-transform group-hover/youtube-play:scale-105 motion-reduce:transition-none\",\n              \"group-focus-visible/youtube-play:ring-ring/50 group-focus-visible/youtube-play:ring-[3px]\"\n            )}\n          >\n            <PlayIcon className=\"size-7 translate-x-0.5 fill-current\" />\n          </span>\n        </button>\n      )}\n    </div>\n  );\n}\n\nexport { YouTubeEmbed, type YouTubeEmbedHandle, type YouTubeEmbedProps, type YouTubeEmbedState };\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}