{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "video-player-jw",
  "title": "Video Player (JW Player)",
  "author": "AlgorizeTech",
  "description": "Ask the user to pick one of 4 video player variants: https://avaraui.com/view/video-player. This is the JW Player. Skip the question if the user already named one. A hero video player built on JW Player, with colour skin presets and a native fallback for when the licensed library is unavailable.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/VideoPlayerJwBlock.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { AlertTriangle } from \"lucide-react\";\nimport React, { useEffect, useId, useRef, useState } from \"react\";\n\n/**\n * JW Player's public documentation library.\n *\n * It is enough to evaluate the component and it is what the docs preview runs\n * on, but it belongs to JW, not to you: it can be rotated or rate-limited\n * without notice, and it carries JW's branding rather than yours. Before\n * shipping, create a player in the JW dashboard and pass your own\n * `https://cdn.jwplayer.com/libraries/<PLAYER_ID>.js` as `libraryUrl`.\n */\nexport const JW_DEMO_LIBRARY_URL = \"https://cdn.jwplayer.com/libraries/IDzF9Zmk.js\";\n\n/**\n * JW8 has no named built-in skins — the control bar is themed by colour, and a\n * fully custom look is a CSS file referenced through `skinUrl`/`skinName`.\n * These presets are that colour config, pre-mixed.\n */\nexport type JwSkinPreset = \"default\" | \"midnight\" | \"neon\" | \"sunset\" | \"minimal\";\n\n/** The shape of JW8's `skin` config object. */\nexport interface JwSkinConfig {\n  name?: string;\n  url?: string;\n  controlbar?: {\n    background?: string;\n    icons?: string;\n    iconsActive?: string;\n    text?: string;\n  };\n  menus?: { background?: string; text?: string; textActive?: string };\n  timeslider?: { progress?: string; rail?: string };\n  tooltips?: { background?: string; text?: string };\n}\n\nconst SKIN_PRESETS: Record<Exclude<JwSkinPreset, \"default\">, JwSkinConfig> = {\n  midnight: {\n    controlbar: {\n      background: \"rgba(9,9,11,0.85)\",\n      icons: \"rgba(255,255,255,0.75)\",\n      iconsActive: \"#818cf8\",\n      text: \"#fafafa\",\n    },\n    menus: { background: \"#18181b\", text: \"rgba(255,255,255,0.75)\", textActive: \"#818cf8\" },\n    timeslider: { progress: \"#818cf8\", rail: \"rgba(255,255,255,0.2)\" },\n    tooltips: { background: \"#18181b\", text: \"#fafafa\" },\n  },\n  neon: {\n    controlbar: {\n      background: \"rgba(0,0,0,0.55)\",\n      icons: \"rgba(236,254,255,0.8)\",\n      iconsActive: \"#22d3ee\",\n      text: \"#ecfeff\",\n    },\n    menus: { background: \"#083344\", text: \"rgba(236,254,255,0.8)\", textActive: \"#22d3ee\" },\n    timeslider: { progress: \"#22d3ee\", rail: \"rgba(34,211,238,0.25)\" },\n    tooltips: { background: \"#0e7490\", text: \"#ecfeff\" },\n  },\n  sunset: {\n    controlbar: {\n      background: \"rgba(28,25,23,0.8)\",\n      icons: \"rgba(255,247,237,0.8)\",\n      iconsActive: \"#fb923c\",\n      text: \"#fff7ed\",\n    },\n    menus: { background: \"#1c1917\", text: \"rgba(255,247,237,0.8)\", textActive: \"#fb923c\" },\n    timeslider: { progress: \"#fb923c\", rail: \"rgba(251,146,60,0.25)\" },\n    tooltips: { background: \"#7c2d12\", text: \"#fff7ed\" },\n  },\n  minimal: {\n    controlbar: {\n      background: \"rgba(255,255,255,0)\",\n      icons: \"rgba(255,255,255,0.85)\",\n      iconsActive: \"#ffffff\",\n      text: \"#ffffff\",\n    },\n    menus: { background: \"#ffffff\", text: \"#3f3f46\", textActive: \"#09090b\" },\n    timeslider: { progress: \"#ffffff\", rail: \"rgba(255,255,255,0.35)\" },\n    tooltips: { background: \"#ffffff\", text: \"#09090b\" },\n  },\n};\n\nexport interface JwPlayerProps\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"title\"> {\n  /** JW library script. See {@link JW_DEMO_LIBRARY_URL} before shipping. */\n  libraryUrl?: string;\n  /** Only for a self-hosted library build — cloud libraries embed their own. */\n  licenseKey?: string;\n  /** A media file (mp4) or an HLS manifest. Ignored when `playlistUrl` is set. */\n  file?: string;\n  /** A JW playlist or media endpoint, e.g. `https://cdn.jwplayer.com/v2/media/<id>`. */\n  playlistUrl?: string;\n  posterUrl?: string;\n  title?: string;\n  subtitle?: string;\n  aspectRatio?: \"16/9\" | \"21/9\" | \"4/3\" | \"1/1\";\n  /** A colour preset, or `default` for JW's own control bar. */\n  skin?: JwSkinPreset;\n  /** Raw JW `skin` config. Wins over `skin` when both are given. */\n  skinConfig?: JwSkinConfig;\n  /** External skin stylesheet plus the class name it defines. */\n  skinUrl?: string;\n  skinName?: string;\n  autoStart?: boolean;\n  muted?: boolean;\n  repeat?: boolean;\n  controls?: boolean;\n  /** Merged last into `jwplayer().setup()` — an escape hatch for anything else. */\n  playerOptions?: Record<string, unknown>;\n  enableGlow?: boolean;\n  /**\n   * The title/subtitle laid over the frame: at the foot until the video is\n   * first played, then a hover-only bar at the top. Turn it off for a bare\n   * player with no copy on it.\n   */\n  showOverlay?: boolean;\n  onReady?: () => void;\n}\n\nconst aspectRatios = {\n  \"16/9\": \"aspect-video\",\n  \"21/9\": \"aspect-[21/9]\",\n  \"4/3\": \"aspect-[4/3]\",\n  \"1/1\": \"aspect-square\",\n};\n\n/** JW's `aspectratio` uses `w:h`, not the CSS `w/h` this component takes. */\nconst jwRatios: Record<string, string> = {\n  \"16/9\": \"16:9\",\n  \"21/9\": \"21:9\",\n  \"4/3\": \"4:3\",\n  \"1/1\": \"1:1\",\n};\n\ntype JwPlayer = {\n  setup: (options: Record<string, unknown>) => JwPlayer;\n  on: (event: string, handler: (e?: unknown) => void) => JwPlayer;\n  remove: () => void;\n};\n\ntype JwGlobal = ((target: string) => JwPlayer) & { key?: string };\n\n/**\n * One in-flight load per library URL.\n *\n * Every player on a page shares the same `window.jwplayer`, so without this a\n * grid of four would append four copies of a ~400KB script and race each other\n * to define the global.\n */\nconst libraryLoads = new Map<string, Promise<JwGlobal>>();\n\nfunction loadJwLibrary(url: string): Promise<JwGlobal> {\n  const cached = libraryLoads.get(url);\n  if (cached) return cached;\n\n  const pending = new Promise<JwGlobal>((resolve, reject) => {\n    const existing = (window as unknown as { jwplayer?: JwGlobal }).jwplayer;\n    if (existing) {\n      resolve(existing);\n      return;\n    }\n\n    const script = document.createElement(\"script\");\n    script.src = url;\n    script.async = true;\n    script.onload = () => {\n      const jw = (window as unknown as { jwplayer?: JwGlobal }).jwplayer;\n      if (jw) resolve(jw);\n      else reject(new Error(\"JW library loaded but window.jwplayer is undefined\"));\n    };\n    script.onerror = () => reject(new Error(`Failed to load JW library: ${url}`));\n    document.head.appendChild(script);\n  });\n\n  // A failed load must not be cached, or a transient network error would leave\n  // every later mount resolving the same rejection for the life of the page.\n  pending.catch(() => libraryLoads.delete(url));\n  libraryLoads.set(url, pending);\n  return pending;\n}\n\nfunction resolveSkin(\n  skin: JwSkinPreset,\n  skinConfig?: JwSkinConfig,\n  skinUrl?: string,\n  skinName?: string,\n): JwSkinConfig | undefined {\n  const base =\n    skinConfig ?? (skin === \"default\" ? undefined : SKIN_PRESETS[skin]);\n  if (!skinUrl && !skinName) return base;\n  return { ...(base ?? {}), ...(skinUrl ? { url: skinUrl } : {}), ...(skinName ? { name: skinName } : {}) };\n}\n\n/**\n * Title and subtitle laid over the frame, following the convention YouTube set.\n *\n * Before anything has played the copy sits at the FOOT of the frame and stays\n * there: nothing is happening yet, so it is free to introduce the video, and a\n * viewer should not have to hover to find out what they are about to watch.\n * Its bottom padding keeps it clear of JW's control bar, so the gradient\n * reaches the bottom edge but the text stops above the scrubber.\n *\n * Once playback has started that is no longer true — the picture is the point,\n * and a permanent caption is in the way. So the copy moves to the TOP of the\n * frame and only appears on hover, where it overlaps nothing that matters.\n *\n * `pointer-events-none` keeps every click going through to JW in both\n * positions.\n */\nfunction MediaOverlay({\n  title,\n  subtitle,\n  hasPlayed,\n}: {\n  title?: string;\n  subtitle?: string;\n  /** Whether the viewer has started watching. Drives the whole treatment. */\n  hasPlayed?: boolean;\n}) {\n  if (!title && !subtitle) return null;\n\n  const copy = (\n    <>\n      {title && (\n        <h3 className=\"line-clamp-1 text-base font-semibold tracking-tight text-white drop-shadow-sm sm:text-xl md:text-2xl\">\n          {title}\n        </h3>\n      )}\n      {subtitle && (\n        <p className=\"mt-0.5 line-clamp-1 text-[11px] text-zinc-300 sm:text-xs md:text-sm\">\n          {subtitle}\n        </p>\n      )}\n    </>\n  );\n\n  if (hasPlayed) {\n    return (\n      <div className=\"pointer-events-none absolute inset-x-0 top-0 z-10 bg-gradient-to-b from-black/85 via-black/40 to-transparent px-4 pt-4 pb-16 opacity-0 transition-opacity duration-300 group-hover/frame:opacity-100 group-focus-within/frame:opacity-100 sm:px-6 sm:pt-5 sm:pb-20\">\n        {copy}\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/90 via-black/50 to-transparent px-4 pt-16 pb-14 transition-opacity duration-300 sm:px-6 sm:pt-24 sm:pb-16\">\n      {copy}\n    </div>\n  );\n}\n\nexport const JwPlayer = React.forwardRef<HTMLDivElement, JwPlayerProps>(\n  (\n    {\n      libraryUrl = JW_DEMO_LIBRARY_URL,\n      licenseKey,\n      file,\n      playlistUrl = \"https://cdn.jwplayer.com/v2/media/hWF9vG66\",\n      posterUrl = \"https://res.cloudinary.com/dodndg7ai/image/upload/f_webp,q_auto,w_1920,c_limit/v1790146210/photo-1506744038136-46273834b3fb-1790146212208.jpg\",\n      title = \"Enterprise-grade video delivery\",\n      subtitle = \"Adaptive streaming, analytics and DRM behind one control bar.\",\n      aspectRatio = \"16/9\",\n      skin = \"default\",\n      skinConfig,\n      skinUrl,\n      skinName,\n      autoStart = false,\n      muted = false,\n      repeat = false,\n      controls = true,\n      playerOptions,\n      enableGlow = true,\n      showOverlay = true,\n      onReady,\n      className,\n      ...props\n    },\n    ref,\n  ) => {\n    // React's useId contains colons, which are legal in an id attribute but not\n    // in the CSS selectors JW resolves the target with.\n    const reactId = useId();\n    const containerId = `jw-player-${reactId.replace(/[^a-zA-Z0-9]/g, \"\")}`;\n\n    const [status, setStatus] = useState<\"loading\" | \"ready\" | \"error\">(\"loading\");\n    // Latches on the first play and never goes back: the title treatment keys\n    // off \"has this viewer started watching\", not the current paused state, so\n    // pausing must not bring the bottom caption back over the picture.\n    const [hasPlayed, setHasPlayed] = useState(false);\n    const onReadyRef = useRef(onReady);\n    useEffect(() => {\n      onReadyRef.current = onReady;\n    });\n\n    // `skinConfig` and `playerOptions` are object literals, so they are new\n    // references on every parent render. The effect keys off their serialized\n    // values and reads the live objects through refs — depending on the objects\n    // themselves would rebuild the player on every render, restarting playback.\n    const resolvedSkin = resolveSkin(skin, skinConfig, skinUrl, skinName);\n    const skinKey = JSON.stringify(resolvedSkin ?? null);\n    const optionsKey = playerOptions ? JSON.stringify(playerOptions) : \"\";\n    const setupRef = useRef({ skin: resolvedSkin, options: playerOptions });\n    useEffect(() => {\n      setupRef.current = { skin: resolvedSkin, options: playerOptions };\n    });\n\n    // Every input the player is built from. When any of them changes the\n    // player is rebuilt, so it is loading again and has not been played yet.\n    // Reset while rendering, when the setup changes, rather than in an effect.\n    const setupKey = JSON.stringify([\n      libraryUrl,\n      licenseKey,\n      file,\n      playlistUrl,\n      posterUrl,\n      aspectRatio,\n      autoStart,\n      muted,\n      repeat,\n      controls,\n      containerId,\n      skinKey,\n      optionsKey,\n    ]);\n    const [prevSetupKey, setPrevSetupKey] = useState(setupKey);\n    if (setupKey !== prevSetupKey) {\n      setPrevSetupKey(setupKey);\n      setStatus(\"loading\");\n      setHasPlayed(false);\n    }\n\n    useEffect(() => {\n      let cancelled = false;\n      let player: JwPlayer | null = null;\n\n      void loadJwLibrary(libraryUrl)\n        .then((jwplayer) => {\n          if (cancelled) return;\n          if (licenseKey) jwplayer.key = licenseKey;\n\n          const { skin: activeSkin, options } = setupRef.current;\n\n          player = jwplayer(containerId);\n          player.setup({\n            ...(playlistUrl ? { playlist: playlistUrl } : { file }),\n            image: posterUrl,\n            width: \"100%\",\n            aspectratio: jwRatios[aspectRatio],\n            autostart: autoStart,\n            mute: muted || autoStart,\n            repeat,\n            controls,\n            ...(activeSkin ? { skin: activeSkin } : {}),\n            ...(options ?? {}),\n          });\n\n          player.on(\"ready\", () => {\n            if (cancelled) return;\n            setStatus(\"ready\");\n            onReadyRef.current?.();\n          });\n          player.on(\"play\", () => {\n            if (!cancelled) setHasPlayed(true);\n          });\n          // A setup error (bad licence, unplayable media) is reported through\n          // the player rather than the promise, so it needs its own handler —\n          // otherwise the spinner spins forever on a page that will never play.\n          player.on(\"setupError\", () => {\n            if (!cancelled) setStatus(\"error\");\n          });\n        })\n        .catch(() => {\n          if (!cancelled) setStatus(\"error\");\n        });\n\n      return () => {\n        cancelled = true;\n        try {\n          player?.remove();\n        } catch {\n          /* already gone */\n        }\n      };\n    }, [\n      libraryUrl,\n      licenseKey,\n      file,\n      playlistUrl,\n      posterUrl,\n      aspectRatio,\n      autoStart,\n      muted,\n      repeat,\n      controls,\n      containerId,\n      skinKey,\n      optionsKey,\n    ]);\n\n    return (\n      <div ref={ref} className={cn(\"relative w-full\", className)} {...props}>\n        {enableGlow && (\n          <div className=\"pointer-events-none absolute -inset-4 z-0 rounded-3xl bg-gradient-to-tr from-primary/20 via-primary/15 to-primary/5 opacity-80 blur-3xl transition-opacity duration-500 dark:opacity-50\" />\n        )}\n\n        <div className=\"relative z-10 flex w-full flex-col overflow-hidden rounded-xl border border-border/80 bg-zinc-900 shadow-2xl sm:rounded-2xl md:rounded-3xl\">\n          <div\n            className={cn(\n              \"group/frame relative w-full overflow-hidden bg-black\",\n              aspectRatios[aspectRatio],\n            )}\n          >\n            {/* JW replaces this node wholesale on setup. It is kept mounted in\n                every state so a re-render never pulls the target out from under\n                a player that is mid-initialisation. */}\n            <div\n              id={containerId}\n              className={cn(\"h-full w-full\", status !== \"ready\" && \"invisible\")}\n            />\n\n            {status === \"loading\" && (\n              <div className=\"absolute inset-0 flex items-center justify-center bg-zinc-950\">\n                <span className=\"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/80\" />\n              </div>\n            )}\n\n            {/* The library is licensed and remote, so it can be absent in a way\n                Plyr and <video> never are. Falling back to the browser's own\n                player keeps the media watchable instead of leaving a black box. */}\n            {status === \"error\" && (\n              <div className=\"absolute inset-0 flex flex-col bg-zinc-950\">\n                {file ? (\n                  <video\n                    className=\"h-full w-full flex-1 bg-black object-contain\"\n                    poster={posterUrl}\n                    controls\n                    playsInline\n                    preload=\"metadata\"\n                    src={file}\n                  />\n                ) : (\n                  // A JW playlist is only resolvable by JW, so with the library\n                  // gone there is no media to hand a <video>. The poster is all\n                  // that is left, and it beats a black rectangle.\n                  <img\n                    src={posterUrl}\n                    alt=\"\"\n                    className=\"h-full w-full flex-1 object-cover opacity-60\"\n                  />\n                )}\n                <p className=\"flex items-center gap-2 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-300\">\n                  <AlertTriangle className=\"h-3.5 w-3.5 shrink-0\" />\n                  {file\n                    ? \"JW Player library unavailable — falling back to the native player.\"\n                    : \"JW Player library unavailable, and a JW playlist cannot be played without it. Set `file` for a native fallback.\"}\n                </p>\n              </div>\n            )}\n\n            {status === \"ready\" && showOverlay && (\n              <MediaOverlay\n                title={title}\n                subtitle={subtitle}\n                hasPlayed={hasPlayed}\n              />\n            )}\n          </div>\n\n        </div>\n      </div>\n    );\n  },\n);\n\nJwPlayer.displayName = \"JwPlayer\";\n",
      "type": "registry:component",
      "target": "components/custom/blocks/VideoPlayerJwBlock.tsx"
    }
  ],
  "docs": "Named exports: JwPlayer, JW_DEMO_LIBRARY_URL, plus the JwSkinConfig and JwSkinPreset types. No npm dependency — the JW library is a licensed remote script loaded from `libraryUrl`. It defaults to JW's public documentation library, which is fine to evaluate against but must be replaced with your own `https://cdn.jwplayer.com/libraries/<PLAYER_ID>.js` before shipping; a self-hosted build also needs `licenseKey`. `skin` picks a colour preset (default | midnight | neon | sunset | minimal), `skinConfig` takes a raw JW skin object, and `skinUrl` / `skinName` point at a custom stylesheet. If the library fails to load the component falls back to a native <video> rather than a black box.",
  "categories": [
    "media"
  ],
  "type": "registry:component"
}
