{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "wave-regions",
  "title": "Wave Regions",
  "description": "Wave player with interactive region markers for audio segments.",
  "dependencies": [
    "wavesurfer.js",
    "lucide-react"
  ],
  "registryDependencies": [
    "@waves-cn/wave-cn",
    "button",
    "card",
    "slider"
  ],
  "files": [
    {
      "path": "src/registry/components/wave-regions.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport RegionsPlugin, {\n  type Region,\n} from \"wavesurfer.js/dist/plugins/regions.esm.js\";\nimport { cn } from \"@/lib/utils\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { Button } from \"@/components/ui/button\";\nimport { Slider } from \"@/components/ui/slider\";\nimport {\n  Play,\n  Pause,\n  Volume2,\n  VolumeX,\n  RotateCcw,\n  Repeat,\n  Trash2,\n} from \"lucide-react\";\nimport WavesurferPlayer, { formatTime, useWavePlayer } from \"@/lib/wave-cn\";\nimport type WaveSurfer from \"wavesurfer.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface RegionData {\n  id: string;\n  start: number;\n  end: number;\n  color?: string;\n  content?: string;\n}\n\nexport interface WaveRegionsProps {\n  /** Audio source URL */\n  src: string;\n  /** Optional title shown above the waveform */\n  title?: string;\n  /** Initial volume (0–1) */\n  defaultVolume?: number;\n  /** Allow creating and editing regions */\n  editable?: boolean;\n  /** Default color for new regions @default \"color-mix(in oklab, var(--primary) 25%, transparent)\" */\n  regionColor?: string;\n  /** Color for the active (looping) region @default \"color-mix(in oklab, var(--primary) 45%, transparent)\" */\n  activeRegionColor?: string;\n  /** Audio bar color. Accepts any CSS value including var(--*) tokens @default \"var(--muted-foreground)\" */\n  waveColor?: string;\n  /** Progress bar color. Accepts any CSS value including var(--*) tokens @default \"var(--primary)\" */\n  progressColor?: string;\n  /** Waveform bar width in px @default 3 */\n  barWidth?: number;\n  /** Waveform bar gap in px @default 2 */\n  barGap?: number;\n  /** Rounded borders for bars @default 2 */\n  barRadius?: number;\n  /** Waveform height in px @default 64 */\n  waveHeight?: number;\n  /** Called when a region is created by the user */\n  onRegionCreated?: (region: RegionData) => void;\n  /** Called when a region is updated (moved/resized) */\n  onRegionUpdated?: (region: RegionData) => void;\n  /** Called when a region is removed */\n  onRegionRemoved?: (id: string) => void;\n  /** Called when a region is clicked */\n  onRegionClicked?: (region: RegionData) => void;\n  /** Called when playback starts */\n  onPlay?: () => void;\n  /** Called when playback pauses */\n  onPause?: () => void;\n  /** Called when playback finishes */\n  onFinish?: () => void;\n  /** Called with current time on every audio process tick */\n  onTimeUpdate?: (currentTime: number, duration: number) => void;\n  className?: string;\n}\n\ntype RegionsPluginInstance = InstanceType<typeof RegionsPlugin>;\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction toRegionData(r: Region): RegionData {\n  return {\n    id: r.id,\n    start: r.start,\n    end: r.end,\n    color: r.color,\n    content: r.content?.textContent ?? undefined,\n  };\n}\n\n// ─── Component ───────────────────────────────────────────────────────────────\n\nexport function WaveRegions({\n  src,\n  title,\n  defaultVolume = 0.8,\n  editable = true,\n  regionColor = \"color-mix(in oklab, var(--primary) 25%, transparent)\",\n  activeRegionColor = \"color-mix(in oklab, var(--primary) 45%, transparent)\",\n  waveColor,\n  progressColor,\n  barWidth,\n  barGap,\n  barRadius,\n  waveHeight,\n  onRegionCreated,\n  onRegionUpdated,\n  onRegionRemoved,\n  onRegionClicked,\n  onPlay,\n  onPause,\n  onFinish,\n  onTimeUpdate,\n  className,\n}: WaveRegionsProps) {\n  const [regionsPlugin, setRegionsPlugin] =\n    React.useState<RegionsPluginInstance | null>(null);\n  const [regions, setRegions] = React.useState<RegionData[]>([]);\n  const [activeRegionId, setActiveRegionId] = React.useState<string | null>(\n    null,\n  );\n  const [isLooping, setIsLooping] = React.useState(false);\n\n  // Latest props/state readable from plugin listeners without re-subscribing.\n  const latest = React.useRef({\n    editable,\n    regionColor,\n    activeRegionId,\n    onRegionCreated,\n    onRegionUpdated,\n    onRegionRemoved,\n    onRegionClicked,\n  });\n  React.useEffect(() => {\n    latest.current = {\n      editable,\n      regionColor,\n      activeRegionId,\n      onRegionCreated,\n      onRegionUpdated,\n      onRegionRemoved,\n      onRegionClicked,\n    };\n  });\n\n  // ── Memoized plugin ──────────────────────────────────────────────────────\n  const plugins = React.useMemo(\n    () => (typeof document === \"undefined\" ? [] : [RegionsPlugin.create()]),\n    [],\n  );\n\n  // ── Player ───────────────────────────────────────────────────────────────\n  const player = useWavePlayer({\n    defaultVolume,\n    onPlay,\n    onPause,\n    onFinish,\n    onTimeUpdate,\n    onReady: (ws) => {\n      const live = ws\n        .getActivePlugins()\n        .find((p) => p instanceof RegionsPlugin) as\n        | RegionsPluginInstance\n        | undefined;\n      setRegionsPlugin(live ?? null);\n    },\n  });\n\n  const handlers = React.useMemo(\n    () => ({\n      ...player.handlers,\n      onDestroy: (ws: WaveSurfer) => {\n        player.handlers.onDestroy?.(ws);\n        setRegionsPlugin(null);\n        setRegions([]);\n        setActiveRegionId(null);\n        setIsLooping(false);\n      },\n    }),\n    [player.handlers],\n  );\n\n  // ── Drag selection ───────────────────────────────────────────────────────\n  React.useEffect(() => {\n    if (!regionsPlugin || !editable) return;\n    return regionsPlugin.enableDragSelection({\n      color: regionColor,\n      resize: true,\n      drag: true,\n    });\n  }, [regionsPlugin, editable, regionColor]);\n\n  // ── Region events ────────────────────────────────────────────────────────\n  React.useEffect(() => {\n    const rp = regionsPlugin;\n    if (!rp) return;\n\n    const unsubs = [\n      rp.on(\"region-created\", (region: Region) => {\n        const { editable, regionColor, onRegionCreated } = latest.current;\n        if (editable) {\n          region.setOptions({ color: regionColor, resize: true, drag: true });\n        }\n        const data = toRegionData(region);\n        setRegions((prev) => {\n          if (prev.some((r) => r.id === data.id)) return prev;\n          return [...prev, data];\n        });\n        onRegionCreated?.(data);\n      }),\n\n      rp.on(\"region-updated\", (region: Region) => {\n        const data = toRegionData(region);\n        setRegions((prev) =>\n          prev.map((r) => (r.id === data.id ? data : r)),\n        );\n        latest.current.onRegionUpdated?.(data);\n      }),\n\n      rp.on(\"region-removed\", (region: Region) => {\n        setRegions((prev) => prev.filter((r) => r.id !== region.id));\n        setActiveRegionId((prev) => (prev === region.id ? null : prev));\n        if (latest.current.activeRegionId === region.id) setIsLooping(false);\n        latest.current.onRegionRemoved?.(region.id);\n      }),\n\n      rp.on(\"region-clicked\", (region: Region, e: MouseEvent) => {\n        e.stopPropagation();\n        setActiveRegionId(region.id);\n        latest.current.onRegionClicked?.(toRegionData(region));\n      }),\n    ];\n\n    return () => unsubs.forEach((u) => u());\n  }, [regionsPlugin]);\n\n  // ── Loop active region ───────────────────────────────────────────────────\n  React.useEffect(() => {\n    const ws = player.wavesurfer.current;\n    const rp = regionsPlugin;\n    if (!ws || !rp || !isLooping || !activeRegionId) return;\n\n    const active = rp.getRegions().find((r) => r.id === activeRegionId);\n    if (!active) return;\n\n    // Play the active region\n    active.play();\n\n    const unsub = rp.on(\"region-out\", (region) => {\n      if (region.id === active.id) active.play();\n    });\n\n    return () => unsub();\n  }, [player.wavesurfer, regionsPlugin, isLooping, activeRegionId]);\n\n  // ── Highlight active region ──────────────────────────────────────────────\n  React.useEffect(() => {\n    if (!regionsPlugin) return;\n    regionsPlugin.getRegions().forEach((r) => {\n      r.setOptions({\n        color: r.id === activeRegionId ? activeRegionColor : regionColor,\n      });\n    });\n  }, [regionsPlugin, activeRegionId, regionColor, activeRegionColor]);\n\n  // ── Controls ─────────────────────────────────────────────────────────────\n\n  const { seek, setVolume } = player;\n  const handleSeek = React.useCallback(([v]: number[]) => seek(v), [seek]);\n  const handleVolume = React.useCallback(\n    ([v]: number[]) => setVolume(v),\n    [setVolume],\n  );\n\n  const toggleLoop = React.useCallback(() => {\n    setIsLooping((prev) => !prev);\n  }, []);\n\n  const removeActiveRegion = React.useCallback(() => {\n    if (!activeRegionId || !regionsPlugin) return;\n    const active = regionsPlugin\n      .getRegions()\n      .find((r) => r.id === activeRegionId);\n    active?.remove();\n  }, [regionsPlugin, activeRegionId]);\n\n  // ── Derived ──────────────────────────────────────────────────────────────\n  const { isReady, isPlaying, isMuted, volume, currentTime, duration, progress } =\n    player;\n  const activeRegion = activeRegionId\n    ? regions.find((r) => r.id === activeRegionId)\n    : undefined;\n\n  // ── Render ─────────────────────────────────────────────────────────────\n  return (\n    <Card\n      className={cn(\n        \"w-full px-0 border-0 rounded-none bg-transparent\",\n        className,\n      )}\n    >\n      <CardContent className=\"border-0 px-0 space-y-3\">\n        {title && (\n          <p className=\"text-sm font-medium text-foreground truncate\">\n            {title}\n          </p>\n        )}\n\n        {/* Waveform with regions */}\n        <div className=\"relative w-full rounded-sm overflow-hidden bg-muted/40\">\n          <WavesurferPlayer\n            url={src}\n            waveColor={waveColor}\n            progressColor={progressColor}\n            height={waveHeight}\n            barWidth={barWidth}\n            barGap={barGap}\n            barRadius={barRadius}\n            dragToSeek\n            plugins={plugins}\n            {...handlers}\n          />\n        </div>\n\n        {/* Region info */}\n        {regions.length > 0 && (\n          <p className=\"text-xs text-muted-foreground\">\n            {regions.length} region{regions.length !== 1 ? \"s\" : \"\"}\n            {activeRegionId && (\n              <>\n                {\" · \"}\n                <span className=\"font-medium text-foreground\">\n                  Active: {formatTime(activeRegion?.start ?? 0)}–\n                  {formatTime(activeRegion?.end ?? 0)}\n                </span>\n              </>\n            )}\n          </p>\n        )}\n\n        {/* Seek bar */}\n        <div className=\"flex items-center gap-2\">\n          <span className=\"text-[11px] tabular-nums text-muted-foreground w-10 text-right shrink-0\">\n            {formatTime(currentTime)}\n          </span>\n          <Slider\n            className=\"flex-1\"\n            value={[progress]}\n            min={0}\n            max={1}\n            step={0.001}\n            disabled={!isReady}\n            onValueChange={handleSeek}\n            aria-label=\"Seek\"\n          />\n          <span className=\"text-[11px] tabular-nums text-muted-foreground w-10 shrink-0\">\n            {formatTime(duration)}\n          </span>\n        </div>\n\n        {/* Controls */}\n        <div className=\"flex items-center justify-between gap-3\">\n          <div className=\"flex items-center gap-1.5\">\n            <Button\n              size=\"icon\"\n              variant=\"ghost\"\n              className=\"h-8 w-8 text-muted-foreground hover:text-foreground\"\n              disabled={!isReady}\n              onClick={player.restart}\n              aria-label=\"Restart\"\n            >\n              <RotateCcw size={15} />\n            </Button>\n            <Button\n              size=\"icon\"\n              variant=\"secondary\"\n              className=\"h-9 w-9\"\n              disabled={!isReady}\n              onClick={player.togglePlay}\n              aria-label={isPlaying ? \"Pause\" : \"Play\"}\n            >\n              {isPlaying ? <Pause size={17} /> : <Play size={17} />}\n            </Button>\n\n            {/* Loop active region */}\n            <Button\n              size=\"icon\"\n              variant={isLooping ? \"default\" : \"ghost\"}\n              className=\"h-8 w-8 text-muted-foreground hover:text-foreground\"\n              disabled={!isReady || !activeRegionId}\n              onClick={toggleLoop}\n              aria-label={isLooping ? \"Stop looping\" : \"Loop active region\"}\n            >\n              <Repeat size={15} />\n            </Button>\n\n            {/* Remove active region */}\n            {editable && activeRegionId && (\n              <Button\n                size=\"icon\"\n                variant=\"ghost\"\n                className=\"h-8 w-8 text-muted-foreground hover:text-destructive\"\n                onClick={removeActiveRegion}\n                aria-label=\"Remove active region\"\n              >\n                <Trash2 size={15} />\n              </Button>\n            )}\n          </div>\n\n          {/* Volume */}\n          <div className=\"flex items-center gap-2 w-36\">\n            <Button\n              size=\"icon\"\n              variant=\"ghost\"\n              className=\"h-7 w-7 shrink-0 text-muted-foreground hover:text-foreground\"\n              onClick={player.toggleMute}\n              aria-label={isMuted ? \"Unmute\" : \"Mute\"}\n            >\n              {isMuted ? <VolumeX size={15} /> : <Volume2 size={15} />}\n            </Button>\n            <Slider\n              value={[isMuted ? 0 : volume]}\n              min={0}\n              max={1}\n              step={0.01}\n              onValueChange={handleVolume}\n              aria-label=\"Volume\"\n            />\n          </div>\n        </div>\n\n        {/* Hint */}\n        {editable && isReady && regions.length === 0 && (\n          <p className=\"text-xs text-muted-foreground/60 text-center\">\n            Click and drag on the waveform to create a region\n          </p>\n        )}\n      </CardContent>\n    </Card>\n  );\n}\n\nexport default WaveRegions;\n",
      "type": "registry:component",
      "target": "components/waves-cn/wave-regions.tsx"
    }
  ],
  "type": "registry:component"
}