{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sound-text",
  "type": "registry:ui",
  "title": "Sound Text",
  "description": "Animated typography that synchronizes with audio frequencies.",
  "dependencies": [
    "react",
    "motion"
  ],
  "devDependencies": [
    "@types/react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "ui/sound-text.tsx",
      "content": "'use client';\n\nimport React, { useRef, useCallback, useEffect } from 'react';\nimport { motion, useAnimationControls } from 'motion/react';\nimport { cn } from '@/lib/utils';\n\ninterface SoundTextProps {\n  text: string;\n  className?: string;\n  basePitch?: number; // Base frequency in Hz\n}\n\n// Simple Pentatonic Scale frequencies (approximate) relative to a base\n// We will just multiply the base freq by these ratios\nconst SCALE_RATIOS = [\n  1, // Root\n  1.125, // Major 2nd\n  1.25, // Major 3rd\n  1.5, // Perfect 5th\n  1.667, // Major 6th\n  2, // Octave\n];\n\nexport default function SoundText({\n  text = 'Hover over me',\n  className,\n  basePitch = 300,\n}: SoundTextProps) {\n  const audioContextRef = useRef<AudioContext | null>(null);\n\n  // Initialize AudioContext lazily on user interaction\n  const initAudio = useCallback(() => {\n    if (!audioContextRef.current) {\n      audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();\n    }\n    if (audioContextRef.current.state === 'suspended') {\n      audioContextRef.current.resume();\n    }\n  }, []);\n\n  const playSound = useCallback(\n    (index: number) => {\n      initAudio(); // Ensure context is ready\n      if (!audioContextRef.current) return;\n\n      const ctx = audioContextRef.current;\n      const osc = ctx.createOscillator();\n      const gain = ctx.createGain();\n\n      // Calculate pitch based on index to create a melody effect\n      // Cycle through the scale\n      const scaleIndex = index % SCALE_RATIOS.length;\n      const octaveOffset = Math.floor(index / SCALE_RATIOS.length);\n      const frequency = basePitch * SCALE_RATIOS[scaleIndex] * Math.pow(2, octaveOffset * 0.5); // Slight octave overlapping for smoother sound\n\n      osc.type = 'sine';\n      osc.frequency.setValueAtTime(frequency, ctx.currentTime);\n\n      // Envelope: Fast attack, smooth decay\n      gain.gain.setValueAtTime(0, ctx.currentTime);\n      gain.gain.linearRampToValueAtTime(0.3, ctx.currentTime + 0.02); // Attack\n      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3); // Decay\n\n      osc.connect(gain);\n      gain.connect(ctx.destination);\n\n      osc.start();\n      osc.stop(ctx.currentTime + 0.4);\n    },\n    [basePitch, initAudio]\n  );\n\n  // Cleanup\n  useEffect(() => {\n    return () => {\n      const ctx = audioContextRef.current;\n      if (ctx && ctx.state !== 'closed') {\n        ctx.close().catch(() => {\n          // Ignore already closed errors or others\n        });\n      }\n    };\n  }, []);\n\n  const letters = text.split('');\n  const lastTouchedIndex = useRef<number | null>(null);\n\n  const handleTouch = (clientX: number, clientY: number) => {\n    initAudio();\n    const elem = document.elementFromPoint(clientX, clientY);\n    if (!elem) return;\n    const letterSpan = elem.closest('[data-sound-index]');\n    if (letterSpan) {\n      const idxStr = letterSpan.getAttribute('data-sound-index');\n      if (idxStr !== null) {\n        const idx = parseInt(idxStr, 10);\n        if (lastTouchedIndex.current !== idx) {\n          lastTouchedIndex.current = idx;\n          playSound(idx);\n          letterSpan.dispatchEvent(new CustomEvent('trigger-sound-anim'));\n        }\n      }\n    }\n  };\n\n  const handleTouchStart = (e: React.TouchEvent) => {\n    initAudio();\n    if (e.touches.length > 0) {\n      handleTouch(e.touches[0].clientX, e.touches[0].clientY);\n    }\n  };\n\n  const handleTouchMove = (e: React.TouchEvent) => {\n    if (e.touches.length > 0) {\n      handleTouch(e.touches[0].clientX, e.touches[0].clientY);\n    }\n  };\n\n  const handleTouchEnd = () => {\n    lastTouchedIndex.current = null;\n  };\n\n  const containerVariants = {\n    hover: {\n      transition: { staggerChildren: 0.05 },\n    },\n  };\n\n  return (\n    <motion.div\n      className={cn('flex cursor-default flex-wrap select-none touch-none', className)}\n      variants={containerVariants}\n      initial=\"initial\"\n      whileHover=\"hover\"\n      onMouseEnter={initAudio}\n      onTouchStart={handleTouchStart}\n      onTouchMove={handleTouchMove}\n      onTouchEnd={handleTouchEnd}\n      onTouchCancel={handleTouchEnd}\n    >\n      {letters.map((letter, index) => {\n        // If it's a space, render it but no sound triggers usually (or keep it for rhythm)\n        if (letter === ' ') {\n          return (\n            <span key={index} className=\"w-2\">\n              {' '}\n            </span>\n          );\n        }\n\n        return <Letter key={index} char={letter} index={index} onHover={() => playSound(index)} />;\n      })}\n    </motion.div>\n  );\n}\n\n// Individual Letter Component for cleaner animation isolation\nconst Letter = ({ char, index, onHover }: { char: string; index: number; onHover: () => void }) => {\n  const controls = useAnimationControls();\n  const elementRef = useRef<HTMLSpanElement>(null);\n\n  // Random subtle rotation for \"organic\" feel\n  const randomRotate = Math.random() * 10 - 5;\n\n  const triggerAnimation = useCallback(() => {\n    controls.start({\n      y: -10,\n      scale: 1.3,\n      rotate: randomRotate,\n      color: '#A855F7', // Purple-500 highlight\n      textShadow: '0px 0px 8px rgba(168, 85, 247, 0.6)',\n      transition: { type: 'spring', stiffness: 500, damping: 10 },\n    });\n    setTimeout(() => {\n      controls.start({\n        y: 0,\n        scale: 1,\n        rotate: 0,\n        color: 'currentColor',\n        textShadow: 'none',\n        transition: { type: 'spring', stiffness: 300, damping: 20 },\n      });\n    }, 350);\n  }, [controls, randomRotate]);\n\n  useEffect(() => {\n    const el = elementRef.current;\n    if (!el) return;\n    const onTrigger = () => triggerAnimation();\n    el.addEventListener('trigger-sound-anim', onTrigger);\n    return () => el.removeEventListener('trigger-sound-anim', onTrigger);\n  }, [triggerAnimation]);\n\n  return (\n    <motion.span\n      ref={elementRef}\n      data-sound-index={index}\n      className=\"relative inline-block\"\n      onMouseEnter={() => {\n        onHover();\n        triggerAnimation();\n      }}\n      onMouseLeave={() => {\n        controls.start({\n          y: 0,\n          scale: 1,\n          rotate: 0,\n          color: 'currentColor',\n          textShadow: 'none',\n          transition: { type: 'spring', stiffness: 300, damping: 20 },\n        });\n      }}\n      animate={controls}\n      // Add initial subtle fade-in for page load\n      initial={{ opacity: 0, y: 20 }}\n      whileInView={{ opacity: 1, y: 0 }}\n      viewport={{ once: true }}\n      transition={{ delay: index * 0.02, type: 'spring', stiffness: 200 }}\n    >\n      {char}\n    </motion.span>\n  );\n};\n",
      "type": "registry:ui"
    }
  ]
}