@nice2dev/ui-audio 1.1.6 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/config/noteSoundSets.d.ts +2 -2
  3. package/dist/core/audioIcons.d.ts +1 -1
  4. package/dist/dmx/DmxEditor.d.ts +1 -1
  5. package/dist/editor/panels/LayerTrack.d.ts +1 -1
  6. package/dist/effects/noteShapes.d.ts +12 -0
  7. package/dist/index.cjs +41 -41
  8. package/dist/index.mjs +8353 -8095
  9. package/dist/karaoke/KaraokeSelectionMode.d.ts +4 -1
  10. package/dist/karaoke/KaraokeSessionJoin.d.ts +5 -2
  11. package/dist/karaoke/KaraokeSetupPanel.d.ts +5 -3
  12. package/dist/karaoke/rendering/karaokeDisplaySettings.d.ts +2 -2
  13. package/dist/karaoke/rendering/karaokeSettings.d.ts +6 -6
  14. package/dist/karaoke/rendering/textureCatalog.d.ts +1 -1
  15. package/dist/lighting/NiceDMXTimeline.d.ts +1 -1
  16. package/dist/midi/oxygen25Profile.d.ts +9 -9
  17. package/dist/models/modelsAiVideo.d.ts +1 -1
  18. package/dist/models/modelsPlatforms.d.ts +1 -1
  19. package/dist/models/modelsPlaylistManager.d.ts +2 -2
  20. package/dist/playlist/tagIcons.d.ts +30 -0
  21. package/dist/radio/NiceRadioPlayer.d.ts +2 -3
  22. package/dist/ui-audio.css +1 -1
  23. package/dist/utils/audioPitchAlgorithms.d.ts +1 -1
  24. package/dist/utils/colorResolver.d.ts +2 -1
  25. package/dist/utils/latencyEstimate.d.ts +1 -1
  26. package/package.json +3 -3
  27. package/dist/__benchmarks__/audio-latency.bench.d.ts.map +0 -1
  28. package/dist/config/noteSoundSets.d.ts.map +0 -1
  29. package/dist/constants/audioColors.d.ts.map +0 -1
  30. package/dist/constants/debugKaraoke.d.ts.map +0 -1
  31. package/dist/constants/index.d.ts.map +0 -1
  32. package/dist/constants/karaokeScoringConfig.d.ts.map +0 -1
  33. package/dist/constants/playerColors.d.ts.map +0 -1
  34. package/dist/constants/ui.d.ts.map +0 -1
  35. package/dist/core/NiceAudioErrorBoundary.d.ts.map +0 -1
  36. package/dist/core/audioIcons.d.ts.map +0 -1
  37. package/dist/core/i18n.d.ts.map +0 -1
  38. package/dist/dmx/DmxChannelControls.d.ts.map +0 -1
  39. package/dist/dmx/DmxEditor.d.ts.map +0 -1
  40. package/dist/dmx/dmxService.d.ts.map +0 -1
  41. package/dist/editor/AudioClipBox.d.ts.map +0 -1
  42. package/dist/editor/AudioClipInfo.d.ts.map +0 -1
  43. package/dist/editor/AudioEditorPianoRoll.d.ts.map +0 -1
  44. package/dist/editor/AudioEditorPianoRollContainer.d.ts.map +0 -1
  45. package/dist/editor/AudioLayerDetails.d.ts.map +0 -1
  46. package/dist/editor/AudioLayerDetailsContainer.d.ts.map +0 -1
  47. package/dist/editor/AudioLayersNavContainer.d.ts.map +0 -1
  48. package/dist/editor/AudioMiniMap.d.ts.map +0 -1
  49. package/dist/editor/AudioMiniMapContainer.d.ts.map +0 -1
  50. package/dist/editor/AudioSourceDetails.d.ts.map +0 -1
  51. package/dist/editor/AudioStudio.d.ts.map +0 -1
  52. package/dist/editor/AudioTimeline.d.ts.map +0 -1
  53. package/dist/editor/AudioTimelineContainer.d.ts.map +0 -1
  54. package/dist/editor/AudioTimelineNavContainer.d.ts.map +0 -1
  55. package/dist/editor/CCLane.d.ts.map +0 -1
  56. package/dist/editor/CCLaneSelector.d.ts.map +0 -1
  57. package/dist/editor/NiceSampleBrowser.d.ts.map +0 -1
  58. package/dist/editor/PianoRoll.d.ts.map +0 -1
  59. package/dist/editor/Waveform.d.ts.map +0 -1
  60. package/dist/editor/editorDisplayModes.d.ts.map +0 -1
  61. package/dist/editor/editorIO.d.ts.map +0 -1
  62. package/dist/editor/hooks/index.d.ts.map +0 -1
  63. package/dist/editor/hooks/useAutoSave.d.ts.map +0 -1
  64. package/dist/editor/hooks/usePlaybackEngine.d.ts.map +0 -1
  65. package/dist/editor/hooks/useProjectCRUD.d.ts.map +0 -1
  66. package/dist/editor/hooks/useRecording.d.ts.map +0 -1
  67. package/dist/editor/nav/AudioLayersNav.d.ts.map +0 -1
  68. package/dist/editor/nav/AudioProjectSectionNav.d.ts.map +0 -1
  69. package/dist/editor/nav/AudioTimelineNav.d.ts.map +0 -1
  70. package/dist/editor/nav/SaveLoadControls.d.ts.map +0 -1
  71. package/dist/editor/panels/AdvancedEditingPanel.d.ts.map +0 -1
  72. package/dist/editor/panels/ArpeggiatorPanel.d.ts.map +0 -1
  73. package/dist/editor/panels/CCAutomationLaneEditor.d.ts.map +0 -1
  74. package/dist/editor/panels/DisplayModeSelector.d.ts.map +0 -1
  75. package/dist/editor/panels/EditorPanels.d.ts.map +0 -1
  76. package/dist/editor/panels/LFOPanel.d.ts.map +0 -1
  77. package/dist/editor/panels/LayerTrack.d.ts.map +0 -1
  78. package/dist/editor/panels/ProjectPanel.d.ts.map +0 -1
  79. package/dist/editor/panels/SectionPanel.d.ts.map +0 -1
  80. package/dist/editor/panels/StepSequencerPanel.d.ts.map +0 -1
  81. package/dist/editor/useEditorRecording.d.ts.map +0 -1
  82. package/dist/editor/useEditorTrack.d.ts.map +0 -1
  83. package/dist/effects/NoteParticles.d.ts.map +0 -1
  84. package/dist/effects/NoteRiver.d.ts.map +0 -1
  85. package/dist/effects/noteThemeColors.d.ts.map +0 -1
  86. package/dist/engine/NiceAudioEffects.d.ts.map +0 -1
  87. package/dist/engine/NiceAudioEffectsRack.d.ts.map +0 -1
  88. package/dist/engine/NiceAudioWorklet.d.ts.map +0 -1
  89. package/dist/engine/NiceMultitrackExport.d.ts.map +0 -1
  90. package/dist/engine/audioContext.d.ts.map +0 -1
  91. package/dist/engine/audioKeyboard.d.ts.map +0 -1
  92. package/dist/engine/audioLayerDetails.d.ts.map +0 -1
  93. package/dist/engine/audioPlaybackEngine.d.ts.map +0 -1
  94. package/dist/engine/audioProject.d.ts.map +0 -1
  95. package/dist/engine/audioSource.d.ts.map +0 -1
  96. package/dist/engine/audioTimeline.d.ts.map +0 -1
  97. package/dist/engine/audioUtils.d.ts.map +0 -1
  98. package/dist/engine/daw-core.d.ts.map +0 -1
  99. package/dist/engine/effects-pro.d.ts.map +0 -1
  100. package/dist/engine/generate-pitch-points.d.ts.map +0 -1
  101. package/dist/engine/instrumentPresets.d.ts.map +0 -1
  102. package/dist/engine/karaoke-pro.d.ts.map +0 -1
  103. package/dist/engine/midi-pro.d.ts.map +0 -1
  104. package/dist/engine/notation.d.ts.map +0 -1
  105. package/dist/engine/pitch-worklet-processor.d.ts.map +0 -1
  106. package/dist/engine/pitch_client.d.ts.map +0 -1
  107. package/dist/engine/recording.d.ts.map +0 -1
  108. package/dist/engine/simpleSynth.d.ts.map +0 -1
  109. package/dist/engine/sound-design.d.ts.map +0 -1
  110. package/dist/hooks/useCCAutomation.d.ts.map +0 -1
  111. package/dist/hooks/useStepSequencer.d.ts.map +0 -1
  112. package/dist/index.d.ts.map +0 -1
  113. package/dist/input/AudioInputPicker.d.ts.map +0 -1
  114. package/dist/input/VocalEffectsRack.d.ts.map +0 -1
  115. package/dist/karaoke/AudioPitchAnalyzer.d.ts.map +0 -1
  116. package/dist/karaoke/BarFillEditor.d.ts.map +0 -1
  117. package/dist/karaoke/KaraokeLyrics.d.ts.map +0 -1
  118. package/dist/karaoke/KaraokeManager.d.ts.map +0 -1
  119. package/dist/karaoke/KaraokeSelectionMode.d.ts.map +0 -1
  120. package/dist/karaoke/KaraokeSessionJoin.d.ts.map +0 -1
  121. package/dist/karaoke/KaraokeSetupPanel.d.ts.map +0 -1
  122. package/dist/karaoke/KaraokeSongBrowser.d.ts.map +0 -1
  123. package/dist/karaoke/KaraokeSummaryOverlay.d.ts.map +0 -1
  124. package/dist/karaoke/KaraokeTimeline.d.ts.map +0 -1
  125. package/dist/karaoke/KaraokeUploader.d.ts.map +0 -1
  126. package/dist/karaoke/LatencyCalibrator.d.ts.map +0 -1
  127. package/dist/karaoke/PadKaraokeOverlay.d.ts.map +0 -1
  128. package/dist/karaoke/VocalPerformanceReport.d.ts.map +0 -1
  129. package/dist/karaoke/karaokeTimelineTypes.d.ts.map +0 -1
  130. package/dist/karaoke/rendering/fontCatalog.d.ts.map +0 -1
  131. package/dist/karaoke/rendering/glossyBarCaps.d.ts.map +0 -1
  132. package/dist/karaoke/rendering/glossyBarPatterns.d.ts.map +0 -1
  133. package/dist/karaoke/rendering/glossyBarRenderer.d.ts.map +0 -1
  134. package/dist/karaoke/rendering/karaokeAnimations.d.ts.map +0 -1
  135. package/dist/karaoke/rendering/karaokeDisplaySettings.d.ts.map +0 -1
  136. package/dist/karaoke/rendering/karaokeLyrics.d.ts.map +0 -1
  137. package/dist/karaoke/rendering/karaokeNoteParsing.d.ts.map +0 -1
  138. package/dist/karaoke/rendering/karaokeSettings.d.ts.map +0 -1
  139. package/dist/karaoke/rendering/karaokeTimeline.d.ts.map +0 -1
  140. package/dist/karaoke/rendering/karaokeTimelineRenderer.d.ts.map +0 -1
  141. package/dist/karaoke/rendering/karaokeTimelineTypes.d.ts.map +0 -1
  142. package/dist/karaoke/rendering/padNotePlayer.d.ts.map +0 -1
  143. package/dist/karaoke/rendering/textureCache.d.ts.map +0 -1
  144. package/dist/karaoke/rendering/textureCatalog.d.ts.map +0 -1
  145. package/dist/karaoke/useKaraokePitch.d.ts.map +0 -1
  146. package/dist/karaoke/useKaraokeScoring.d.ts.map +0 -1
  147. package/dist/karaokeEditor/KaraokeEditorManager.d.ts.map +0 -1
  148. package/dist/karaokeEditor/KaraokePhaserRenderer.d.ts.map +0 -1
  149. package/dist/library/MusicLibraryExplorer.d.ts.map +0 -1
  150. package/dist/lighting/NiceDMXTimeline.d.ts.map +0 -1
  151. package/dist/midi/midiSeedGenerator.d.ts.map +0 -1
  152. package/dist/midi/oxygen25Profile.d.ts.map +0 -1
  153. package/dist/midi/useMidiLearn.d.ts.map +0 -1
  154. package/dist/midi/useOxygen25.d.ts.map +0 -1
  155. package/dist/midi/useWebMidi.d.ts.map +0 -1
  156. package/dist/models/editor/audioTypes.d.ts.map +0 -1
  157. package/dist/models/editor/fxTypes.d.ts.map +0 -1
  158. package/dist/models/editor/midiTypes.d.ts.map +0 -1
  159. package/dist/models/editor/timelineTypes.d.ts.map +0 -1
  160. package/dist/models/game/modelsGame.d.ts.map +0 -1
  161. package/dist/models/index.d.ts.map +0 -1
  162. package/dist/models/modelsAiAudio.d.ts.map +0 -1
  163. package/dist/models/modelsAiVideo.d.ts.map +0 -1
  164. package/dist/models/modelsAudio.d.ts.map +0 -1
  165. package/dist/models/modelsDmx.d.ts.map +0 -1
  166. package/dist/models/modelsEditor.d.ts.map +0 -1
  167. package/dist/models/modelsKaraoke.d.ts.map +0 -1
  168. package/dist/models/modelsMusicPlatform.d.ts.map +0 -1
  169. package/dist/models/modelsPlatforms.d.ts.map +0 -1
  170. package/dist/models/modelsPlaylistManager.d.ts.map +0 -1
  171. package/dist/models/modelsPlaylists.d.ts.map +0 -1
  172. package/dist/player/GenericPlayer.d.ts.map +0 -1
  173. package/dist/player/GenericPlayerControls.d.ts.map +0 -1
  174. package/dist/player/GenericPlayerStage.d.ts.map +0 -1
  175. package/dist/player/GenericPlayerStageVisualizer.d.ts.map +0 -1
  176. package/dist/player/GenericPlayerTrackList.d.ts.map +0 -1
  177. package/dist/player/YouTubePlayer.d.ts.map +0 -1
  178. package/dist/player/nowPlayingAdapter.d.ts.map +0 -1
  179. package/dist/player/visualizer/ModeSwitcher.d.ts.map +0 -1
  180. package/dist/player/visualizer/StageVisualizer.d.ts.map +0 -1
  181. package/dist/player/visualizer/VuOverlay.d.ts.map +0 -1
  182. package/dist/player/visualizer/modes/BarsMode.d.ts.map +0 -1
  183. package/dist/player/visualizer/modes/BlobFlowMode.d.ts.map +0 -1
  184. package/dist/player/visualizer/modes/ColorRipplesMode.d.ts.map +0 -1
  185. package/dist/player/visualizer/modes/CoverMode.d.ts.map +0 -1
  186. package/dist/player/visualizer/modes/CozyFireplaceMode.d.ts.map +0 -1
  187. package/dist/player/visualizer/modes/EqualizerCircleMode.d.ts.map +0 -1
  188. package/dist/player/visualizer/modes/GridMode.d.ts.map +0 -1
  189. package/dist/player/visualizer/modes/ImageTornadoMode.d.ts.map +0 -1
  190. package/dist/player/visualizer/modes/LavaLampMode.d.ts.map +0 -1
  191. package/dist/player/visualizer/modes/NeonTrianglesMode.d.ts.map +0 -1
  192. package/dist/player/visualizer/modes/OrbitalsMode.d.ts.map +0 -1
  193. package/dist/player/visualizer/modes/PaletteMode.d.ts.map +0 -1
  194. package/dist/player/visualizer/modes/ParticlesMode.d.ts.map +0 -1
  195. package/dist/player/visualizer/modes/PlasmaBallMode.d.ts.map +0 -1
  196. package/dist/player/visualizer/modes/RadialMode.d.ts.map +0 -1
  197. package/dist/player/visualizer/modes/RaysMode.d.ts.map +0 -1
  198. package/dist/player/visualizer/modes/RiftMode.d.ts.map +0 -1
  199. package/dist/player/visualizer/modes/RingsMode.d.ts.map +0 -1
  200. package/dist/player/visualizer/modes/SpectrumMode.d.ts.map +0 -1
  201. package/dist/player/visualizer/modes/StarfieldMode.d.ts.map +0 -1
  202. package/dist/player/visualizer/modes/WaveformMode.d.ts.map +0 -1
  203. package/dist/player/visualizer/types.d.ts.map +0 -1
  204. package/dist/player/visualizer/useLocalStorageState.d.ts.map +0 -1
  205. package/dist/playlist/DynamicRuleEditor.d.ts.map +0 -1
  206. package/dist/playlist/GenericPlaylist.d.ts.map +0 -1
  207. package/dist/playlist/GenericPlaylistItem.d.ts.map +0 -1
  208. package/dist/playlist/PlaylistBrowser.d.ts.map +0 -1
  209. package/dist/playlist/PlaylistDualPane.d.ts.map +0 -1
  210. package/dist/playlist/PlaylistGridView.d.ts.map +0 -1
  211. package/dist/playlist/PlaylistImportWizard.d.ts.map +0 -1
  212. package/dist/playlist/PlaylistList.d.ts.map +0 -1
  213. package/dist/playlist/PlaylistOverview.d.ts.map +0 -1
  214. package/dist/playlist/PlaylistSearchBar.d.ts.map +0 -1
  215. package/dist/playlist/PlaylistSidebar.d.ts.map +0 -1
  216. package/dist/playlist/PlaylistTagEditor.d.ts.map +0 -1
  217. package/dist/playlist/PlaylistTrackList.d.ts.map +0 -1
  218. package/dist/playlist/useLocalPlaylists.d.ts.map +0 -1
  219. package/dist/radio/NiceRadioPlayer.d.ts.map +0 -1
  220. package/dist/streaming/NiceStreamingVisualizer.d.ts.map +0 -1
  221. package/dist/streaming/NiceVoiceChatOverlay.d.ts.map +0 -1
  222. package/dist/streaming/index.d.ts.map +0 -1
  223. package/dist/streaming/liveStreamManager.d.ts.map +0 -1
  224. package/dist/streaming/useLiveStream.d.ts.map +0 -1
  225. package/dist/streaming/webrtcAudio.d.ts.map +0 -1
  226. package/dist/utils/BaseStreamClient.d.ts.map +0 -1
  227. package/dist/utils/arpeggiator.d.ts.map +0 -1
  228. package/dist/utils/articulationEngine.d.ts.map +0 -1
  229. package/dist/utils/audioDragDrop.d.ts.map +0 -1
  230. package/dist/utils/audioEditorUtils.d.ts.map +0 -1
  231. package/dist/utils/audioFxUtils.d.ts.map +0 -1
  232. package/dist/utils/audioMidiUtils.d.ts.map +0 -1
  233. package/dist/utils/audioPitchAlgorithms.d.ts.map +0 -1
  234. package/dist/utils/audioPitchAnalyzeFile.d.ts.map +0 -1
  235. package/dist/utils/audioTimelineUtils.d.ts.map +0 -1
  236. package/dist/utils/ccAutomation.d.ts.map +0 -1
  237. package/dist/utils/chordScale.d.ts.map +0 -1
  238. package/dist/utils/clipLauncher.d.ts.map +0 -1
  239. package/dist/utils/colorResolver.d.ts.map +0 -1
  240. package/dist/utils/crepeStreaming.d.ts.map +0 -1
  241. package/dist/utils/drawTool.d.ts.map +0 -1
  242. package/dist/utils/envelopeFollower.d.ts.map +0 -1
  243. package/dist/utils/gameAudio.d.ts.map +0 -1
  244. package/dist/utils/grooveTemplates.d.ts.map +0 -1
  245. package/dist/utils/index.d.ts.map +0 -1
  246. package/dist/utils/karaokeHelpers.d.ts.map +0 -1
  247. package/dist/utils/karaokeMetadata.d.ts.map +0 -1
  248. package/dist/utils/karaokeScoring.d.ts.map +0 -1
  249. package/dist/utils/latencyEstimate.d.ts.map +0 -1
  250. package/dist/utils/lfoEngine.d.ts.map +0 -1
  251. package/dist/utils/librosaStreaming.d.ts.map +0 -1
  252. package/dist/utils/logger.d.ts.map +0 -1
  253. package/dist/utils/macroSystem.d.ts.map +0 -1
  254. package/dist/utils/midiCCMapping.d.ts.map +0 -1
  255. package/dist/utils/musicPlayerUtils.d.ts.map +0 -1
  256. package/dist/utils/padKaraokeSession.d.ts.map +0 -1
  257. package/dist/utils/pianoRollUtils.d.ts.map +0 -1
  258. package/dist/utils/sanitize.d.ts.map +0 -1
  259. package/dist/utils/shortcutManager.d.ts.map +0 -1
  260. package/dist/utils/songDataHelpers.d.ts.map +0 -1
  261. package/dist/utils/stepSequencer.d.ts.map +0 -1
  262. package/dist/utils/undoRedoUtils.d.ts.map +0 -1
  263. package/dist/utils/vocalEffectsEngine.d.ts.map +0 -1
  264. package/dist/utils/vocalPerformanceMetrics.d.ts.map +0 -1
  265. package/dist/workers/audioWorkletProcessor.d.ts.map +0 -1
  266. package/dist/workers/pitchWorker.d.ts.map +0 -1
  267. package/dist/workers/scoringWorker.d.ts.map +0 -1
  268. package/dist/workers/useAudioWorklet.d.ts.map +0 -1
  269. package/dist/workers/usePitchWorker.d.ts.map +0 -1
  270. package/dist/workers/useScoringWorker.d.ts.map +0 -1
  271. package/dist/workers/useWorker.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,52 +1,52 @@
1
- "use strict";var Bc=Object.create;var Ss=Object.defineProperty;var Gc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var Vc=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wc(t))!qc.call(e,s)&&s!==n&&Ss(e,s,{get:()=>t[s],enumerable:!(a=Gc(t,s))||a.enumerable});return e};var Vn=(e,t,n)=>(n=e!=null?Bc(Uc(e)):{},Vc(t||!e||!e.__esModule?Ss(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),d=require("react"),we=require("@nice2dev/ui"),se=require("@nice2dev/icons"),rt=require("react-bootstrap"),ra=require("pitchy"),Ma=require("react-youtube"),Ne=require("recharts"),aa=require("@nice2dev/ui-core"),Hc=require("react-window");var xt=typeof document<"u"?document.currentScript:null;const Kc=(e,t)=>t??e,Mi=d.createContext(Kc),Yc=({t:e,children:t})=>r.jsx(Mi.Provider,{value:e,children:t});function Te(){return{t:d.useContext(Mi)}}class Zc extends d.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,n),(i=(s=this.props).onError)==null||i.call(s,t,n)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:r.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:r.jsxs("div",{className:"nice-audio-error-boundary__content",children:[r.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),r.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),r.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}const Ur={},sa={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function Xc(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"?Ur==null?void 0:Ur.VITE_LOG_LEVEL:void 0;return e&&e in sa?e:"WARN"}const Qc=Xc();function Hn(e){return sa[e]>=sa[Qc]}function Kn(e){return`[${e}]`}const it={debug(e,t,...n){Hn("DEBUG")&&console.debug(Kn(e),t,...n)},info(e,t,...n){Hn("INFO")&&console.info(Kn(e),t,...n)},warn(e,t,...n){Hn("WARN")&&console.warn(Kn(e),t,...n)},error(e,t,...n){Hn("ERROR")&&console.error(Kn(e),t,...n)},scoped(e){return{debug:(t,...n)=>it.debug(e,t,...n),info:(t,...n)=>it.info(e,t,...n),warn:(t,...n)=>it.warn(e,t,...n),error:(t,...n)=>it.error(e,t,...n)}}},ks=it.scoped("Waveform"),Jc=["audio/","video/"],Ra=({audioBlob:e,currentTime:t,duration:n,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:u=[],displayMode:h="waveform",multiChannel:p=!1,waveColor:f="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:m="transparent",showRuler:v=!1,showChannelLabels:x=!0,showPeakMeter:g=!1,className:k})=>{const b=d.useRef(null),S=d.useRef(null),M=d.useRef(null),[R,N]=d.useState(0),[C,w]=d.useState(!1),[O,$]=d.useState(null),[E,_]=d.useState(null),[L,U]=d.useState(0),Z=Math.max(a,a*i),A=v?24:0;d.useEffect(()=>{if(!e||e.size===0){M.current=null;return}e.type&&!Jc.some(W=>e.type.startsWith(W))&&ks.warn("Unexpected blob MIME type:",e.type);let D=!1;return(async()=>{let W=null;try{const j=await e.arrayBuffer();if(j.byteLength===0||D)return;W=new AudioContext;const F=await W.decodeAudioData(j);D||(M.current=F)}catch(j){ks.error("Failed to decode audio:",j)}finally{W==null||W.close().catch(()=>{})}})(),()=>{D=!0}},[e]),d.useEffect(()=>{if(i>1&&n>0){const D=t/n*Z;(D<R||D>R+a)&&N(Math.max(0,D-a/2))}},[t,n,i,a,Z,R]),d.useEffect(()=>{const D=b.current,W=M.current;if(!D||!n||n===1/0)return;const j=D.getContext("2d");if(!j)return;const F=Z,I=s;if(D.width=F,D.height=I+A,j.clearRect(0,0,F,I+A),m!=="transparent"&&(j.fillStyle=m,j.fillRect(0,0,F,I+A)),v){j.fillStyle="rgba(128,128,128,0.15)",j.fillRect(0,0,F,A),j.fillStyle="var(--nice-text-secondary, #888)",j.font="10px monospace",j.textAlign="center";const P=Math.max(1,Math.floor(n/(Z/80)));for(let T=0;T<=n;T+=P){const z=T/n*F;j.fillText(rd(T),z,A-4),j.fillStyle="rgba(128,128,128,0.3)",j.fillRect(z,A,1,I),j.fillStyle="var(--nice-text-secondary, #888)"}}for(const P of u){const T=P.start/n*F,z=P.end/n*F;j.fillStyle=P.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))",j.fillRect(T,A,z-T,I),P.label&&(j.fillStyle=P.color??"var(--nice-info, #6366f1)",j.font="10px sans-serif",j.textAlign="left",j.fillText(P.label,T+2,A+12))}if(O!==null&&E!==null){const P=Math.min(O,E),T=Math.max(O,E);j.fillStyle="rgba(255,200,0,0.2)",j.fillRect(P,A,T-P,I)}if(W){const P=p?W.numberOfChannels:1,T=I/P;let z=0;for(let B=0;B<P;B++){const G=W.getChannelData(B),Y=A+B*T;if(h==="waveform"?ed(j,G,F,T,Y,f):h==="bars"?td(j,G,F,T,Y,f):h==="spectrogram"&&nd(j,G,F,T,Y,W.sampleRate),g&&n>0){const X=Math.floor(t/n*G.length),ie=Math.floor(W.sampleRate*.05);let le=0;for(let V=Math.max(0,X-ie);V<Math.min(G.length,X+ie);V++)le+=G[V]*G[V];const te=Math.sqrt(le/(ie*2));z=Math.max(z,te)}p&&x&&P>1&&(j.fillStyle="var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))",j.font="bold 11px sans-serif",j.textAlign="left",j.fillText(B===0?"L":B===1?"R":`Ch${B+1}`,4,Y+14))}U(z)}if(n>0){const P=Math.max(0,Math.min(t/n*F,F));j.beginPath(),j.strokeStyle=y,j.lineWidth=2,j.moveTo(P,A),j.lineTo(P,I+A),j.stroke()}for(const P of c){const T=P.time/n*F;j.beginPath(),j.strokeStyle=P.color??"var(--nice-warning, #f59e0b)",j.lineWidth=2,j.setLineDash([4,4]),j.moveTo(T,A),j.lineTo(T,I+A),j.stroke(),j.setLineDash([]),P.label&&(j.fillStyle=P.color??"var(--nice-warning, #f59e0b)",j.font="bold 10px sans-serif",j.textAlign="center",j.fillText(P.label,T,A+I-4))}},[e,M.current,t,n,Z,s,i,h,p,f,y,m,v,c,u,O,E,g,x,A]);const q=d.useCallback(D=>{var F;if(!n)return;const W=(F=b.current)==null?void 0:F.getBoundingClientRect();if(!W)return;const j=D.clientX-W.left+R;w(!0),$(j),_(j)},[n,R]),H=d.useCallback(D=>{if(!C||!b.current)return;const W=b.current.getBoundingClientRect(),j=D.clientX-W.left+R;_(j)},[C,R]),re=d.useCallback(()=>{if(!C||O===null||E===null||!n){w(!1),$(null),_(null);return}const D=Math.min(O,E),W=Math.max(O,E),j=(W-D)/Z*n;if(w(!1),$(null),_(null),j<.2){const F=D/Z*n;o==null||o(F)}else{const F=D/Z*n,I=W/Z*n;l==null||l({start:F,end:I})}},[C,O,E,n,Z,o,l]);return r.jsxs("div",{ref:S,className:`nice-waveform${k?` ${k}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:D=>N(D.target.scrollLeft),children:[r.jsx("canvas",{ref:b,width:Z,height:s+A,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:q,onMouseMove:H,onMouseUp:re,onMouseLeave:re}),g&&r.jsx("div",{style:{position:"absolute",right:4,top:A+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:r.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,L*300)}%`,background:L>.8?"var(--nice-danger, #ef4444)":L>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function ed(e,t,n,a,s,i){const o=Math.floor(t.length/n),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<n;c++){const u=c*o,h=t.subarray(u,u+o);let p=0,f=0;for(let v=0;v<h.length;v++)h[v]<p&&(p=h[v]),h[v]>f&&(f=h[v]);const y=l-f*(a/2),m=l-p*(a/2);e.moveTo(c,y),e.lineTo(c,m)}e.stroke()}function td(e,t,n,a,s,i){const o=Math.max(2,Math.floor(n/128)),l=Math.floor(n/o),c=Math.floor(t.length/l);for(let u=0;u<l;u++){const h=u*c,p=t.subarray(h,h+c);let f=0;for(let x=0;x<p.length;x++)f+=Math.abs(p[x]);const m=f/p.length*a*.9,v=u*o;e.fillStyle=i,e.fillRect(v+1,s+a-m,o-2,m)}}function nd(e,t,n,a,s,i){const l=Math.min(n,512),c=Math.floor(t.length/l),u=n/l;for(let h=0;h<l;h++){const p=h*c,f=new Float32Array(256/2);for(let m=0;m<256/2;m++){let v=0,x=0;for(let g=0;g<256&&p+g<t.length;g++){const k=2*Math.PI*m*g/256;v+=t[p+g]*Math.cos(k),x-=t[p+g]*Math.sin(k)}f[m]=Math.sqrt(v*v+x*x)/256}const y=a/f.length;for(let m=0;m<f.length;m++){const v=Math.min(1,f[m]*10),x=Math.floor(v*255),g=Math.floor(v*100),k=Math.floor((1-v)*200);e.fillStyle=`rgb(${x},${g},${k})`,e.fillRect(h*u,s+a-(m+1)*y,u+1,y+1)}}}function rd(e){const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const ws=88,Yt=16,Yn=16,ad=320;function sd(e){return e-21}function id(e){return e+21}const Na=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=d.useRef(null),c=ad*o,u=ws*Yt,h=d.useRef(null);d.useEffect(()=>{},[e,o,i]);const p=y=>{const m=l.current;if(!m)return;const v=m.getBoundingClientRect(),x=y.clientX-v.left,g=y.clientY-v.top,k=Math.floor(g/Yt),b=id(k),S=x/c*i;h.current={drawing:!0,startX:x,key:k},t(b,S,i/Yn)},f=(y,m)=>{m.stopPropagation(),s==null||s(y)};return r.jsxs("svg",{ref:l,width:c,height:u,style:{background:"var(--bg-secondary, #f8fafc)",border:"1px solid var(--border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(ws)].map((y,m)=>r.jsx("rect",{x:0,y:m*Yt,width:c,height:Yt,fill:m%2===0?"var(--bg-secondary, #f8fafc)":"var(--bg-tertiary, #f1f5f9)"},m)),[...Array(Yn+1)].map((y,m)=>r.jsx("line",{x1:m*c/Yn,y1:0,x2:m*c/Yn,y2:u,stroke:"var(--border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=sd(y.pitch),v=y.start/i*c,x=y.duration/i*c;return r.jsx("rect",{x:v,y:m*Yt,width:Math.max(6,x),height:Yt-2,fill:y.id===a?"var(--color-primary, #6366f1)":"color-mix(in srgb, var(--color-primary, #6366f1) 55%, var(--bg-primary, #ffffff))",stroke:"var(--color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:g=>f(y.id,g),onDoubleClick:()=>n(y.id),style:{cursor:"pointer"}},y.id)})]})},Ri=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const u=d.useRef(null),{t:h}=Te(),[p,f]=d.useState(null),[y,m]=d.useState(null),[v,x]=d.useState(null),g=[...e].sort((_,L)=>_.time-L.time),k=_=>[_.time/i*o,(127-_.value)/127*l],b=(_,L,U)=>Math.max(L,Math.min(U,_)),S=_=>{var H;if(_.target instanceof SVGCircleElement)return;const L=(H=u.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=_.clientX-L.left,Z=_.clientY-L.top,A=b(U/o*i,0,i),q=b(127-Math.round(Z/l*127),0,127);t(s,q,A)},M=(_,L)=>{var q;L.stopPropagation(),f(_.id),x(_.id);const[U,Z]=k(_),A=(q=u.current)==null?void 0:q.getBoundingClientRect();A&&m({dx:L.clientX-A.left-U,dy:L.clientY-A.top-Z})},R=_=>{var H;if(p==null||!y)return;const L=(H=u.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=b(_.clientX-L.left-y.dx,0,o),Z=b(_.clientY-L.top-y.dy,0,l),A=b(U/o*i,0,i),q=b(127-Math.round(Z/l*127),0,127);n(p,q,A)},N=()=>{f(null),m(null)};d.useEffect(()=>{const _=L=>{(L.key==="Delete"||L.key==="Backspace")&&v!=null&&(a(v),x(null))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[v,a]),d.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",R),window.addEventListener("mouseup",N),()=>{window.removeEventListener("mousemove",R),window.removeEventListener("mouseup",N)}});const[C,w]=d.useState(null),O=(_,L)=>{const[U,Z]=k(_);w({x:U+10,y:Z-10,text:`Val: ${_.value}, Time: ${_.time.toFixed(2)}s`})},$=()=>w(null),E=_=>{var H;const L=(H=u.current)==null?void 0:H.getBoundingClientRect();if(!L)return;const U=_.clientX-L.left,Z=_.clientY-L.top,A=b(U/o*i,0,i),q=b(127-Math.round(Z/l*127),0,127);t(s,q,A)};return r.jsxs("svg",{ref:u,width:o,height:l,style:{background:"var(--surface-muted, #f3f3f3)",border:"1px solid var(--border, #bbb)",cursor:p?"grabbing":"crosshair",display:"block"},onClick:S,onDoubleClick:E,tabIndex:0,children:[[...Array(9)].map((_,L)=>r.jsx("line",{x1:0,y1:L*l/8,x2:o,y2:L*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:L===0||L===8?2:1},L)),g.length>1&&r.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:g.map(_=>k(_).join(",")).join(" ")}),g.map(_=>{const[L,U]=k(_);return r.jsxs("g",{children:[r.jsx("circle",{cx:L,cy:U,r:v===_.id?8:6,fill:v===_.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:v===_.id?3:2,style:{cursor:"pointer"},onMouseDown:Z=>M(_,Z),onContextMenu:Z=>{Z.preventDefault(),a(_.id)},onClick:Z=>{Z.stopPropagation(),x(_.id)},onMouseOver:Z=>O(_),onMouseOut:$}),v===_.id&&r.jsx("foreignObject",{x:L+10,y:U-18,width:90,height:30,style:{pointerEvents:"auto"},children:r.jsxs("div",{style:{fontSize:12,background:"var(--surface-bg, #fff)",border:"1px solid var(--border, #bbb)",borderRadius:4,padding:"2px 6px",display:"inline-block"},children:[r.jsxs("label",{style:{marginRight:4},children:[h("ccLane.curve","Curve"),":"]}),r.jsxs("select",{value:_.handleType||c||"linear",onChange:Z=>{n(_.id,_.value,_.time,Z.target.value)},children:[r.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),r.jsx("option",{value:"step",children:h("ccLane.step","Step")}),r.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},_.id)}),C&&r.jsxs("g",{pointerEvents:"none",children:[r.jsx("rect",{x:C.x,y:C.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),r.jsx("text",{x:C.x+6,y:C.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:C.text})]}),r.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",s]})]})},od=it.scoped("audioContext");let On=null;function mn(){if(!On)try{On=new(window.AudioContext||window.webkitAudioContext)}catch(e){od.error("Error initializing AudioContext:",e)}return On}async function Bt(){const e=mn();e&&e.state==="suspended"&&await e.resume()}function Ni(){return!!On&&On.state==="running"}function Ti(e){const t=e.bpm/60;switch(e.snapMode){case"bar":return 4/t;case"beat":return 1/t;case"sub-beat":return 1/(t*4);case"second":default:return 1}}function ld(e,t){if(!t.snapEnabled)return e;const n=Ti(t);return Math.round(e/n)*n}function cd(e,t=!1){const n=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${n}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${n}:${a.toString().padStart(2,"0")}`}function dd(e,t){const n=t/60,a=e*n,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function $i(e,t,n=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle="var(--surface-bg, #f5f5f5)",a.fillRect(0,0,s,i);const o=s/t.duration;let l=1;o<30?l=5:o<60?l=2:o>150&&(l=.5),a.strokeStyle="var(--border-secondary, #ddd)",a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const u=c/t.duration*s,h=c%1===0;if(a.strokeStyle=h?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(u,0),a.lineTo(u,i),a.stroke(),h&&o>40){a.fillStyle="var(--muted, #666)",a.font="10px monospace",a.textAlign="center";const p=n?dd(c,t.bpm):cd(c);a.fillText(p,u,12)}}if(t.snapEnabled){const c=Ti(t);a.strokeStyle="var(--accent-primary, #ffeb3b)",a.lineWidth=.5;for(let u=0;u<=t.duration;u+=c){const h=u/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function ud(e,t,n,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=n/t.duration*i;$i(e,t),s.strokeStyle=a?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",s.lineWidth=2,s.beginPath(),s.moveTo(l,0),s.lineTo(l,o),s.stroke(),s.fillStyle=a?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function hd(e,t,n,a="var(--success, #4caf50)"){const s=e.getContext("2d");if(!s||!(n!=null&&n.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=a,s.lineWidth=1,s.beginPath(),n.forEach((u,h)=>{const p=h/(n.length-1)*i,f=l-u*c;h===0?s.moveTo(p,f):s.lineTo(p,f)}),s.stroke(),s.restore()}const Ta=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:u,onCurrentTimeChange:h,onZoomChange:p})=>{const f=d.useRef(null),y=d.useRef(null),m=d.useRef(null),[v,x]=d.useState(!1),g={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};d.useEffect(()=>{Bt(),k()},[e,t,s,a,i,o,l,c]),d.useEffect(()=>{n?(m.current=performance.now(),b()):y.current&&cancelAnimationFrame(y.current)},[n]);const k=()=>{f.current&&($i(f.current,g),c!=null&&c.length&&hd(f.current,g,c,u),ud(f.current,g,s,a))},b=()=>{if(!n)return;const w=O=>{if(m.current!==null){const $=(O-m.current)/1e3;m.current=O;const E=Math.min(s+$,t);h(E)}s<t&&(y.current=requestAnimationFrame(w))};y.current=requestAnimationFrame(w)},S=w=>{x(!0),N(w)},M=w=>{v&&N(w)},R=()=>{x(!1)},N=w=>{if(!f.current)return;const O=f.current.getBoundingClientRect();let E=(w.clientX-O.left)/O.width*t;E=ld(E,g),h(Math.min(Math.max(E,0),t))},C=w=>{if(!p)return;w.preventDefault();const O=w.deltaY>0?-.1:.1,$=Math.max(.5,Math.min(5,e+O));p($)};return r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:r.jsx("canvas",{ref:f,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:v?"grabbing":"pointer"},onMouseDown:S,onMouseMove:M,onMouseUp:R,onMouseLeave:R,onWheel:C,role:"img","aria-label":"Audio timeline canvas"})})},Je=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function pd(e){for(const t of Je)if(!e.includes(t))return t;return Je[Math.floor(Math.random()*Je.length)]}const cr=Je.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function fd(e){for(let t=0;t<Je.length;t++){const n=Je[t],a=cr[t];if(!e.includes(n)&&!e.includes(a))return a}return cr[Math.floor(Math.random()*cr.length)]}const md="_panelNarrow_19isp_3",gd="_panelWide_19isp_9",yd="_smallLabel_19isp_19",bd="_noteText_19isp_29",xd="_buttonRow_19isp_41",vd="_noteTextMargin_19isp_49",Sd="_rangeW100_19isp_63",kd="_zoomValue_19isp_69",wd="_selectW100_19isp_77",jd="_inputW70_19isp_83",Cd="_masterVolGroup_19isp_93",Md="_rangeW140_19isp_99",Rd="_volumeValue_19isp_105",Nd="_selectW140_19isp_115",Td="_freqGroup_19isp_121",$d="_freqValue_19isp_127",Pd="_narrowGroup_19isp_137",Ad="_rangeW120_19isp_143",Ed="_smallValue_19isp_149",Id="_presetDivider_19isp_159",Ld="_presetLabel_19isp_165",Dd="_presetBtn_19isp_175",_d="_deletePresetSelect_19isp_183",Fd="_presetNameInput_19isp_191",zd="_savePresetBtn_19isp_199",Od="_countInAlert_19isp_211",Bd="_inputW80_19isp_219",Gd="_levelLabel_19isp_225",Wd="_levelMeter_19isp_233",Ud="_levelBar_19isp_249",ke={panelNarrow:md,panelWide:gd,smallLabel:yd,noteText:bd,buttonRow:xd,noteTextMargin:vd,rangeW100:Sd,zoomValue:kd,selectW100:wd,inputW70:jd,masterVolGroup:Cd,rangeW140:Md,volumeValue:Rd,selectW140:Nd,freqGroup:Td,freqValue:$d,narrowGroup:Pd,rangeW120:Ad,smallValue:Ed,presetDivider:Id,presetLabel:Ld,presetBtn:Dd,deletePresetSelect:_d,presetNameInput:Fd,savePresetBtn:zd,countInAlert:Od,inputW80:Bd,levelLabel:Gd,levelMeter:Wd,levelBar:Ud},Pi=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:a})=>{const{t:s}=Te();return r.jsxs("div",{className:`card p-3 mb-3 ${ke.panelNarrow}`,children:[r.jsx("h6",{className:"mb-2",children:s("editorPanels.autoSaveTitle","Project auto-save")}),r.jsxs("div",{className:"mb-2",children:[r.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveMode","Auto-save mode"),":"]}),r.jsxs("select",{className:"form-select",value:e,onChange:i=>t(i.target.value),children:[r.jsx("option",{value:"off",children:s("editorPanels.off","Off")}),r.jsx("option",{value:"onChange",children:s("editorPanels.onChange","On every change")}),r.jsx("option",{value:"interval",children:s("editorPanels.interval","At set interval")}),r.jsx("option",{value:"both",children:s("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&r.jsxs("div",{className:"mb-2",children:[r.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),r.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:n,onChange:i=>a(Math.max(5,Math.min(600,Number(i.target.value))))})]}),r.jsxs("div",{className:ke.noteText,children:[r.jsxs("b",{children:[s("editorPanels.noteLabel","Note"),":"]})," ",s("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},Ai=({undoCount:e,redoCount:t,onUndo:n,onRedo:a})=>{const{t:s}=Te();return r.jsxs("div",{className:`card p-3 mb-3 ${ke.panelNarrow}`,children:[r.jsx("h6",{className:"mb-2",children:s("editorPanels.changeHistory","Project change history")}),r.jsxs("div",{className:ke.buttonRow,children:[r.jsxs("button",{className:"btn btn-secondary",onClick:n,disabled:e===0,title:s("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:["↩️ ",s("editorPanels.undo","Undo")]}),r.jsxs("button",{className:"btn btn-secondary",onClick:a,disabled:t===0,title:s("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:["↪️ ",s("editorPanels.redo","Redo")]})]}),r.jsx("div",{className:ke.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},$a=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:u})=>{const{t:h}=Te();return r.jsx("div",{className:`card p-2 mb-3 ${ke.panelNarrow}`,children:r.jsxs("div",{className:"d-flex align-items-center gap-3",children:[r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Zoom:"}),r.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:p=>t(Number(p.target.value)),className:ke.rangeW100}),r.jsxs("span",{className:ke.zoomValue,children:[e.toFixed(1),"x"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Zoom UI:"}),r.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:p=>a(Number(p.target.value)),className:ke.rangeW100}),r.jsxs("span",{className:ke.zoomValue,children:[n.toFixed(1),"x"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:s,onChange:i}),r.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${ke.smallLabel}`,children:"Snap"})]}),s&&r.jsxs("select",{className:`form-select form-select-sm ${ke.selectW100}`,value:o,onChange:p=>l(p.target.value),children:[r.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),r.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),r.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),r.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"BPM:"}),r.jsx("input",{type:"number",className:`form-control form-control-sm ${ke.inputW70}`,value:c,onChange:p=>u(Number(p.target.value)),min:"20",max:"300"})]})]})})},Ei=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:u,onSavePreset:h,onDeletePreset:p})=>{const{t:f}=Te();return r.jsxs("div",{className:`card p-2 mb-3 ${ke.panelWide}`,children:[r.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.masterVolGroup}`,children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Master Vol"}),r.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:y=>t(Number(y.target.value)),className:ke.rangeW140}),r.jsxs("span",{className:ke.volumeValue,children:[Math.round(e*100),"%"]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:"Filter"}),r.jsx("select",{className:`form-select form-select-sm ${ke.selectW140}`,value:n,onChange:y=>o({type:y.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(y=>r.jsx("option",{value:y,children:y},y))})]}),r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.freqGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Freq"}),r.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:a,onChange:y=>o({frequency:Number(y.target.value)}),className:ke.rangeW140}),r.jsxs("span",{className:ke.freqValue,children:[Math.round(a)," Hz"]})]}),r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.narrowGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Q"}),r.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:s,onChange:y=>o({q:Number(y.target.value)}),className:ke.rangeW120}),r.jsx("span",{className:ke.smallValue,children:s.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&r.jsxs("div",{className:`d-flex align-items-center gap-2 ${ke.narrowGroup}`,children:[r.jsx("span",{className:ke.smallLabel,children:"Gain"}),r.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:i,onChange:y=>o({gain:Number(y.target.value)}),className:ke.rangeW120}),r.jsxs("span",{className:ke.smallValue,children:[i.toFixed(1)," dB"]})]})]}),r.jsxs("div",{className:`mt-2 pt-2 ${ke.presetDivider}`,children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsxs("span",{className:ke.presetLabel,children:[f("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(y=>r.jsx("button",{className:`btn btn-sm btn-outline-secondary ${ke.presetBtn}`,onClick:()=>u(y),children:y.name},y.name)),c.length>0&&r.jsxs("select",{className:`form-select form-select-sm ${ke.deletePresetSelect}`,onChange:y=>{y.target.value&&(p(y.target.value),y.target.value="")},defaultValue:"",children:[r.jsx("option",{value:"",children:f("editorPanels.deletePreset","Delete preset...")}),c.map(y=>r.jsx("option",{value:y.name,children:y.name},y.name))]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsx("input",{type:"text",className:`form-control form-control-sm ${ke.presetNameInput}`,placeholder:f("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),r.jsx("button",{className:`btn btn-sm btn-success ${ke.savePresetBtn}`,onClick:()=>{const y=document.getElementById("presetNameInput");y!=null&&y.value.trim()&&(h(y.value.trim()),y.value="")},children:f("editorPanels.saveCurrent","Save Current")})]})]})]})},Ii=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:u,monitorLevel:h})=>{const{t:p}=Te();return r.jsx("div",{className:`card p-2 mb-3 ${ke.panelWide}`,children:r.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[r.jsxs("div",{className:"d-flex align-items-center gap-2",children:[r.jsxs("label",{className:`form-label mb-0 ${ke.smallLabel}`,children:[p("editorPanels.countIn","Count-in (bars)"),":"]}),r.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${ke.inputW70}`,value:e,onChange:f=>t(Number(f.target.value))}),n&&r.jsxs("span",{className:ke.countInAlert,children:["Count-in: ",a.toFixed(1),"s"]})]}),r.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[r.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:s,onChange:f=>i(f.target.checked)}),r.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${ke.smallLabel}`,children:p("editorPanels.overdub","Overdub (play background)")})]}),r.jsxs("div",{className:"d-flex align-items-center gap-1",children:[r.jsx("span",{className:ke.smallLabel,children:"Punch In"}),r.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${ke.inputW80}`,value:o??"",onChange:f=>l(f.target.value===""?null:Number(f.target.value))}),r.jsx("span",{className:ke.smallLabel,children:"s"})]}),r.jsxs("div",{className:"d-flex align-items-center gap-1",children:[r.jsx("span",{className:ke.smallLabel,children:"Punch Out"}),r.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${ke.inputW80}`,value:c??"",onChange:f=>u(f.target.value===""?null:Number(f.target.value))}),r.jsx("span",{className:ke.smallLabel,children:"s"})]}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),u(null)},children:p("editorPanels.clearPunch","Clear punch")}),r.jsx("div",{className:ke.levelLabel,children:"Level"}),r.jsx("div",{className:ke.levelMeter,children:r.jsx("div",{className:ke.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},qd=[{id:1,name:"Audio 1",type:"audio",color:Je[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:Je[1],volume:.8,notes:[]}],Vd=({initialTracks:e,tracks:t,onTracksChange:n,initialBpm:a=120,duration:s=30,height:i=480,title:o="Untitled project",displayMode:l="standard",onNew:c,onOpen:u,onSave:h,onExport:p,t:f})=>{var K,oe;const{t:y}=Te(),m=f??y,[v,x]=d.useState(l),g=v==="advanced",k=v!=="basic",[b,S]=d.useState(e??qd),M=t??b,R=d.useCallback(ne=>{t===void 0&&S(ne),n==null||n(ne)},[t,n]),[N,C]=d.useState(!1),[w,O]=d.useState(0),[$,E]=d.useState(1),[_,L]=d.useState(2),[U,Z]=d.useState(!0),[A,q]=d.useState("beat"),[H,re]=d.useState(a),[D,W]=d.useState(80),[j,F]=d.useState(((K=M[0])==null?void 0:K.id)??null),I=d.useRef(0),P=d.useRef(0);d.useEffect(()=>{if(!N)return;P.current=performance.now();const ne=he=>{const J=(he-P.current)/1e3;P.current=he,O(de=>{const me=de+J;return me>=s?(C(!1),s):me}),I.current=requestAnimationFrame(ne)};return I.current=requestAnimationFrame(ne),()=>cancelAnimationFrame(I.current)},[N,s]);const T=d.useCallback((ne,he)=>R(M.map(J=>J.id===ne?{...J,...he}:J)),[M,R]),z=d.useCallback(ne=>{const he=M.reduce((de,me)=>Math.max(de,me.id),0)+1,J=M.filter(de=>de.type===ne).length+1;R([...M,{id:he,name:`${ne==="audio"?"Audio":"MIDI"} ${J}`,type:ne,color:Je[M.length%Je.length],volume:.8,...ne==="audio"?{audioBlob:null}:{notes:[]}}]),F(he)},[M,R]),B=d.useCallback(ne=>R(M.filter(he=>he.id!==ne)),[M,R]),G=d.useCallback(()=>{if(c){c();return}R([]),O(0),C(!1)},[c,R]),Y=d.useCallback((ne,he,J,de)=>{const me=M.find(ye=>ye.id===ne),xe=(me==null?void 0:me.notes)??[],ce=xe.reduce((ye,Se)=>Math.max(ye,Se.id),0)+1;T(ne,{notes:[...xe,{id:ce,pitch:he,start:J,duration:de,velocity:100}]})},[M,T]),X=d.useCallback((ne,he)=>{const J=M.find(de=>de.id===ne);T(ne,{notes:((J==null?void 0:J.notes)??[]).filter(de=>de.id!==he)})},[M,T]),ie=d.useMemo(()=>{const ne=Math.floor(w/60),he=Math.floor(w%60),J=Math.floor(w%1*100);return`${ne}:${he.toString().padStart(2,"0")}.${J.toString().padStart(2,"0")}`},[w]),le=d.useMemo(()=>{const ne=(J,de)=>({id:`mode-${J}`,label:`${v===J?"• ":" "}${de}`,onClick:()=>x(J)}),he=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:G},...u?[{id:"open",label:m("studio.menu.open","Open…"),onClick:u}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(M)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>p==null?void 0:p(M)}]}];return k&&he.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>z("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>z("midi")}]}),he.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},ne("basic",m("studio.mode.basic","Basic")),ne("standard",m("studio.mode.standard","Standard")),ne("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${U?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>Z(J=>!J)}]}),he.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),he},[m,v,k,U,G,u,h,p,M,z]),te=r.jsxs(r.Fragment,{children:[r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>C(ne=>!ne),children:[N?r.jsx(se.NtdPause,{size:14}):r.jsx(se.NtdPlay,{size:14})," ",N?m("studio.pause","Pause"):m("studio.play","Play")]}),r.jsxs(we.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{C(!1),O(0)},children:[r.jsx(se.NtdStop,{size:14})," ",m("studio.stop","Stop")]}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:ie}),r.jsx("span",{style:{flex:1}}),r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>z("audio"),children:[r.jsx(se.NtdPlus,{size:14})," ",m("studio.addAudio","Audio")]}),k&&r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>z("midi"),children:[r.jsx(se.NtdPlus,{size:14})," ",m("studio.addMidi","MIDI")]}),r.jsx("span",{style:{fontSize:12,color:"var(--text-muted, #94a3b8)"},children:m("studio.master","Master")}),r.jsx("div",{style:{width:90},children:r.jsx(we.NiceSlider,{value:D,onChange:W,min:0,max:100})})]}),V=r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[H," BPM"]}),r.jsx("span",{children:"·"}),r.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:ie}),r.jsx("span",{children:"·"}),r.jsxs("span",{children:[M.length," ",m("studio.tracks","tracks")]}),g&&j!=null&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:[m("studio.active","Active"),": ",((oe=M.find(ne=>ne.id===j))==null?void 0:oe.name)??"—"]})]}),r.jsx("span",{style:{flex:1}}),r.jsx("span",{style:{textTransform:"capitalize"},children:v})]});return r.jsxs(we.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[r.jsx(we.NiceMenu,{items:le,orientation:"horizontal"}),r.jsx("span",{style:{color:"var(--text-secondary)",fontSize:13},children:o})]}),toolbar:te,statusBar:V,children:[k&&r.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--border-color)"},children:r.jsx($a,{zoom:$,setZoom:E,uiZoom:_,setUiZoom:L,snapEnabled:U,onToggleSnap:()=>Z(ne=>!ne),snapMode:A,onSnapModeChange:q,bpm:H,setBpm:re})}),r.jsx("div",{style:{padding:8},children:r.jsx(Ta,{zoom:$,duration:s,isPlaying:N,isRecording:!1,currentTime:w,bpm:H,snapEnabled:U,snapMode:A,onCurrentTimeChange:O,onZoomChange:E})}),M.length===0?r.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--text-muted, #94a3b8)"},children:m("studio.empty","No tracks — add an audio or MIDI track to start.")}):M.map(ne=>r.jsxs("div",{style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--border-color)",background:j===ne.id?"color-mix(in srgb, var(--color-primary) 8%, transparent)":"transparent"},onClick:()=>F(ne.id),children:[r.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:ne.color||Je[0],flex:"0 0 auto"}}),r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceTextInput,{value:ne.name,onChange:he=>T(ne.id,{name:he}),size:"sm"})})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[r.jsx(we.NiceButton,{variant:ne.muted?"danger":"ghost",size:"sm",onClick:()=>T(ne.id,{muted:!ne.muted}),children:"M"}),k&&r.jsx(we.NiceButton,{variant:ne.solo?"warning":"ghost",size:"sm",onClick:()=>T(ne.id,{solo:!ne.solo}),children:"S"}),r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceSlider,{value:Math.round((ne.volume??.8)*100),onChange:he=>T(ne.id,{volume:he/100}),min:0,max:100})}),r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>B(ne.id),children:r.jsx(se.NtdClose,{size:14})})]})]}),r.jsx("div",{style:{flex:1,minWidth:0,opacity:ne.muted?.5:1},children:ne.type==="audio"?r.jsx(Ra,{audioBlob:ne.audioBlob??null,currentTime:w,duration:s,zoom:$,height:80,waveColor:ne.color,onSeek:O}):r.jsx(Na,{notes:ne.notes??[],onAddNote:(he,J,de)=>Y(ne.id,he,J,de),onRemoveNote:he=>X(ne.id,he),duration:s,zoom:$})})]},ne.id))]})};let Hd=Date.now();function fn(){return Hd++}function Kd(e,t,n=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=n&&(a.push({id:fn(),cc:t,value:gn(i.value),time:i.time}),s=i.time);return a}function js(e,t,n,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:fn(),cc:n,value:gn(wr(e.value,t.value,o)),time:wr(e.time,t.time,o)})}return s}function Yd(e,t,n,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Cs(e.time,t.time,n.time,l),u=Cs(e.value,t.value,n.value,l);i.push({id:fn(),cc:a,value:gn(u),time:c})}return i}function Zd(e,t,n,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,u=gn(e.value+l*o);s.push({id:fn(),cc:n,value:u,time:c}),s.push({id:fn(),cc:n,value:u,time:c+i-.001})}return s}function Xd(e,t,n,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:fn(),cc:n,value:gn(wr(e.value,t.value,c)),time:wr(e.time,t.time,l)})}return i}function Qd(e,t=3){if(e.length<t)return e;const n=[...e].sort((a,s)=>a.time-s.time);return n.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(n.length,i+t),l=n.slice(i,o),c=l.reduce((u,h)=>u+h.value,0)/l.length;return{...a,value:gn(Math.round(c))}})}function Jd(e,t){let n;switch(e.mode){case"pencil":n=Kd(t,e.cc,e.resolution);break;case"line":n=t.length>=2?js(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=Yd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=js(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Zd(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Xd(t[0],t[t.length-1],e.cc):[];break;default:n=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));n=Qd(n,a)}return n}function gn(e){return Math.max(0,Math.min(127,Math.round(e)))}function wr(e,t,n){return e+(t-e)*n}function Cs(e,t,n,a){const s=1-a;return s*s*e+2*s*a*t+a*a*n}function Er(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const eu={"4/1":.25,"2/1":.5,"1/1":1,"1/2":2,"1/4":4,"1/8":8,"1/16":16,"1/32":32,"1/2t":3,"1/4t":6,"1/8t":12,"1/16t":24};function Li(e,t){return e/60*eu[t]/4}function Di(e,t){const n=(t%1+1)%1;switch(e){case"sine":return Math.sin(n*2*Math.PI);case"triangle":return n<.5?4*n-1:3-4*n;case"sawtooth":return 2*n-1;case"square":return n<.5?1:-1;case"random":return Math.sin(n*127.1)*Math.cos(n*311.7)*2;case"sample-hold":return Math.sin(Math.floor(n*4)*2.399+.5)*2-1;default:return 0}}function Pa(e,t,n){if(!e.enabled)return e.center;const a=e.syncToBpm&&n?Li(n,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=Di(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Aa(e,t,n){return Math.round(Pa(e,t,n)*127)}function _i(e,t,n,a,s=30,i){const o=n-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let u=0;u<=l;u++){const h=t+u/l*o,p=Aa(e,h,i);c.push({time:h,value:p,cc:a})}return c}function Fi(e,t,n,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,u=Pa(e,c,s);o.push({x:l/i*t,y:(1-u)*n})}return o}function tu(e){return JSON.stringify(e,null,2)}function nu(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const qr=140,yn=24,ru=[{cc:1,label:"Mod Wheel"},{cc:7,label:"Volume"},{cc:10,label:"Pan"},{cc:11,label:"Expression"},{cc:64,label:"Sustain"},{cc:74,label:"Brightness"}],zi=({layerId:e=0,ccNumber:t=1,duration:n=8,zoom:a=1,automation:s,onChangeCCNumber:i,points:o,onChange:l})=>{const c=d.useRef({getEvents:()=>[],setEvents:()=>{},addEvent:()=>{},removeEvent:()=>{},updateEvent:()=>{},clearLane:()=>{},exportLane:()=>"",importLane:()=>{},undo:()=>{},redo:()=>{},canUndo:!1,canRedo:!1}).current,u=s??c,{t:h}=Te(),p=d.useRef(null),[f,y]=d.useState("pencil"),[m,v]=d.useState(!1),x=d.useRef([]),[g,k]=d.useState(null),[b,S]=d.useState(!1),[M,R]=d.useState(Er()),N=d.useRef(null),C=u.getEvents(e),w=C.filter(j=>j.cc===t),O=Math.max(400,n*30*a),$=d.useCallback(j=>j/O*n,[O,n]),E=d.useCallback(j=>Math.round(Math.max(0,Math.min(127,127-(j-yn)/qr*127))),[]),_=d.useCallback(j=>j/n*O,[O,n]),L=d.useCallback(j=>yn+(127-j)/127*qr,[]),U=d.useCallback(()=>{const j=p.current;if(!j)return;const F=j.getContext("2d");if(!F)return;const I=j.width,P=j.height;F.clearRect(0,0,I,P),F.fillStyle="var(--nice-bg, #1a1a2e)",F.fillRect(0,0,I,P),F.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",F.lineWidth=1;for(let B=0;B<=127;B+=16){const G=L(B);F.beginPath(),F.moveTo(0,G),F.lineTo(I,G),F.stroke()}F.fillStyle="var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",F.font="10px monospace",F.textBaseline="middle";for(const B of[0,32,64,96,127])F.fillText(String(B),2,L(B));F.strokeStyle="var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))";for(let B=0;B<=n;B++){const G=_(B);F.beginPath(),F.moveTo(G,0),F.lineTo(G,P),F.stroke()}const T=[...w].sort((B,G)=>B.time-G.time);if(T.length>0){F.beginPath(),F.moveTo(_(T[0].time),P-yn);for(const B of T)F.lineTo(_(B.time),L(B.value));F.lineTo(_(T[T.length-1].time),P-yn),F.closePath(),F.fillStyle="var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",F.fill(),F.beginPath(),F.strokeStyle="var(--nice-primary, #3b82f6)",F.lineWidth=2;for(let B=0;B<T.length;B++){const G=_(T[B].time),Y=L(T[B].value);B===0?F.moveTo(G,Y):((T[B].handleType??"linear")==="step"&&F.lineTo(G,L(T[B-1].value)),F.lineTo(G,Y))}F.stroke();for(const B of T){const G=_(B.time),Y=L(B.value),X=g===B.id;F.beginPath(),F.arc(G,Y,X?6:4,0,Math.PI*2),F.fillStyle=X?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",F.fill(),F.strokeStyle="var(--nice-bg, #fff)",F.lineWidth=1.5,F.stroke()}}F.strokeStyle="var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",F.lineWidth=1,F.setLineDash([4,4]);const z=L(0);F.beginPath(),F.moveTo(0,z),F.lineTo(I,z),F.stroke(),F.setLineDash([])},[w,n,O,_,L,g]);d.useEffect(()=>{U()},[U]);const Z=j=>{var T;const F=(T=p.current)==null?void 0:T.getBoundingClientRect();if(!F)return;const I=j.clientX-F.left,P=j.clientY-F.top;f==="pencil"?(v(!0),x.current=[{time:$(I),value:E(P)}]):(v(!0),x.current=[{time:$(I),value:E(P)}])},A=j=>{var B;const F=(B=p.current)==null?void 0:B.getBoundingClientRect();if(!F)return;const I=j.clientX-F.left,P=j.clientY-F.top;m&&x.current.push({time:$(I),value:E(P)});const T=[...w].sort((G,Y)=>G.time-Y.time);let z=null;for(const G of T){const Y=_(G.time),X=L(G.value);if(Math.abs(I-Y)<8&&Math.abs(P-X)<8){z=G.id;break}}k(z)},q=()=>{if(!m)return;v(!1);const j=x.current;if(j.length===0)return;const F=Jd({mode:f,cc:t,resolution:.02,smoothing:f==="pencil"?.3:0},j);F.length>0&&u.setEvents(e,[...C,...F]),x.current=[]},H=j=>{var T;const F=(T=p.current)==null?void 0:T.getBoundingClientRect();if(!F)return;const I=j.clientX-F.left,P=j.clientY-F.top;for(const z of w){const B=_(z.time),G=L(z.value);if(Math.abs(I-B)<8&&Math.abs(P-G)<8){u.removeEvent(e,z.id);return}}u.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:E(P),time:$(I)})},re=()=>{const F=_i(M,0,n,t,Math.ceil(n*20),120).map((I,P)=>({...I,id:Date.now()+P}));u.setEvents(e,[...C,...F]),S(!1)},D=()=>{const j=u.exportLane(e),F=new Blob([j],{type:"application/json"}),I=URL.createObjectURL(F),P=document.createElement("a");P.href=I,P.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(I)},W=j=>{var I;const F=(I=j.target.files)==null?void 0:I[0];F&&(F.text().then(P=>{u.importLane(e,P)}),N.current&&(N.current.value=""))};return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:h("ccLane.title","CC Automation Lane")}),r.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:t,onChange:j=>i(Number(j.target.value)),children:ru.map(j=>r.jsxs("option",{value:j.cc,children:[j.label," (CC",j.cc,")"]},j.cc))}),r.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(j=>r.jsx("button",{className:`btn ${f===j?"btn-primary":"btn-outline-secondary"}`,onClick:()=>y(j),style:{fontSize:11,textTransform:"capitalize"},children:j},j))}),r.jsxs("div",{className:"btn-group btn-group-sm",children:[r.jsx("button",{className:"btn btn-outline-secondary",onClick:u.undo,disabled:!u.canUndo,title:"Undo",children:"↩"}),r.jsx("button",{className:"btn btn-outline-secondary",onClick:u.redo,disabled:!u.canRedo,title:"Redo",children:"↪"})]}),r.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>S(!b),title:"Apply LFO modulation",children:"LFO"}),r.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:D,title:"Export CC lane as JSON",children:"Export"}),r.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var j;return(j=N.current)==null?void 0:j.click()},title:"Import CC lane from JSON",children:"Import"}),r.jsx("input",{ref:N,type:"file",accept:".json",style:{display:"none"},onChange:W}),r.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>u.setEvents(e,C.filter(j=>j.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),r.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginLeft:"auto"},children:[w.length," ",h("ccLane.events","events")]})]}),b&&r.jsx("div",{className:"mb-2 p-2",style:{background:"var(--nice-bg-secondary, #161b22)",borderRadius:6,border:"1px solid var(--nice-border, #30363d)"},children:r.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[r.jsxs("label",{style:{fontSize:12},children:["Wave:",r.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:M.waveform,onChange:j=>R(F=>({...F,waveform:j.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(j=>r.jsx("option",{value:j,children:j},j))})]}),r.jsxs("label",{style:{fontSize:12},children:["Rate:",r.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:.01,max:20,step:.1,value:M.rate,onChange:j=>R(F=>({...F,rate:Number(j.target.value)}))})]}),r.jsxs("label",{style:{fontSize:12},children:["Depth:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.depth,onChange:j=>R(F=>({...F,depth:Number(j.target.value)})),style:{width:80}}),r.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.depth.toFixed(2)})]}),r.jsxs("label",{style:{fontSize:12},children:["Center:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:M.center,onChange:j=>R(F=>({...F,center:Number(j.target.value)})),style:{width:80}}),r.jsx("span",{style:{fontSize:11,marginLeft:4},children:M.center.toFixed(2)})]}),r.jsx("button",{className:"btn btn-sm btn-primary",onClick:re,children:"Apply LFO"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>S(!1),children:"Cancel"})]})}),r.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:r.jsx("canvas",{ref:p,width:O,height:qr+yn*2,style:{cursor:m?"crosshair":g?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:Z,onMouseMove:A,onMouseUp:q,onMouseLeave:()=>{m&&q()},onDoubleClick:H,role:"img","aria-label":"CC automation lane editor canvas"})}),r.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:4},children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Oi={"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":1/1.5,"1/8T":.5/1.5,"1/16T":.25/1.5},ia={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function au(e,t){const n=[];for(let a=0;a<t;a++)for(const s of e)n.push({...s,pitch:s.pitch+a*12});return n}function Bi(e,t){if(e.length===0)return[];const n=au(e,t.octaves),a=[...n].sort((o,l)=>o.pitch-l.pitch),s=[...n].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...n].sort(()=>Math.random()-.5);break;case"as-played":i=[...n].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=n;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function su(e,t,n,a=0,s=1){const i=Bi(e,t);if(i.length===0)return[];const o=60/n,l=Oi[t.rate]*o,c=l*t.gate,u=[],h=t.mode==="chord",p=h?s:i.length*s;for(let f=0;f<p;f++){const y=f%2===1?l*t.swing*.5:0,m=a+f*l+y;if(h)for(const v of i){const x=t.velocityPattern?t.velocityPattern[f%t.velocityPattern.length]:v.velocity;u.push({pitch:v.pitch,velocity:x,startTime:m,duration:c,step:f})}else{const v=f%i.length,x=i[v],g=t.velocityPattern?t.velocityPattern[f%t.velocityPattern.length]:x.velocity;u.push({pitch:x.pitch,velocity:g,startTime:m,duration:c,step:f})}}return u}function Gi(){return[{mode:"up",label:"Up",description:"Notes played low to high"},{mode:"down",label:"Down",description:"Notes played high to low"},{mode:"updown",label:"Up/Down",description:"Alternates up then down"},{mode:"downup",label:"Down/Up",description:"Alternates down then up"},{mode:"random",label:"Random",description:"Random note order"},{mode:"as-played",label:"As Played",description:"Order in which notes were pressed"},{mode:"chord",label:"Chord",description:"All notes played simultaneously"}]}function Wi(){return Object.keys(Oi)}const Ui=({config:e=ia,onChange:t=()=>{},active:n=!1,onToggleActive:a=()=>{}})=>{const{t:s}=Te(),i=Gi(),o=Wi(),l=c=>t({...e,...c});return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:n?1:.6},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:s("arp.title","Arpeggiator")}),r.jsx("button",{className:`btn btn-sm ${n?"btn-success":"btn-outline-secondary"}`,onClick:a,children:n?"ON":"OFF"}),r.jsx("button",{className:`btn btn-sm ${e.latch?"btn-warning":"btn-outline-secondary"}`,onClick:()=>l({latch:!e.latch}),title:"Latch — keep arp running after releasing keys",children:"Latch"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(ia),title:"Reset to defaults",children:"Reset"})]}),r.jsxs("div",{className:"row g-2",children:[r.jsxs("div",{className:"col-12",children:[r.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.mode","Mode")}),r.jsx("div",{className:"btn-group btn-group-sm w-100",children:i.map(c=>r.jsx("button",{className:`btn ${e.mode===c.mode?"btn-primary":"btn-outline-secondary"}`,onClick:()=>l({mode:c.mode}),title:c.description,style:{fontSize:11},children:c.label},c.mode))})]}),r.jsxs("div",{className:"col-6",children:[r.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.rate","Rate")}),r.jsx("select",{className:"form-select form-select-sm",style:{background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:o.map(c=>r.jsx("option",{value:c,children:c},c))})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.octaves","Octaves"),": ",e.octaves]}),r.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.repeats","Repeats"),": ",e.repeats]}),r.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},iu=["sine","triangle","sawtooth","square","random","sample-hold"],ou=["1/1","1/2","1/4","1/8","1/16","1/32"],bn=200,Zt=48,qi=({config:e,onChange:t,index:n,onRemove:a})=>{const{t:s}=Te(),i=d.useRef(null),o=c=>t({...e,...c}),l=d.useCallback(()=>{const c=i.current;if(!c)return;const u=c.getContext("2d");if(!u)return;u.clearRect(0,0,bn,Zt),u.fillStyle="var(--nice-bg-secondary, #161b22)",u.fillRect(0,0,bn,Zt),u.strokeStyle="var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",u.lineWidth=1,u.setLineDash([3,3]),u.beginPath(),u.moveTo(0,Zt/2),u.lineTo(bn,Zt/2),u.stroke(),u.setLineDash([]);const h=Fi(e,bn,Zt);if(h.length>0){u.beginPath(),u.strokeStyle=e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",u.lineWidth=1.5;for(let p=0;p<h.length;p++){const f=h[p].x,y=h[p].y;p===0?u.moveTo(f,y):u.lineTo(f,y)}u.stroke()}},[e]);return d.useEffect(()=>{l()},[l]),r.jsxs("div",{className:"card p-2 mb-2",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:e.enabled?1:.5},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsxs("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)",fontSize:13},children:[s("lfo.title","LFO")," ",n!==void 0?`#${n+1}`:""]}),r.jsx("button",{className:`btn btn-sm ${e.enabled?"btn-success":"btn-outline-secondary"}`,onClick:()=>o({enabled:!e.enabled}),style:{fontSize:11,padding:"1px 8px"},children:e.enabled?"ON":"OFF"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Er()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),a&&r.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:a,style:{fontSize:11,padding:"1px 8px"},"aria-label":s("lfo.remove","Remove LFO"),title:s("lfo.remove","Remove LFO"),children:r.jsx(se.NtdClose,{size:12})})]}),r.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[r.jsx("canvas",{ref:i,width:bn,height:Zt,style:{borderRadius:4,border:"1px solid var(--nice-border, #30363d)",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),r.jsxs("div",{className:"flex-grow-1",children:[r.jsx("div",{className:"mb-1",children:r.jsx("div",{className:"btn-group btn-group-sm w-100",children:iu.map(c=>r.jsx("button",{className:`btn ${e.waveform===c?"btn-primary":"btn-outline-secondary"}`,onClick:()=>o({waveform:c}),style:{fontSize:10,textTransform:"capitalize",padding:"1px 4px"},children:c==="sample-hold"?"S&H":c.slice(0,3)},c))})}),r.jsxs("div",{className:"row g-1",children:[r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),r.jsx("input",{type:"range",className:"form-range",min:.01,max:20,step:.1,value:e.rate,onChange:c=>o({rate:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.depth,onChange:c=>o({depth:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:Number(c.target.value)}),style:{height:16}})]}),r.jsxs("div",{className:"col-6",children:[r.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),r.jsx("input",{type:"range",className:"form-range",min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:Number(c.target.value)}),style:{height:16}})]})]}),r.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[r.jsxs("label",{style:{fontSize:10},children:[r.jsx("input",{type:"checkbox",checked:e.syncToBpm,onChange:c=>o({syncToBpm:c.target.checked}),className:"form-check-input me-1",style:{marginTop:0,width:12,height:12}}),"BPM Sync"]}),e.syncToBpm&&r.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>o({syncDivision:c.target.value}),children:ou.map(c=>r.jsx("option",{value:c,children:c},c))}),r.jsxs("label",{style:{fontSize:10},children:["CC:",r.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:Number(c.target.value)})})]})]})]})]})]})},lu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function cu(e){const t=Math.floor(e/12)-1;return`${lu[e%12]}${t}`}const Vi=({seq:e,steps:t,tracks:n,bpm:a,pattern:s,onChange:i})=>{const{t:o}=Te();if(!e)return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),r.jsx("small",{style:{color:"var(--nice-text-muted, #8b949e)"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:u}=e,h=d.useMemo(()=>l.steps.slice(0,l.length),[l]);return r.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[r.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),r.jsx("button",{className:`btn btn-sm ${u?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60,display:"inline-flex",alignItems:"center",gap:4},children:u?r.jsxs(r.Fragment,{children:[r.jsx(se.NtdStop,{size:12})," Stop"]}):r.jsxs(r.Fragment,{children:[r.jsx(se.NtdPlay,{size:12})," Play"]})}),r.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",r.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:20,max:300,value:l.bpm,onChange:p=>e.setBpm(Number(p.target.value))})]}),r.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",r.jsx("input",{type:"range",min:0,max:1,step:.01,value:l.swing,onChange:p=>e.setSwing(Number(p.target.value)),style:{width:60}}),r.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(l.swing*100),"%"]})]}),r.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(p=>r.jsx("button",{className:`btn ${l.length===p?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(p),style:{fontSize:11},children:p},p))})]}),r.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:"Shift →"}),r.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:"← Shift"}),r.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),r.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),r.jsx("div",{style:{overflowX:"auto"},children:r.jsx("div",{style:{display:"flex",gap:2,minWidth:l.length*36},children:h.map((p,f)=>{const y=p.active,m=c===f,v=f%4===0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[r.jsx("span",{style:{fontSize:9,color:v?"var(--nice-text-muted, #8b949e)":"var(--nice-border, #30363d)"},children:f+1}),r.jsx("button",{onClick:()=>e.toggle(f),style:{width:32,height:32,borderRadius:4,border:m?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:y?`hsl(${210+p.velocity/127*40}, 80%, ${35+p.velocity/127*20}%)`:v?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:y?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:y?cu(p.note):""}),r.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden"},children:r.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${p.velocity/127*100}%`,background:y?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${p.velocity}`,onMouseDown:x=>{x.preventDefault();const g=x.target.parentElement.getBoundingClientRect(),k=S=>{const M=S.clientY-g.top,R=Math.round(Math.max(1,Math.min(127,(1-M/g.height)*127)));e.setVelocity(f,R)},b=()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",k),document.addEventListener("mouseup",b)}})}),y&&p.probability<1&&r.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(p.probability*100),"%"]})]},f)})})}),r.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:o("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})};function du(e,t,n){const[a,s]=d.useState("interval"),[i,o]=d.useState(30),l=d.useRef(null),c=d.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(u){t("Auto-save error: "+u.message),n("error")}},[e,t,n]);return d.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),d.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(a==="interval"||a==="both")&&i>0&&(l.current=window.setInterval(c,i*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:o}}function uu(e,t,n){const a=d.useRef(null),[s,i]=d.useState(!1),[o,l]=d.useState(0),[c,u]=d.useState(10),[h,p]=d.useState(!1),[f,y]=d.useState(120),m=d.useCallback((N,C)=>`L${N}-C${C}`,[]),v=d.useCallback((N,C)=>{if(!a.current||!C.audioBuffer)return;const w=m(N,C.id),O=e[N];a.current.addClip({id:w,buffer:C.audioBuffer,startTime:C.start,offset:0,duration:C.duration,layerId:N,volume:(O==null?void 0:O.volume)??1,pan:(O==null?void 0:O.pan)??0,stretchFactor:C.stretchFactor||1,effectChain:(O==null?void 0:O.effectChain)||[]})},[e,m]),x=d.useCallback((N,C)=>{var w;(w=a.current)==null||w.removeClip(m(N,C))},[m]);d.useEffect(()=>{Object.entries(t).forEach(([N,C])=>{const w=Number(N);C==null||C.forEach(O=>v(w,O))})},[t,e,v]),d.useEffect(()=>{a.current&&Object.entries(n).forEach(([N,C])=>{const w=Number(N);a.current.setMidiCCEvents(w,C)})},[n]);const g=d.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),k=d.useCallback(()=>{var N;(N=a.current)==null||N.stop()},[]),b=d.useCallback(N=>{var C;(C=a.current)==null||C.seek(N)},[]),S=d.useCallback(()=>{if(!a.current)return;const N=!h;p(N),a.current.setLoopRegion(0,c,N)},[h,c]),M=d.useCallback(N=>{var w;const C=Math.max(1,c+N);u(C),(w=a.current)==null||w.setLoopRegion(0,C,h)},[c,h]),R=d.useCallback(async(N,C=1024)=>{const w=await N.arrayBuffer(),O=new(window.AudioContext||window.webkitAudioContext),$=await O.decodeAudioData(w.slice(0)),E=$.getChannelData(0),_=E.length,L=Math.max(1,Math.floor(_/C)),U=[];for(let Z=0;Z<C;Z++){const A=Z*L;if(A>=_)break;U.push(E[A])}return O.close(),{waveform:U.map(Z=>Math.max(-1,Math.min(1,Z))),duration:$.duration,buffer:$}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:u,isLooping:h,setIsLooping:p,bpm:f,setBpm:y,handlePlayPause:g,handleStop:k,handleSeek:b,handleToggleLoop:S,handleAdjustDuration:M,upsertEngineClip:v,removeEngineClip:x,makeEngineClipId:m,blobToWaveform:R}}class Ea{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const n=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:n}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const a=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(a)},n.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function hu(e){const[t,n]=d.useState(!1),[a,s]=d.useState(!1),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(null),p=d.useRef(null),f=d.useRef(null),y=d.useRef(0),m=d.useRef(null),v=d.useRef(null),x=d.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),v.current&&(clearTimeout(v.current),v.current=null)},[]),g=d.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(p.current||(p.current=new Ea),y.current=f.current??e.currentTime,n(!0),o(0),await p.current.startRecording({onLevel:o}))},[e,t]),k=d.useCallback(async()=>{var E;if(x(),s(!1),c(0),f.current=null,!p.current){n(!1),o(0);return}const M=await p.current.stopRecording();if(n(!1),o(0),!M||!e.activeLayer)return;const{waveform:R,duration:N,buffer:C}=await e.blobToWaveform(M),w=e.activeLayer.id;e.setWaveforms(_=>({..._,[w]:R}));const O=Math.max(0,y.current||0),$={id:Date.now(),label:"Recording",start:O,duration:N,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(E=e.layerSettings[w])==null?void 0:E.color,blob:M,blobUrl:URL.createObjectURL(M),audioBuffer:C};e.setLayerClips(_=>({..._,[w]:[..._[w]||[],$]})),e.upsertEngineClip(w,$),e.setSelectedClip({layerId:w,clipId:$.id})},[e,x]),b=d.useCallback(M=>{if(M<=0){g();return}s(!0),c(M);const R=performance.now();m.current=window.setInterval(()=>{const N=(performance.now()-R)/1e3;c(Math.max(0,M-N))},100),v.current=window.setTimeout(()=>{x(),s(!1),c(0),f.current||g()},M*1e3)},[g,x]),S=d.useCallback(async()=>{if(t||a){await k();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const M=Math.max(0,e.countInBars)*4*(60/e.bpm),R=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;R&&(f.current=R),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),R?M>0&&b(M):b(M)},[t,a,e,k,b]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:l,punchOut:u,setPunchOut:h,armedPunchInRef:f,recorderRef:p,clearCountInTimers:x,startRecordingNow:g,stopRecordingFlow:k,handleRecord:S}}var Hi=(e=>(e.Recorder="Recorder",e.AudioClip="Audio Clip",e.SpeechSynth="Speech Synth",e.Stream="Stream",e.KeyboardPad="Keyboard/Pads",e.Keyboard="Keyboard",e.AudioClipCompact="AudioClip",e))(Hi||{});const pu={};class Zn{constructor(t,n,a,s={}){this.type=t,this.name=n,this.component=pu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Zn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Zn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Zn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Zn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function Ki(e,t,n,a,s){n(i=>t?[...i,t]:i),a([]),s(e)}function fu(e,t,n,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return n(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function mu(e,t,n,a){n(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class gu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,n,a,s){this.undoStack.push({label:t,category:n,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var n;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(n=this.onChange)==null||n.call(this,t,"undo"),t.oldState):null}redo(){var n;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(n=this.onChange)==null||n.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const n=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<n;s++)a=this.undo();return a}}const yu=it.scoped("useProjectCRUD");function bu(e){const{project:t,activeSection:n,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c}=e,u=d.useCallback(x=>Ki(x,t,l,c,a),[t,l,c,a]),h=d.useCallback(async()=>{var b;if(!t)return;const x=(((b=t.sections)==null?void 0:b.length)??0)+1,k={id:await e.addSection(t.id,"Section",x),projectId:t.id,name:"Section",orderNumber:x,layers:[]};u({...t,sections:[...t.sections||[],k]}),s(k)},[t,u,s]),p=d.useCallback(async x=>{var b,S,M;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(x);const k=(t.sections??[]).filter(R=>R.id!==x);u({...t,sections:k}),s(k[0]??null),i(((b=k[0])==null?void 0:b.layers)??[]),o(((M=(S=k[0])==null?void 0:S.layers)==null?void 0:M[0])??null)},[t,u,s,i,o,e]),f=d.useCallback(async()=>{var g;if(!n)return;const x={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:Hi.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(k=>[...k,x]),o(x);try{const k=await e.addLayer(n.id,x.name,x.audioSource,x.audioSourceParameters);i(b=>b.map(S=>S.id===x.id?{...x,id:k}:S)),t&&u({...t,sections:((g=t.sections)==null?void 0:g.map(b=>b.id===n.id?{...b,layers:[...(b.layers??[]).filter(S=>S.id!==k),{...x,id:k}]}:b))??[]})}catch(k){i(b=>b.filter(S=>S.id!==x.id)),yu.error("Failed to add layer:",k)}},[n,t,u,i,o]),y=d.useCallback(async x=>{var k,b;if((k=e.layerSettings[x])!=null&&k.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[x]||[]).forEach(S=>e.removeEngineClip(x,S.id)),e.setLayerMidiNotes(S=>{const M={...S};return delete M[x],M}),await e.deleteLayer(x),i(S=>S.filter(M=>M.id!==x)),o(S=>(S==null?void 0:S.id)===x?null:S),t&&u({...t,sections:((b=t.sections)==null?void 0:b.map(S=>S.id===(n==null?void 0:n.id)?{...S,layers:(S.layers??[]).filter(M=>M.id!==x)}:S))??[]}))},[t,n,u,i,o,e]),m=d.useCallback(async()=>{if(!t)return;const x=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(x)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:x}),u({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:x}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,u]),v=d.useCallback(async()=>{var k;if(!n)return;const x=e.sectionName||n.name,g=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!x.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(g)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:x,orderNumber:g}),s({...n,name:x,orderNumber:g}),t&&u({...t,sections:((k=t.sections)==null?void 0:k.map(b=>b.id===n.id?{...b,name:x,orderNumber:g}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,u,s]);return{handleAddSection:h,handleDeleteSection:p,handleAddLayer:f,handleDeleteLayer:y,handleSaveProject:m,handleSaveSection:v}}const Yi=d.createContext(null);function xu(){const e=d.useContext(Yi);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Ia=({value:e,children:t})=>r.jsx(Yi.Provider,{value:e,children:t});Ia.displayName="EditorTrackProvider";const on=(e,t)=>t&&t>0?e*15/t:e/10,La=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},vu=(e,t)=>{const n=t??La(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(u=>{if(!(u.startsWith("#")||u.startsWith("E"))){if(u.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(u.startsWith(":")||u.startsWith("*")){const h=u.indexOf(" "),p=u.indexOf(" ",h+1),f=u.indexOf(" ",p+1),y=u.indexOf(" ",f+1);if(y===-1)return;const m=on(parseFloat(u.substring(h+1,p)),n);s===""&&(i=m);const v=u.substring(y+1);if(v.trim()==="~")return;let x=v;x.startsWith("~")&&(x=x.substring(1)),l?(c(),o=x.trimEnd()):o+=x.trimEnd(),l=v.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},Su=(e,t)=>{const n=t??La(e),a=[];let s=[],i="",o=0,l=!0,c=null,u="";function h(){c&&u.trim()!==""&&(c.text=u.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,u=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const f=p.startsWith("*"),y=p.indexOf(" "),m=p.indexOf(" ",y+1),v=p.indexOf(" ",m+1),x=p.indexOf(" ",v+1);if(x===-1)return;const g=on(parseFloat(p.substring(y+1,m)),n),k=on(parseFloat(p.substring(m+1,v)),n),b=g+k;i===""&&(o=g);const S=p.substring(x+1);if(S.trim()==="~"){c&&(c.endTime=b);return}let M=S;M.startsWith("~")&&(M=M.substring(1)),l?(h(),u=M.trimEnd(),c={text:"",startTime:g,endTime:b,isGolden:f}):c?(u+=M.trimEnd(),c.endTime=b,f&&(c.isGolden=!0)):(u=M.trimEnd(),c={text:"",startTime:g,endTime:b,isGolden:f}),l=S.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},Zi=(e,t)=>{const n=t??La(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const u=parseFloat(c[1]);isFinite(u)&&(i=on(u,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),u=l.indexOf(" "),h=l.indexOf(" ",u+1),p=l.indexOf(" ",h+1),f=l.indexOf(" ",p+1);if(f===-1)return;const y=parseFloat(l.substring(u+1,h)),m=parseFloat(l.substring(h+1,p)),v=on(y,n),x=v+on(m,n);s.length===0&&(i=v);const g=l.substring(f+1);if(g.trim()==="~"){s.length>0&&(s[s.length-1].endTime=x);return}let k=g;k.startsWith("~")&&(k=k.substring(1));const b=g.endsWith(" "),S=b?k.slice(0,-1):k;s.push({text:S,startTime:v,endTime:x,isGolden:c,hasTrailingSpace:b})}}}),o(),a},ku=(e,t,n=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(n-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},wu=(e,t)=>{const n=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&n.push(s);return n},Ms="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Rs="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",ju="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Cu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Mu=({song:e,currentTime:t=0})=>{const n=d.useMemo(()=>!e||!e.notes.length?[]:Zi(e.notes.map(l=>l.noteLine),e.bpm??void 0),[e]),a=t-((e==null?void 0:e.gap)??0)/1e3;let s=-1;for(let l=0;l<n.length;l++){const c=n[l].timestamp,u=l+1<n.length?n[l+1].timestamp:c+30;if(a>=c&&a<u){s=l;break}}const i=s>=0?n[s]:null,o=s>=0&&s+1<n.length?n[s+1]:null;return r.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:i?r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:ju,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children:i.syllables.map((l,c)=>{let u=0;a>=l.endTime?u=1:a>l.startTime&&(u=(a-l.startTime)/(l.endTime-l.startTime));const h=Math.round(u*100),p=l.text+(l.hasTrailingSpace?" ":""),f=u>0&&u<1,y=l.isGolden;return u<=0?r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:p},c):u>=1?r.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ms,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${Rs})`:"none",transition:"filter 0.2s ease"},children:p},c):r.jsxs("span",{style:{position:"relative",display:"inline",filter:f?y?`drop-shadow(${Rs})`:`drop-shadow(${Cu})`:"none",transition:"filter 0.15s ease"},children:[r.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:p}),r.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ms,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:p})]},c)})}),o&&r.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:o.syllables.map((l,c)=>r.jsx("span",{style:{color:l.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:l.text+(l.hasTrailingSpace?" ":"")},c))})]}):n.length>0?r.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:r.jsx(se.NtdMusic,{size:20})}):r.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdMicrophone,{size:18})," Waiting for lyrics..."]})})},Da=d.memo(Mu),Vr={},Ru=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Vr==null?void 0:Vr.VITE_DEBUG_KARAOKE)==="true";function oa(e,t,...n){(Ru||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-accent-dark, #6c3483);color:var(--nice-bg, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-accent-dark, #6c3483);font-weight:bold",...n)}const Xi=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const a=parseFloat(n.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Ns=(e,t)=>t&&t>0?e*15/t:e/10,qn=(e,t)=>{const n=t??Xi(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:Ns(parseFloat(o[1]),n),duration:Ns(parseFloat(o[2]),n),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},Qi=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},Nu=it.scoped("karaokeScoringConfig"),_a={easy:{semitoneTolerance:2,preWindow:.25,postExtra:.3,difficultyMult:.9},normal:{semitoneTolerance:1,preWindow:.15,postExtra:.2,difficultyMult:1},hard:{semitoneTolerance:0,preWindow:.08,postExtra:.12,difficultyMult:1.05}},Tu="karaoke.scoringPresets";function $u(){try{const e=localStorage.getItem(Tu);return e?JSON.parse(e):null}catch(e){return Nu.warn("Failed to parse scoring presets overrides",e),null}}function Ji(e){const t={..._a},n=$u();return n&&Object.keys(n).forEach(a=>{const s=n[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=Ji();const Pu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(console.debug("[karaokeScoringConfig] No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=Ji(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},Ir=(e="normal")=>exports.ScoringPresets[e]||_a.normal;function la(e){if(typeof document>"u")return e;const t=/var\(\s*([^,\s)]+)\s*(?:,\s*([^)]+))?\)/,n=e.match(t);if(n){const a=n[1],s=n[2]?n[2].trim():"",i=getComputedStyle(document.documentElement).getPropertyValue(a).trim();return i||s||e}return e}function Au(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const n=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return n?[+n[1],+n[2],+n[3]]:[128,128,128]}const Eu=3,ee=Eu;function Ut(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${ee}V${e-ee}A${t-ee} ${t-ee} 0 0 1 ${ee} ${t}A${t-ee} ${t-ee} 0 0 1 ${t} ${ee}Z`}}function ln(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M${ee} ${ee}H${ee+1}V${e-ee}H${ee}Z`}}function Fa(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function jr(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e-ee-a}V${ee+a}Z`}}function zt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+a}L${ee} ${e/2}Z`}}function Cr(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M${t} 0H${n}V${e}H${t*.6|0}L0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${ee+a} ${ee}H${n}V${e-ee}H${ee+(a*.6|0)}L${ee} ${e-ee-a}V${ee+a}Q${ee} ${ee} ${ee+a} ${ee}Z`}}function za(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M${t*1.5|0} 0H${n}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${ee+(t*1.2|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.2|0)}C${ee+(t*2.2|0)} ${e*.37|0} ${ee+(t*2.2|0)} ${e*.63|0} ${ee+(t*1.2|0)} ${e-ee}Z`}}function Oa(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+a}Q${ee} ${e-ee} ${ee} ${e-ee-a}Z`}}function Mr(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M${t*2} 0H${n}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${ee+(t*1.8|0)} ${ee}H${n}V${e-ee}H${ee+(t*1.8|0)}C${ee+(t*.4|0)} ${e*.78|0} ${ee+(t*2.8|0)} ${e*.55|0} ${ee+(t*.4|0)} ${e*.37|0}S${ee+(t*.9|0)} ${ee} ${ee+(t*1.8|0)} ${ee}Z`}}function Ba(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M${t*3} 0H${n}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${ee+(t*2.5|0)} ${ee}H${n}V${e-ee}H${ee+(t*2.5|0)}L${ee+(t*.7|0)} ${e-ee-(t*1.6|0)}L${ee+(t*1.7|0)} ${e*.64|0}L${ee} ${e/2|0}L${ee+(t*1.7|0)} ${e*.36|0}L${ee+(t*.7|0)} ${ee+(t*1.6|0)}Z`}}function dr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${ee+t-(ee*1.3|0)} ${ee}H${n}V${e-ee}H${ee+1}Z`}}function ca(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${ee} ${ee}H${n}V${e-ee}H${ee+t-(ee*1.3|0)+1}Z`}}function _t(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${ee}A${t-ee} ${t-ee} 0 0 1 ${t-ee} ${t}A${t-ee} ${t-ee} 0 0 1 0 ${e-ee}Z`}}function cn(e){return{w:ee+1,out:`M0 0H${ee+1}V${e}H0Z`,inn:`M0 ${ee}H1V${e-ee}H0Z`}}function eo(e){const t=Math.min(14,e*.22)|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function dn(e){const t=e*.3|0,n=t+2,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${ee+a}V${e-ee-a}L${n-ee-a} ${e-ee}H0Z`}}function Tt(e){const t=e*.42|0,n=t+2,a=Math.max(t-(ee*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}L${n-ee} ${e/2}L${n-ee-a} ${e-ee}H0Z`}}function to(e){const t=e*.3|0,n=t+4,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n-t}Q${n} 0 ${n} ${t}V${e-t}L${n-(t*.6|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-a}Q${n-ee} ${ee} ${n-ee} ${ee+a}V${e-ee-a}L${n-ee-(a*.6|0)} ${e-ee}H0Z`}}function no(e){const t=e*.16|0,n=t*2+4;return{w:n,out:`M0 0H${n-(t*1.5|0)}C${n-(t*2.5|0)} ${e*.35|0} ${n-(t*2.5|0)} ${e*.65|0} ${n-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.2|0)}C${n-ee-(t*2.2|0)} ${e*.37|0} ${n-ee-(t*2.2|0)} ${e*.63|0} ${n-ee-(t*1.2|0)} ${e-ee}H0Z`}}function ro(e){const t=e*.32|0,n=t+3,a=Math.max(t-ee,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}V${e-ee-a}Q${n-ee} ${e-ee} ${n-ee-a} ${e-ee}H0Z`}}function Ga(e){const t=e*.14|0,n=t*3+2;return{w:n,out:`M0 0H${n-t*2}C${n-t} 0 ${n+(t*.3|0)} ${e*.2|0} ${n-(t*.5|0)} ${e*.35|0}S${n-(t*.5|0)} ${e*.8|0} ${n-t*2} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*1.8|0)}C${n-ee-(t*.9|0)} ${ee} ${n-ee+(t*.1|0)} ${e*.22|0} ${n-ee-(t*.4|0)} ${e*.37|0}S${n-ee-(t*.4|0)} ${e*.78|0} ${n-ee-(t*1.8|0)} ${e-ee}H0Z`}}function Rr(e){const t=e*.09|0,n=e*.35|0;return{w:n,out:`M0 0H${n-t*3}L${n-t} ${t*2}L${n-t*2} ${e*.35|0}L${n} ${e/2|0}L${n-t*2} ${e*.65|0}L${n-t} ${e-t*2}L${n-t*3} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-(t*2.5|0)}L${n-ee-(t*.7|0)} ${ee+(t*1.6|0)}L${n-ee-(t*1.7|0)} ${e*.36|0}L${n-ee} ${e/2|0}L${n-ee-(t*1.7|0)} ${e*.64|0}L${n-ee-(t*.7|0)} ${e-ee-(t*1.6|0)}L${n-ee-(t*2.5|0)} ${e-ee}H0Z`}}function da(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${ee}H${n-ee}L${n-ee-t+(ee*1.3|0)} ${e-ee}H0Z`}}function ur(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${ee}H${n-ee-t+(ee*1.3|0)}L${n-ee} ${e-ee}H0Z`}}const Wa=[{name:"Pill",L:Ut,R:_t},{name:"Sharp",L:ln,R:cn},{name:"Soft",L:Fa,R:eo},{name:"Chamfer",L:jr,R:dn},{name:"Arrow",L:zt,R:Tt},{name:"Shield",L:Cr,R:to},{name:"Bracket",L:za,R:no},{name:"Tab",L:Oa,R:ro},{name:"Wave",L:Mr,R:Ga},{name:"Ornate",L:Ba,R:Rr}],ao=[{name:"Pill→Arrow",L:Ut,R:Tt},{name:"Arrow→Pill",L:zt,R:_t},{name:"Pill→Sharp",L:Ut,R:cn},{name:"Sharp→Pill",L:ln,R:_t},{name:"Pill→Chamfer",L:Ut,R:dn},{name:"Chamfer→Pill",L:jr,R:_t},{name:"Arrow→Sharp",L:zt,R:cn},{name:"Sharp→Arrow",L:ln,R:Tt},{name:"Arrow→Chamfer",L:zt,R:dn},{name:"Chamfer→Arrow",L:jr,R:Tt},{name:"Soft→Arrow",L:Fa,R:Tt},{name:"Shield→Chamfer",L:Cr,R:dn},{name:"Pill→Wave",L:Ut,R:Ga},{name:"Wave→Arrow",L:Mr,R:Tt},{name:"Tab→Pill",L:Oa,R:_t},{name:"Ornate→Sharp",L:Ba,R:cn},{name:"Sharp→Ornate",L:ln,R:Rr},{name:"Bracket→Arrow",L:za,R:Tt},{name:"Shield→Pill",L:Cr,R:_t},{name:"Wave→Ornate",L:Mr,R:Rr}],so=[{name:"Skew ╲",L:dr,R:da},{name:"Skew ╱",L:ca,R:ur},{name:"◇ Romb",L:zt,R:Tt},{name:"╲→Pill",L:dr,R:_t},{name:"Pill→╲",L:Ut,R:da},{name:"╱→Sharp",L:ca,R:cn},{name:"Sharp→╱",L:ln,R:ur},{name:"╲→Arrow",L:dr,R:Tt},{name:"Arrow→╱",L:zt,R:ur},{name:"◇→Chamfer",L:zt,R:dn}],Bn=[...Wa,...ao,...so],io=Wa[0];function Cn(e){return Bn.find(t=>t.name===e)||io}const Nr=[{name:"Flames",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${n||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,n)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${n||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${n||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${n||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,n)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${n||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,n)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${n||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${n||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${n||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${n||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${n||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${n||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,n)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,n)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${n||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,n)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${n||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,n)=>{const a=n||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,n)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${n||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,n)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${n||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Mn(e){return Nr.find(t=>t.name===e)||null}const Vt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Lr={...Vt,glass:85},Dr={...Vt,patternName:"Stars"},_r={...Vt,patternName:"Stars"},Fr={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},oo={filledBar:{...Vt},emptyBar:{...Lr},goldFilledBar:{..._r},goldEmptyBar:{...Dr},font:{...Fr},disableGoldNotes:!1},un={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ts="nice2dev-player-bar-style",$s="nice2dev-player-karaoke-settings";function hn(e){return e!=null?`${$s}-${e}`:$s}function Wn(e){return e!=null?`${Ts}-${e}`:Ts}function Ps(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function As(e){const t=oo,n=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:n(t.filledBar,e.filledBar),emptyBar:n(t.emptyBar,e.emptyBar),goldFilledBar:n(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:n(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Ua(e){try{const t=localStorage.getItem(hn(e));if(t){const a=JSON.parse(t);return As(a)}const n=localStorage.getItem(Wn(e));if(n){const a=JSON.parse(n),s=Ps({...un,...a});return localStorage.setItem(hn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(hn());if(a)return As(JSON.parse(a));const s=localStorage.getItem(Wn());if(s)return Ps({...un,...JSON.parse(s)})}}catch{}return{filledBar:{...Vt},emptyBar:{...Lr},goldFilledBar:{..._r},goldEmptyBar:{...Dr},font:{...Fr}}}function Iu(e,t){const n=JSON.stringify(e);localStorage.setItem(hn(t),n)}let Es=!1;async function Lu(e){if(Es||(Es=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(hn())||localStorage.setItem(hn(),t)}catch{}}function Du(e){const t=new Map;for(const n of e)t.set(n,Ua(n));return t}function lo(e){try{const t=localStorage.getItem(Wn(e));if(t)return{...un,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(Wn());if(n)return{...un,...JSON.parse(n)}}}catch{}return{...un}}function _u(e,t){localStorage.setItem(Wn(t),JSON.stringify(e))}function Fu(e){const t=new Map;for(const n of e)t.set(n,lo(n));return t}const zu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ou=/[&<>"']/g;function Bu(e){return e.replace(Ou,t=>zu[t])}function Gu(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const Wu=3,Xe=Wu;function Tr(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,a),i=Math.min(t,n,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const u=s-i;switch(l=c>.5?u/(2-s-i):u/(s+i),s){case t:o=((n-a)/u+(n<a?6:0))/6;break;case n:o=((a-t)/u+2)/6;break;case a:o=((t-n)/u+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function $r(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function dt(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
1
+ "use strict";var Uc=Object.create;var ws=Object.defineProperty;var qc=Object.getOwnPropertyDescriptor;var Vc=Object.getOwnPropertyNames;var Hc=Object.getPrototypeOf,Kc=Object.prototype.hasOwnProperty;var Yc=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vc(t))!Kc.call(e,s)&&s!==r&&ws(e,s,{get:()=>t[s],enumerable:!(a=qc(t,s))||a.enumerable});return e};var Kn=(e,t,r)=>(r=e!=null?Uc(Hc(e)):{},Yc(t||!e||!e.__esModule?ws(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),Se=require("@nice2dev/ui-core"),Ce=require("@nice2dev/ui"),W=require("@nice2dev/icons"),at=require("react-bootstrap"),ia=require("pitchy"),Na=require("react-youtube"),$e=require("recharts"),Xc=require("react-window");var xt=typeof document<"u"?document.currentScript:null;const Zc=(e,t)=>t??e,Mi=u.createContext(Zc),Qc=({t:e,children:t})=>n.jsx(Mi.Provider,{value:e,children:t});function Te(){return{t:u.useContext(Mi)}}class Jc extends u.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){var s,i;const a=this.props.componentName?`[${this.props.componentName}]`:"[AudioErrorBoundary]";console.error(`${a} Caught error:`,t,r),(i=(s=this.props).onError)==null||i.call(s,t,r)}render(){return this.state.hasError&&this.state.error?typeof this.props.fallback=="function"?this.props.fallback(this.state.error,this.reset):this.props.fallback?this.props.fallback:n.jsx("div",{className:"nice-audio-error-boundary",role:"alert",children:n.jsxs("div",{className:"nice-audio-error-boundary__content",children:[n.jsx("h3",{className:"nice-audio-error-boundary__title",children:this.props.componentName?`${this.props.componentName} encountered an error`:"Something went wrong"}),n.jsx("p",{className:"nice-audio-error-boundary__message",children:this.state.error.message}),n.jsx("button",{className:"nice-audio-error-boundary__retry",onClick:this.reset,children:"Try Again"})]})}):this.props.children}}function ed(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let a=t[1];if(a.length===3&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),a.length>=6)return[parseInt(a.slice(0,2),16),parseInt(a.slice(2,4),16),parseInt(a.slice(4,6),16)]}const r=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);return r?[+r[1],+r[2],+r[3]]:[128,128,128]}const Hr={},oa={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function td(){const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"?Hr==null?void 0:Hr.VITE_LOG_LEVEL:void 0;return e&&e in oa?e:"WARN"}const nd=td();function Yn(e){return oa[e]>=oa[nd]}function Xn(e){return`[${e}]`}const ot={debug(e,t,...r){Yn("DEBUG")&&console.debug(Xn(e),t,...r)},info(e,t,...r){Yn("INFO")&&console.info(Xn(e),t,...r)},warn(e,t,...r){Yn("WARN")&&console.warn(Xn(e),t,...r)},error(e,t,...r){Yn("ERROR")&&console.error(Xn(e),t,...r)},scoped(e){return{debug:(t,...r)=>ot.debug(e,t,...r),info:(t,...r)=>ot.info(e,t,...r),warn:(t,...r)=>ot.warn(e,t,...r),error:(t,...r)=>ot.error(e,t,...r)}}},Cs=ot.scoped("Waveform"),rd=["audio/","video/"],Ta=({audioBlob:e,currentTime:t,duration:r,width:a=600,height:s=200,zoom:i=1,onSeek:o,onRegionSelect:l,markers:c=[],regions:d=[],displayMode:h="waveform",multiChannel:f=!1,waveColor:p="#007bff",progressColor:y="rgba(255,0,0,0.8)",backgroundColor:m="transparent",showRuler:x=!1,showChannelLabels:v=!0,showPeakMeter:g=!1,className:S})=>{const b=u.useRef(null),k=u.useRef(null),[j,N]=u.useState(null),[R,w]=u.useState(0),[M,I]=u.useState(!1),[A,T]=u.useState(null),[O,E]=u.useState(null),[V,ee]=u.useState(0),z=Math.max(a,a*i),q=x?24:0;u.useEffect(()=>{if(!e||e.size===0){N(null);return}e.type&&!rd.some($=>e.type.startsWith($))&&Cs.warn("Unexpected blob MIME type:",e.type);let U=!1;return(async()=>{let $=null;try{const P=await e.arrayBuffer();if(P.byteLength===0||U)return;$=new AudioContext;const F=await $.decodeAudioData(P);U||N(F)}catch(P){Cs.error("Failed to decode audio:",P)}finally{$==null||$.close().catch(()=>{})}})(),()=>{U=!0}},[e]),u.useEffect(()=>{if(i>1&&r>0){const U=t/r*z;(U<R||U>R+a)&&w(Math.max(0,U-a/2))}},[t,r,i,a,z,R]),u.useEffect(()=>{const U=b.current,$=j;if(!U||!r||r===1/0)return;const P=U.getContext("2d");if(!P)return;const F=z,D=s;if(U.width=F,U.height=D+q,P.clearRect(0,0,F,D+q),m!=="transparent"&&(P.fillStyle=Se.resolveCssColor(m),P.fillRect(0,0,F,D+q)),x){const C=Se.resolveCssColor("var(--nice-text-secondary, #888)");P.fillStyle="rgba(128,128,128,0.15)",P.fillRect(0,0,F,q),P.fillStyle=C,P.font="10px monospace",P.textAlign="center";const L=Math.max(1,Math.floor(r/(z/80)));for(let B=0;B<=r;B+=L){const G=B/r*F;P.fillText(od(B),G,q-4),P.fillStyle="rgba(128,128,128,0.3)",P.fillRect(G,q,1,D),P.fillStyle=C}}for(const C of d){const L=C.start/r*F,B=C.end/r*F;P.fillStyle=Se.resolveCssColor(C.color??"var(--nice-accent-tint-15, rgba(99, 102, 241, 0.15))"),P.fillRect(L,q,B-L,D),C.label&&(P.fillStyle=Se.resolveCssColor(C.color??"var(--nice-info, #6366f1)"),P.font="10px sans-serif",P.textAlign="left",P.fillText(C.label,L+2,q+12))}if(A!==null&&O!==null){const C=Math.min(A,O),L=Math.max(A,O);P.fillStyle="rgba(255,200,0,0.2)",P.fillRect(C,q,L-C,D)}if($){const C=f?$.numberOfChannels:1,L=D/C,B=Se.resolveCssColor(p);let G=0;for(let H=0;H<C;H++){const X=$.getChannelData(H),oe=q+H*L;if(h==="waveform"?ad(P,X,F,L,oe,B):h==="bars"?sd(P,X,F,L,oe,B):h==="spectrogram"&&id(P,X,F,L,oe,$.sampleRate),g&&r>0){const le=Math.floor(t/r*X.length),ne=Math.floor($.sampleRate*.05);let Z=0;for(let se=Math.max(0,le-ne);se<Math.min(X.length,le+ne);se++)Z+=X[se]*X[se];const Y=Math.sqrt(Z/(ne*2));G=Math.max(G,Y)}f&&v&&C>1&&(P.fillStyle=Se.resolveCssColor("var(--nice-overlay-light-60, rgba(255, 255, 255, 0.6))"),P.font="bold 11px sans-serif",P.textAlign="left",P.fillText(H===0?"L":H===1?"R":`Ch${H+1}`,4,oe+14))}ee(G)}if(r>0){const C=Math.max(0,Math.min(t/r*F,F));P.beginPath(),P.strokeStyle=Se.resolveCssColor(y),P.lineWidth=2,P.moveTo(C,q),P.lineTo(C,D+q),P.stroke()}for(const C of c){const L=C.time/r*F,B=Se.resolveCssColor(C.color??"var(--nice-warning, #f59e0b)");P.beginPath(),P.strokeStyle=B,P.lineWidth=2,P.setLineDash([4,4]),P.moveTo(L,q),P.lineTo(L,D+q),P.stroke(),P.setLineDash([]),C.label&&(P.fillStyle=B,P.font="bold 10px sans-serif",P.textAlign="center",P.fillText(C.label,L,q+D-4))}},[j,t,r,z,s,i,h,f,p,y,m,x,c,d,A,O,g,v,q]);const K=u.useCallback(U=>{var F;if(!r)return;const $=(F=b.current)==null?void 0:F.getBoundingClientRect();if(!$)return;const P=U.clientX-$.left+R;I(!0),T(P),E(P)},[r,R]),re=u.useCallback(U=>{if(!M||!b.current)return;const $=b.current.getBoundingClientRect(),P=U.clientX-$.left+R;E(P)},[M,R]),_=u.useCallback(()=>{if(!M||A===null||O===null||!r){I(!1),T(null),E(null);return}const U=Math.min(A,O),$=Math.max(A,O),P=($-U)/z*r;if(I(!1),T(null),E(null),P<.2){const F=U/z*r;o==null||o(F)}else{const F=U/z*r,D=$/z*r;l==null||l({start:F,end:D})}},[M,A,O,r,z,o,l]);return n.jsxs("div",{ref:k,className:`nice-waveform${S?` ${S}`:""}`,style:{position:"relative",width:a,overflow:i>1?"auto":"hidden",cursor:o?"crosshair":"default"},onScroll:U=>w(U.target.scrollLeft),children:[n.jsx("canvas",{ref:b,width:z,height:s+q,style:{display:"block"},role:"img","aria-label":"Waveform canvas",onMouseDown:K,onMouseMove:re,onMouseUp:_,onMouseLeave:_}),g&&n.jsx("div",{style:{position:"absolute",right:4,top:q+4,bottom:4,width:12,background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))",borderRadius:4,overflow:"hidden"},children:n.jsx("div",{style:{position:"absolute",bottom:0,width:"100%",height:`${Math.min(100,V*300)}%`,background:V>.8?"var(--nice-danger, #ef4444)":V>.5?"var(--nice-warning, #f59e0b)":"var(--nice-success, #22c55e)",borderRadius:4,transition:"height 50ms"}})})]})};function ad(e,t,r,a,s,i){const o=Math.floor(t.length/r),l=s+a/2;e.beginPath(),e.strokeStyle=i,e.lineWidth=1;for(let c=0;c<r;c++){const d=c*o,h=t.subarray(d,d+o);let f=0,p=0;for(let x=0;x<h.length;x++)h[x]<f&&(f=h[x]),h[x]>p&&(p=h[x]);const y=l-p*(a/2),m=l-f*(a/2);e.moveTo(c,y),e.lineTo(c,m)}e.stroke()}function sd(e,t,r,a,s,i){const o=Math.max(2,Math.floor(r/128)),l=Math.floor(r/o),c=Math.floor(t.length/l);for(let d=0;d<l;d++){const h=d*c,f=t.subarray(h,h+c);let p=0;for(let v=0;v<f.length;v++)p+=Math.abs(f[v]);const m=p/f.length*a*.9,x=d*o;e.fillStyle=i,e.fillRect(x+1,s+a-m,o-2,m)}}function id(e,t,r,a,s,i){const l=Math.min(r,512),c=Math.floor(t.length/l),d=r/l;for(let h=0;h<l;h++){const f=h*c,p=new Float32Array(256/2);for(let m=0;m<256/2;m++){let x=0,v=0;for(let g=0;g<256&&f+g<t.length;g++){const S=2*Math.PI*m*g/256;x+=t[f+g]*Math.cos(S),v-=t[f+g]*Math.sin(S)}p[m]=Math.sqrt(x*x+v*v)/256}const y=a/p.length;for(let m=0;m<p.length;m++){const x=Math.min(1,p[m]*10),v=Math.floor(x*255),g=Math.floor(x*100),S=Math.floor((1-x)*200);e.fillStyle=`rgb(${v},${g},${S})`,e.fillRect(h*d,s+a-(m+1)*y,d+1,y+1)}}}function od(e){const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`}const js=88,Zt=16,Zn=16,ld=320;function cd(e){return e-21}function dd(e){return e+21}const $a=({notes:e,onAddNote:t,onRemoveNote:r,selectedNoteId:a,setSelectedNoteId:s,duration:i=4,zoom:o=1})=>{const l=u.useRef(null),c=ld*o,d=js*Zt,h=u.useRef(null);u.useEffect(()=>{},[e,o,i]);const f=y=>{const m=l.current;if(!m)return;const x=m.getBoundingClientRect(),v=y.clientX-x.left,g=y.clientY-x.top,S=Math.floor(g/Zt),b=dd(S),k=v/c*i;h.current={drawing:!0,startX:v,key:S},t(b,k,i/Zn)},p=(y,m)=>{m.stopPropagation(),s==null||s(y)};return n.jsxs("svg",{ref:l,width:c,height:d,style:{background:"var(--nice-bg-secondary, #f8fafc)",border:"1px solid var(--nice-border-color, #cbd5e1)",userSelect:"none",display:"block"},onMouseDown:f,children:[[...Array(js)].map((y,m)=>n.jsx("rect",{x:0,y:m*Zt,width:c,height:Zt,fill:m%2===0?"var(--nice-bg-secondary, #f8fafc)":"var(--nice-bg-tertiary, #f1f5f9)"},m)),[...Array(Zn+1)].map((y,m)=>n.jsx("line",{x1:m*c/Zn,y1:0,x2:m*c/Zn,y2:d,stroke:"var(--nice-border-muted, #ccc)",strokeWidth:m%4===0?2:1},m)),e.map(y=>{const m=cd(y.pitch),x=y.start/i*c,v=y.duration/i*c;return n.jsx("rect",{x,y:m*Zt,width:Math.max(6,v),height:Zt-2,fill:y.id===a?"var(--nice-color-primary, #6366f1)":"color-mix(in srgb, var(--nice-color-primary, #6366f1) 55%, var(--nice-bg-primary, #ffffff))",stroke:"var(--nice-color-primary, #6366f1)",strokeWidth:y.id===a?2:1,rx:3,onClick:g=>p(y.id,g),onDoubleClick:()=>r(y.id),style:{cursor:"pointer"}},y.id)})]})},Ri=({ccEvents:e,onAddEvent:t,onUpdateEvent:r,onRemoveEvent:a,ccType:s,duration:i,width:o,height:l=60,curveType:c})=>{const d=u.useRef(null),{t:h}=Te(),[f,p]=u.useState(null),[y,m]=u.useState(null),[x,v]=u.useState(null),g=[...e].sort((O,E)=>O.time-E.time),S=O=>[O.time/i*o,(127-O.value)/127*l],b=(O,E,V)=>Math.max(E,Math.min(V,O)),k=O=>{var K;if(O.target instanceof SVGCircleElement)return;const E=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!E)return;const V=O.clientX-E.left,ee=O.clientY-E.top,z=b(V/o*i,0,i),q=b(127-Math.round(ee/l*127),0,127);t(s,q,z)},j=(O,E)=>{var q;E.stopPropagation(),p(O.id),v(O.id);const[V,ee]=S(O),z=(q=d.current)==null?void 0:q.getBoundingClientRect();z&&m({dx:E.clientX-z.left-V,dy:E.clientY-z.top-ee})},N=O=>{var K;if(f==null||!y)return;const E=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!E)return;const V=b(O.clientX-E.left-y.dx,0,o),ee=b(O.clientY-E.top-y.dy,0,l),z=b(V/o*i,0,i),q=b(127-Math.round(ee/l*127),0,127);r(f,q,z)},R=()=>{p(null),m(null)};u.useEffect(()=>{const O=E=>{(E.key==="Delete"||E.key==="Backspace")&&x!=null&&(a(x),v(null))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[x,a]),u.useEffect(()=>{if(f!=null)return window.addEventListener("mousemove",N),window.addEventListener("mouseup",R),()=>{window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",R)}});const[w,M]=u.useState(null),I=(O,E)=>{const[V,ee]=S(O);M({x:V+10,y:ee-10,text:`Val: ${O.value}, Time: ${O.time.toFixed(2)}s`})},A=()=>M(null),T=O=>{var K;const E=(K=d.current)==null?void 0:K.getBoundingClientRect();if(!E)return;const V=O.clientX-E.left,ee=O.clientY-E.top,z=b(V/o*i,0,i),q=b(127-Math.round(ee/l*127),0,127);t(s,q,z)};return n.jsxs("svg",{ref:d,width:o,height:l,style:{background:"var(--nice-bg-tertiary, #f3f3f3)",border:"1px solid var(--nice-border, #bbb)",cursor:f?"grabbing":"crosshair",display:"block"},onClick:k,onDoubleClick:T,tabIndex:0,children:[[...Array(9)].map((O,E)=>n.jsx("line",{x1:0,y1:E*l/8,x2:o,y2:E*l/8,stroke:"var(--nice-border-muted, #ddd)",strokeWidth:E===0||E===8?2:1},E)),g.length>1&&n.jsx("polyline",{fill:"none",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:2,points:g.map(O=>S(O).join(",")).join(" ")}),g.map(O=>{const[E,V]=S(O);return n.jsxs("g",{children:[n.jsx("circle",{cx:E,cy:V,r:x===O.id?8:6,fill:x===O.id?"var(--nice-color-accent, #1976d2)":"var(--nice-color-accent-light, #90caf9)",stroke:"var(--nice-color-accent, #1976d2)",strokeWidth:x===O.id?3:2,style:{cursor:"pointer"},onMouseDown:ee=>j(O,ee),onContextMenu:ee=>{ee.preventDefault(),a(O.id)},onClick:ee=>{ee.stopPropagation(),v(O.id)},onMouseOver:ee=>I(O),onMouseOut:A}),x===O.id&&n.jsx("foreignObject",{x:E+10,y:V-18,width:90,height:30,style:{pointerEvents:"auto"},children:n.jsxs("div",{style:{fontSize:12,background:"var(--nice-color-surface, #fff)",border:"1px solid var(--nice-border, #bbb)",borderRadius:4,padding:"2px 6px",display:"inline-block"},children:[n.jsxs("label",{style:{marginRight:4},children:[h("ccLane.curve","Curve"),":"]}),n.jsxs("select",{value:O.handleType||c||"linear",onChange:ee=>{r(O.id,O.value,O.time,ee.target.value)},children:[n.jsx("option",{value:"linear",children:h("ccLane.linear","Linear")}),n.jsx("option",{value:"step",children:h("ccLane.step","Step")}),n.jsx("option",{value:"exp",children:h("ccLane.exponential","Exponential")})]})]})})]},O.id)}),w&&n.jsxs("g",{pointerEvents:"none",children:[n.jsx("rect",{x:w.x,y:w.y-18,width:90,height:20,fill:"var(--nice-color-surface, #fff)",stroke:"var(--nice-color-accent, #1976d2)",rx:4}),n.jsx("text",{x:w.x+6,y:w.y-4,fontSize:13,fill:"var(--nice-color-accent, #1976d2)",children:w.text})]}),n.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--nice-color-accent, #1976d2)",children:["CC",s]})]})},ud=ot.scoped("audioContext");let Gn=null;function yn(){if(!Gn)try{Gn=new(window.AudioContext||window.webkitAudioContext)}catch(e){ud.error("Error initializing AudioContext:",e)}return Gn}async function Gt(){const e=yn();e&&e.state==="suspended"&&await e.resume()}function Ni(){return!!Gn&&Gn.state==="running"}function Ti(e){const t=e.bpm/60;switch(e.snapMode){case"bar":return 4/t;case"beat":return 1/t;case"sub-beat":return 1/(t*4);case"second":default:return 1}}function hd(e,t){if(!t.snapEnabled)return e;const r=Ti(t);return Math.round(e/r)*r}function pd(e,t=!1){const r=Math.floor(e/60),a=Math.floor(e%60),s=Math.floor(e%1*1e3);return t?`${r}:${a.toString().padStart(2,"0")}.${s.toString().padStart(3,"0")}`:`${r}:${a.toString().padStart(2,"0")}`}function fd(e,t){const r=t/60,a=e*r,s=Math.floor(a/4),i=Math.floor(a%4);return`${s+1}:${i+1}`}function $i(e,t,r=!0){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom);e.width=s,e.height=i,a.clearRect(0,0,s,i),a.fillStyle=Se.resolveCssColor("var(--nice-color-surface, #f5f5f5)",a.canvas),a.fillRect(0,0,s,i);const o=s/t.duration;let l=1;o<30?l=5:o<60?l=2:o>150&&(l=.5),a.strokeStyle=Se.resolveCssColor("var(--nice-border-secondary, #ddd)",a.canvas),a.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const d=c/t.duration*s,h=c%1===0;if(a.strokeStyle=Se.resolveCssColor(h?"var(--nice-border-secondary, #ccc)":"var(--nice-border-muted, #eee)",a.canvas),a.lineWidth=h?1.5:.5,a.beginPath(),a.moveTo(d,0),a.lineTo(d,i),a.stroke(),h&&o>40){a.fillStyle=Se.resolveCssColor("var(--nice-text-muted, #666)",a.canvas),a.font="10px monospace",a.textAlign="center";const f=r?fd(c,t.bpm):pd(c);a.fillText(f,d,12)}}if(t.snapEnabled){const c=Ti(t);a.strokeStyle=Se.resolveCssColor("var(--nice-color-accent, #ffeb3b)",a.canvas),a.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const h=d/t.duration*s;a.beginPath(),a.moveTo(h,i-5),a.lineTo(h,i),a.stroke()}}}function md(e,t,r,a){const s=e.getContext("2d");if(!s)return;const i=30*t.zoom*t.duration,o=Math.max(80,30*t.zoom),l=r/t.duration*i;$i(e,t),s.strokeStyle=Se.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.lineWidth=2,s.beginPath(),s.moveTo(l,0),s.lineTo(l,o),s.stroke(),s.fillStyle=Se.resolveCssColor(a?"var(--nice-color-danger, #f44336)":"var(--nice-color-accent, #2196f3)",s.canvas),s.beginPath(),s.moveTo(l,0),s.lineTo(l-5,-8),s.lineTo(l+5,-8),s.closePath(),s.fill()}function gd(e,t,r,a="var(--nice-color-success, #4caf50)"){const s=e.getContext("2d");if(!s||!(r!=null&&r.length))return;const i=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);s.save(),s.strokeStyle=a,s.lineWidth=1,s.beginPath(),r.forEach((d,h)=>{const f=h/(r.length-1)*i,p=l-d*c;h===0?s.moveTo(f,p):s.lineTo(f,p)}),s.stroke(),s.restore()}const Pa=({zoom:e=1,duration:t=4,isPlaying:r,isRecording:a,currentTime:s,bpm:i=120,snapEnabled:o=!1,snapMode:l="beat",waveform:c,waveformColor:d,onCurrentTimeChange:h,onZoomChange:f})=>{const p=u.useRef(null),[y,m]=u.useState(!1),x=u.useRef(s);x.current=s;const v=u.useRef(t);v.current=t;const g=u.useRef(h);g.current=h;const S={zoom:e,duration:t,bpm:i,snapEnabled:o,snapMode:l};u.useEffect(()=>{Gt(),b()},[e,t,s,a,i,o,l,c]),u.useEffect(()=>{if(!r)return;let M=performance.now(),I=0;const A=T=>{const O=Math.max(0,T-M)/1e3;M=T;const E=Math.min(x.current+O,v.current);x.current=E,g.current(E),E<v.current&&(I=requestAnimationFrame(A))};return I=requestAnimationFrame(A),()=>cancelAnimationFrame(I)},[r]);const b=()=>{p.current&&($i(p.current,S),c!=null&&c.length&&gd(p.current,S,c,d),md(p.current,S,s,a))},k=M=>{m(!0),R(M)},j=M=>{y&&R(M)},N=()=>{m(!1)},R=M=>{if(!p.current)return;const I=p.current.getBoundingClientRect();let T=(M.clientX-I.left)/I.width*t;T=hd(T,S),h(Math.min(Math.max(T,0),t))},w=M=>{if(!f)return;M.preventDefault();const I=M.deltaY>0?-.1:.1,A=Math.max(.5,Math.min(5,e+I));f(A)};return n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:n.jsx("canvas",{ref:p,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:y?"grabbing":"pointer"},onMouseDown:k,onMouseMove:j,onMouseUp:N,onMouseLeave:N,onWheel:w,role:"img","aria-label":"Audio timeline canvas"})})},et=["var(--nice-primary, #2196f3)","var(--nice-danger, #e53935)","var(--nice-warning, #ffeb3b)","var(--nice-success, #43a047)","var(--nice-warning, #ff9800)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-warning, #ffc107)","var(--nice-success, #8bc34a)","var(--nice-danger, #f44336)","var(--nice-accent, #3f51b5)","var(--nice-text-secondary, #607d8b)","var(--nice-warning-dark, #795548)","var(--nice-warning, #cddc39)","var(--nice-accent, #673ab7)","var(--nice-success, #009688)"];function yd(e){for(const t of et)if(!e.includes(t))return t;return et[Math.floor(Math.random()*et.length)]}const ur=et.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function bd(e){for(let t=0;t<et.length;t++){const r=et[t],a=ur[t];if(!e.includes(r)&&!e.includes(a))return a}return ur[Math.floor(Math.random()*ur.length)]}const vd="_panelNarrow_1r7m9_3",xd="_panelWide_1r7m9_9",Sd="_smallLabel_1r7m9_19",kd="_noteText_1r7m9_29",wd="_buttonRow_1r7m9_41",Cd="_noteTextMargin_1r7m9_49",jd="_rangeW100_1r7m9_63",Md="_zoomValue_1r7m9_69",Rd="_selectW100_1r7m9_77",Nd="_inputW70_1r7m9_83",Td="_masterVolGroup_1r7m9_93",$d="_rangeW140_1r7m9_99",Pd="_volumeValue_1r7m9_105",Ad="_selectW140_1r7m9_115",Ed="_freqGroup_1r7m9_121",Id="_freqValue_1r7m9_127",Ld="_narrowGroup_1r7m9_137",Dd="_rangeW120_1r7m9_143",zd="_smallValue_1r7m9_149",_d="_presetDivider_1r7m9_159",Fd="_presetLabel_1r7m9_165",Od="_presetBtn_1r7m9_175",Bd="_deletePresetSelect_1r7m9_183",Gd="_presetNameInput_1r7m9_191",Wd="_savePresetBtn_1r7m9_199",Ud="_countInAlert_1r7m9_211",qd="_inputW80_1r7m9_219",Vd="_levelLabel_1r7m9_225",Hd="_levelMeter_1r7m9_233",Kd="_levelBar_1r7m9_249",we={panelNarrow:vd,panelWide:xd,smallLabel:Sd,noteText:kd,buttonRow:wd,noteTextMargin:Cd,rangeW100:jd,zoomValue:Md,selectW100:Rd,inputW70:Nd,masterVolGroup:Td,rangeW140:$d,volumeValue:Pd,selectW140:Ad,freqGroup:Ed,freqValue:Id,narrowGroup:Ld,rangeW120:Dd,smallValue:zd,presetDivider:_d,presetLabel:Fd,presetBtn:Od,deletePresetSelect:Bd,presetNameInput:Gd,savePresetBtn:Wd,countInAlert:Ud,inputW80:qd,levelLabel:Vd,levelMeter:Hd,levelBar:Kd},Pi=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:r,setAutoSaveInterval:a})=>{const{t:s}=Te();return n.jsxs("div",{className:`card p-3 mb-3 ${we.panelNarrow}`,children:[n.jsx("h6",{className:"mb-2",children:s("editorPanels.autoSaveTitle","Project auto-save")}),n.jsxs("div",{className:"mb-2",children:[n.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveMode","Auto-save mode"),":"]}),n.jsxs("select",{className:"form-select",value:e,onChange:i=>t(i.target.value),children:[n.jsx("option",{value:"off",children:s("editorPanels.off","Off")}),n.jsx("option",{value:"onChange",children:s("editorPanels.onChange","On every change")}),n.jsx("option",{value:"interval",children:s("editorPanels.interval","At set interval")}),n.jsx("option",{value:"both",children:s("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&n.jsxs("div",{className:"mb-2",children:[n.jsxs("label",{className:"form-label",children:[s("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),n.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:r,onChange:i=>a(Math.max(5,Math.min(600,Number(i.target.value))))})]}),n.jsxs("div",{className:we.noteText,children:[n.jsxs("b",{children:[s("editorPanels.noteLabel","Note"),":"]})," ",s("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},Ai=({undoCount:e,redoCount:t,onUndo:r,onRedo:a})=>{const{t:s}=Te();return n.jsxs("div",{className:`card p-3 mb-3 ${we.panelNarrow}`,children:[n.jsx("h6",{className:"mb-2",children:s("editorPanels.changeHistory","Project change history")}),n.jsxs("div",{className:we.buttonRow,children:[n.jsxs("button",{className:"btn btn-secondary",onClick:r,disabled:e===0,title:s("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:[n.jsx(W.NtdUndo,{size:14})," ",s("editorPanels.undo","Undo")]}),n.jsxs("button",{className:"btn btn-secondary",onClick:a,disabled:t===0,title:s("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:[n.jsx(W.NtdRedo,{size:14})," ",s("editorPanels.redo","Redo")]})]}),n.jsx("div",{className:we.noteTextMargin,children:s("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},Aa=({zoom:e,setZoom:t,uiZoom:r,setUiZoom:a,snapEnabled:s,onToggleSnap:i,snapMode:o,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:h}=Te();return n.jsx("div",{className:`card p-2 mb-3 ${we.panelNarrow}`,children:n.jsxs("div",{className:"d-flex align-items-center gap-3",children:[n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${we.smallLabel}`,children:"Zoom:"}),n.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:f=>t(Number(f.target.value)),className:we.rangeW100}),n.jsxs("span",{className:we.zoomValue,children:[e.toFixed(1),"x"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${we.smallLabel}`,children:"Zoom UI:"}),n.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:r,onChange:f=>a(Number(f.target.value)),className:we.rangeW100}),n.jsxs("span",{className:we.zoomValue,children:[r.toFixed(1),"x"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:s,onChange:i}),n.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${we.smallLabel}`,children:"Snap"})]}),s&&n.jsxs("select",{className:`form-select form-select-sm ${we.selectW100}`,value:o,onChange:f=>l(f.target.value),children:[n.jsx("option",{value:"bar",children:h("editorPanels.snapBar","Bar")}),n.jsx("option",{value:"beat",children:h("editorPanels.snapBeat","Beat")}),n.jsx("option",{value:"sub-beat",children:h("editorPanels.snap16","1/16")}),n.jsx("option",{value:"second",children:h("editorPanels.snapSecond","Second")})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${we.smallLabel}`,children:"BPM:"}),n.jsx("input",{type:"number",className:`form-control form-control-sm ${we.inputW70}`,value:c,onChange:f=>d(Number(f.target.value)),min:"20",max:"300"})]})]})})},Ei=({masterVolume:e,onMasterVolumeChange:t,filterType:r,filterFreq:a,filterQ:s,filterGain:i,onFilterChange:o,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:h,onDeletePreset:f})=>{const{t:p}=Te();return n.jsxs("div",{className:`card p-2 mb-3 ${we.panelWide}`,children:[n.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[n.jsxs("div",{className:`d-flex align-items-center gap-2 ${we.masterVolGroup}`,children:[n.jsx("label",{className:`form-label mb-0 ${we.smallLabel}`,children:"Master Vol"}),n.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:y=>t(Number(y.target.value)),className:we.rangeW140}),n.jsxs("span",{className:we.volumeValue,children:[Math.round(e*100),"%"]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("label",{className:`form-label mb-0 ${we.smallLabel}`,children:"Filter"}),n.jsx("select",{className:`form-select form-select-sm ${we.selectW140}`,value:r,onChange:y=>o({type:y.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(y=>n.jsx("option",{value:y,children:y},y))})]}),n.jsxs("div",{className:`d-flex align-items-center gap-2 ${we.freqGroup}`,children:[n.jsx("span",{className:we.smallLabel,children:"Freq"}),n.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:a,onChange:y=>o({frequency:Number(y.target.value)}),className:we.rangeW140}),n.jsxs("span",{className:we.freqValue,children:[Math.round(a)," Hz"]})]}),n.jsxs("div",{className:`d-flex align-items-center gap-2 ${we.narrowGroup}`,children:[n.jsx("span",{className:we.smallLabel,children:"Q"}),n.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:s,onChange:y=>o({q:Number(y.target.value)}),className:we.rangeW120}),n.jsx("span",{className:we.smallValue,children:s.toFixed(1)})]}),(r==="peaking"||r==="lowshelf"||r==="highshelf")&&n.jsxs("div",{className:`d-flex align-items-center gap-2 ${we.narrowGroup}`,children:[n.jsx("span",{className:we.smallLabel,children:"Gain"}),n.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:i,onChange:y=>o({gain:Number(y.target.value)}),className:we.rangeW120}),n.jsxs("span",{className:we.smallValue,children:[i.toFixed(1)," dB"]})]})]}),n.jsxs("div",{className:`mt-2 pt-2 ${we.presetDivider}`,children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsxs("span",{className:we.presetLabel,children:[p("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(y=>n.jsx("button",{className:`btn btn-sm btn-outline-secondary ${we.presetBtn}`,onClick:()=>d(y),children:y.name},y.name)),c.length>0&&n.jsxs("select",{className:`form-select form-select-sm ${we.deletePresetSelect}`,onChange:y=>{y.target.value&&(f(y.target.value),y.target.value="")},defaultValue:"",children:[n.jsx("option",{value:"",children:p("editorPanels.deletePreset","Delete preset...")}),c.map(y=>n.jsx("option",{value:y.name,children:y.name},y.name))]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsx("input",{type:"text",className:`form-control form-control-sm ${we.presetNameInput}`,placeholder:p("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),n.jsx("button",{className:`btn btn-sm btn-success ${we.savePresetBtn}`,onClick:()=>{const y=document.getElementById("presetNameInput");y!=null&&y.value.trim()&&(h(y.value.trim()),y.value="")},children:p("editorPanels.saveCurrent","Save Current")})]})]})]})},Ii=({countInBars:e,setCountInBars:t,isCountIn:r,countInRemaining:a,overdubEnabled:s,setOverdubEnabled:i,punchIn:o,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:h})=>{const{t:f}=Te();return n.jsx("div",{className:`card p-2 mb-3 ${we.panelWide}`,children:n.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[n.jsxs("div",{className:"d-flex align-items-center gap-2",children:[n.jsxs("label",{className:`form-label mb-0 ${we.smallLabel}`,children:[f("editorPanels.countIn","Count-in (bars)"),":"]}),n.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${we.inputW70}`,value:e,onChange:p=>t(Number(p.target.value))}),r&&n.jsxs("span",{className:we.countInAlert,children:["Count-in: ",a.toFixed(1),"s"]})]}),n.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[n.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:s,onChange:p=>i(p.target.checked)}),n.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${we.smallLabel}`,children:f("editorPanels.overdub","Overdub (play background)")})]}),n.jsxs("div",{className:"d-flex align-items-center gap-1",children:[n.jsx("span",{className:we.smallLabel,children:"Punch In"}),n.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${we.inputW80}`,value:o??"",onChange:p=>l(p.target.value===""?null:Number(p.target.value))}),n.jsx("span",{className:we.smallLabel,children:"s"})]}),n.jsxs("div",{className:"d-flex align-items-center gap-1",children:[n.jsx("span",{className:we.smallLabel,children:"Punch Out"}),n.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${we.inputW80}`,value:c??"",onChange:p=>d(p.target.value===""?null:Number(p.target.value))}),n.jsx("span",{className:we.smallLabel,children:"s"})]}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:f("editorPanels.clearPunch","Clear punch")}),n.jsx("div",{className:we.levelLabel,children:"Level"}),n.jsx("div",{className:we.levelMeter,children:n.jsx("div",{className:we.levelBar,style:{width:`${Math.min(1,h*2)*100}%`,background:h>.7?"var(--nice-danger, #f44336)":"var(--nice-success, #4caf50)"}})})]})})},Yd=[{id:1,name:"Audio 1",type:"audio",color:et[0],volume:.8,audioBlob:null},{id:2,name:"MIDI 1",type:"midi",color:et[1],volume:.8,notes:[]}],Xd=({initialTracks:e,tracks:t,onTracksChange:r,initialBpm:a=120,duration:s=30,height:i=480,title:o="Untitled project",displayMode:l="standard",onNew:c,onOpen:d,onSave:h,onExport:f,t:p})=>{var Y,se;const{t:y}=Te(),m=p??y,[x,v]=u.useState(l),g=x==="advanced",S=x!=="basic",[b,k]=u.useState(e??Yd),j=t??b,N=u.useCallback(ae=>{t===void 0&&k(ae),r==null||r(ae)},[t,r]),[R,w]=u.useState(!1),[M,I]=u.useState(0),[A,T]=u.useState(1),[O,E]=u.useState(2),[V,ee]=u.useState(!0),[z,q]=u.useState("beat"),[K,re]=u.useState(a),[_,U]=u.useState(80),[$,P]=u.useState(((Y=j[0])==null?void 0:Y.id)??null),F=u.useRef(0),D=u.useRef(0);u.useEffect(()=>{if(!R)return;D.current=performance.now();const ae=ue=>{const J=(ue-D.current)/1e3;D.current=ue,I(de=>{const me=de+J;return me>=s?(w(!1),s):me}),F.current=requestAnimationFrame(ae)};return F.current=requestAnimationFrame(ae),()=>cancelAnimationFrame(F.current)},[R,s]);const C=u.useCallback((ae,ue)=>N(j.map(J=>J.id===ae?{...J,...ue}:J)),[j,N]),L=u.useCallback(ae=>{const ue=j.reduce((de,me)=>Math.max(de,me.id),0)+1,J=j.filter(de=>de.type===ae).length+1;N([...j,{id:ue,name:`${ae==="audio"?"Audio":"MIDI"} ${J}`,type:ae,color:et[j.length%et.length],volume:.8,...ae==="audio"?{audioBlob:null}:{notes:[]}}]),P(ue)},[j,N]),B=u.useCallback(ae=>N(j.filter(ue=>ue.id!==ae)),[j,N]),G=u.useCallback(()=>{if(c){c();return}N([]),I(0),w(!1)},[c,N]),H=u.useCallback((ae,ue,J,de)=>{const me=j.find(ye=>ye.id===ae),ve=(me==null?void 0:me.notes)??[],ce=ve.reduce((ye,ke)=>Math.max(ye,ke.id),0)+1;C(ae,{notes:[...ve,{id:ce,pitch:ue,start:J,duration:de,velocity:100}]})},[j,C]),X=u.useCallback((ae,ue)=>{const J=j.find(de=>de.id===ae);C(ae,{notes:((J==null?void 0:J.notes)??[]).filter(de=>de.id!==ue)})},[j,C]),oe=u.useMemo(()=>{const ae=Math.floor(M/60),ue=Math.floor(M%60),J=Math.floor(M%1*100);return`${ae}:${ue.toString().padStart(2,"0")}.${J.toString().padStart(2,"0")}`},[M]),le=u.useMemo(()=>{const ae=(J,de)=>({id:`mode-${J}`,label:`${x===J?"• ":" "}${de}`,onClick:()=>v(J)}),ue=[{id:"file",label:m("studio.menu.file","File"),children:[{id:"new",label:m("studio.menu.new","New"),onClick:G},...d?[{id:"open",label:m("studio.menu.open","Open…"),onClick:d}]:[],{id:"save",label:m("studio.menu.save","Save"),onClick:()=>h==null?void 0:h(j)},{id:"export",label:m("studio.menu.export","Export…"),onClick:()=>f==null?void 0:f(j)}]}];return S&&ue.push({id:"edit",label:m("studio.menu.edit","Edit"),children:[{id:"add-audio",label:m("studio.addAudio","Add audio track"),onClick:()=>L("audio")},{id:"add-midi",label:m("studio.addMidi","Add MIDI track"),onClick:()=>L("midi")}]}),ue.push({id:"view",label:m("studio.menu.view","View"),children:[{id:"modes",label:m("studio.menu.modes","Display mode"),divider:!1,disabled:!0},ae("basic",m("studio.mode.basic","Basic")),ae("standard",m("studio.mode.standard","Standard")),ae("advanced",m("studio.mode.advanced","Advanced")),{id:"d1",divider:!0},{id:"snap",label:`${V?"• ":" "}${m("studio.snap","Snap to grid")}`,onClick:()=>ee(J=>!J)}]}),ue.push({id:"help",label:m("studio.menu.help","Help"),children:[{id:"about",label:m("studio.menu.about","About NiceAudioStudio"),disabled:!0}]}),ue},[m,x,S,V,G,d,h,f,j,L]),ne=n.jsxs(n.Fragment,{children:[n.jsxs(Ce.NiceButton,{variant:"primary",size:"sm",onClick:()=>w(ae=>!ae),children:[R?n.jsx(W.NtdPause,{size:14}):n.jsx(W.NtdPlay,{size:14})," ",R?m("studio.pause","Pause"):m("studio.play","Play")]}),n.jsxs(Ce.NiceButton,{variant:"secondary",size:"sm",onClick:()=>{w(!1),I(0)},children:[n.jsx(W.NtdStop,{size:14})," ",m("studio.stop","Stop")]}),n.jsx("span",{style:{fontVariantNumeric:"tabular-nums",fontWeight:700,minWidth:80},children:oe}),n.jsx("span",{style:{flex:1}}),n.jsxs(Ce.NiceButton,{variant:"outline",size:"sm",onClick:()=>L("audio"),children:[n.jsx(W.NtdPlus,{size:14})," ",m("studio.addAudio","Audio")]}),S&&n.jsxs(Ce.NiceButton,{variant:"outline",size:"sm",onClick:()=>L("midi"),children:[n.jsx(W.NtdPlus,{size:14})," ",m("studio.addMidi","MIDI")]}),n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.master","Master")}),n.jsx("div",{style:{width:90},children:n.jsx(Ce.NiceSlider,{value:_,onChange:U,min:0,max:100})})]}),Z=n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[K," BPM"]}),n.jsx("span",{children:"·"}),n.jsx("span",{style:{fontVariantNumeric:"tabular-nums"},children:oe}),n.jsx("span",{children:"·"}),n.jsxs("span",{children:[j.length," ",m("studio.tracks","tracks")]}),g&&$!=null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"·"}),n.jsxs("span",{children:[m("studio.active","Active"),": ",((se=j.find(ae=>ae.id===$))==null?void 0:se.name)??"—"]})]}),n.jsx("span",{style:{flex:1}}),n.jsx("span",{style:{textTransform:"capitalize"},children:x})]});return n.jsxs(Ce.NiceAppShell,{className:"nice-audio-studio",height:i,menubar:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[n.jsx(Ce.NiceMenu,{items:le,orientation:"horizontal"}),n.jsx("span",{style:{color:"var(--nice-text-secondary)",fontSize:13},children:o})]}),toolbar:ne,statusBar:Z,children:[S&&n.jsx("div",{style:{padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color)"},children:n.jsx(Aa,{zoom:A,setZoom:T,uiZoom:O,setUiZoom:E,snapEnabled:V,onToggleSnap:()=>ee(ae=>!ae),snapMode:z,onSnapModeChange:q,bpm:K,setBpm:re})}),n.jsx("div",{style:{padding:8},children:n.jsx(Pa,{zoom:A,duration:s,isPlaying:R,isRecording:!1,currentTime:M,bpm:K,snapEnabled:V,snapMode:z,onCurrentTimeChange:I,onZoomChange:T})}),j.length===0?n.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--nice-text-muted, #94a3b8)"},children:m("studio.empty","No tracks — add an audio or MIDI track to start.")}):j.map(ae=>n.jsxs("div",{style:{display:"flex",gap:8,padding:8,borderTop:"1px solid var(--nice-border-color)",background:$===ae.id?"color-mix(in srgb, var(--nice-color-primary) 8%, transparent)":"transparent"},onClick:()=>P(ae.id),children:[n.jsxs("div",{style:{flex:"0 0 180px",display:"flex",flexDirection:"column",gap:6},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:ae.color||et[0],flex:"0 0 auto"}}),n.jsx("div",{style:{flex:1},children:n.jsx(Ce.NiceTextInput,{value:ae.name,onChange:ue=>C(ae.id,{name:ue}),size:"sm"})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[n.jsx(Ce.NiceButton,{variant:ae.muted?"danger":"ghost",size:"sm",onClick:()=>C(ae.id,{muted:!ae.muted}),children:"M"}),S&&n.jsx(Ce.NiceButton,{variant:ae.solo?"warning":"ghost",size:"sm",onClick:()=>C(ae.id,{solo:!ae.solo}),children:"S"}),n.jsx("div",{style:{flex:1},children:n.jsx(Ce.NiceSlider,{value:Math.round((ae.volume??.8)*100),onChange:ue=>C(ae.id,{volume:ue/100}),min:0,max:100})}),n.jsx(Ce.NiceButton,{variant:"ghost",size:"sm",onClick:()=>B(ae.id),children:n.jsx(W.NtdClose,{size:14})})]})]}),n.jsx("div",{style:{flex:1,minWidth:0,opacity:ae.muted?.5:1},children:ae.type==="audio"?n.jsx(Ta,{audioBlob:ae.audioBlob??null,currentTime:M,duration:s,zoom:A,height:80,waveColor:ae.color,onSeek:I}):n.jsx($a,{notes:ae.notes??[],onAddNote:(ue,J,de)=>H(ae.id,ue,J,de),onRemoveNote:ue=>X(ae.id,ue),duration:s,zoom:A})})]},ae.id))]})};let Zd=Date.now();function gn(){return Zd++}function Qd(e,t,r=.01){if(e.length===0)return[];const a=[];let s=-1/0;for(const i of e)i.time-s>=r&&(a.push({id:gn(),cc:t,value:bn(i.value),time:i.time}),s=i.time);return a}function Ms(e,t,r,a=32){const s=[];for(let i=0;i<=a;i++){const o=i/a;s.push({id:gn(),cc:r,value:bn(jr(e.value,t.value,o)),time:jr(e.time,t.time,o)})}return s}function Jd(e,t,r,a,s=48){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Rs(e.time,t.time,r.time,l),d=Rs(e.value,t.value,r.value,l);i.push({id:gn(),cc:a,value:bn(d),time:c})}return i}function eu(e,t,r,a=8){const s=[],i=(t.time-e.time)/a,o=(t.value-e.value)/a;for(let l=0;l<a;l++){const c=e.time+l*i,d=bn(e.value+l*o);s.push({id:gn(),cc:r,value:d,time:c}),s.push({id:gn(),cc:r,value:d,time:c+i-.001})}return s}function tu(e,t,r,a=2,s=32){const i=[];for(let o=0;o<=s;o++){const l=o/s,c=Math.pow(l,a);i.push({id:gn(),cc:r,value:bn(jr(e.value,t.value,c)),time:jr(e.time,t.time,l)})}return i}function nu(e,t=3){if(e.length<t)return e;const r=[...e].sort((a,s)=>a.time-s.time);return r.map((a,s)=>{const i=Math.max(0,s-Math.floor(t/2)),o=Math.min(r.length,i+t),l=r.slice(i,o),c=l.reduce((d,h)=>d+h.value,0)/l.length;return{...a,value:bn(Math.round(c))}})}function ru(e,t){let r;switch(e.mode){case"pencil":r=Qd(t,e.cc,e.resolution);break;case"line":r=t.length>=2?Ms(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?r=Jd(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?r=Ms(t[0],t[t.length-1],e.cc):r=[];break;case"step":r=t.length>=2?eu(t[0],t[t.length-1],e.cc):[];break;case"ramp":r=t.length>=2?tu(t[0],t[t.length-1],e.cc):[];break;default:r=[]}if(e.smoothing>0){const a=Math.max(2,Math.round(e.smoothing*8));r=nu(r,a)}return r}function bn(e){return Math.max(0,Math.min(127,Math.round(e)))}function jr(e,t,r){return e+(t-e)*r}function Rs(e,t,r,a){const s=1-a;return s*s*e+2*s*a*t+a*a*r}function Dr(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const au={"4/1":.25,"2/1":.5,"1/1":1,"1/2":2,"1/4":4,"1/8":8,"1/16":16,"1/32":32,"1/2t":3,"1/4t":6,"1/8t":12,"1/16t":24};function Li(e,t){return e/60*au[t]/4}function Di(e,t){const r=(t%1+1)%1;switch(e){case"sine":return Math.sin(r*2*Math.PI);case"triangle":return r<.5?4*r-1:3-4*r;case"sawtooth":return 2*r-1;case"square":return r<.5?1:-1;case"random":return Math.sin(r*127.1)*Math.cos(r*311.7)*2;case"sample-hold":return Math.sin(Math.floor(r*4)*2.399+.5)*2-1;default:return 0}}function Ea(e,t,r){if(!e.enabled)return e.center;const a=e.syncToBpm&&r?Li(r,e.syncDivision):e.rate,s=t*a+e.phase/(2*Math.PI),i=Di(e.waveform,s),o=e.center+i*e.depth*.5;return Math.max(0,Math.min(1,o))}function Ia(e,t,r){return Math.round(Ea(e,t,r)*127)}function zi(e,t,r,a,s=30,i){const o=r-t,l=Math.max(2,Math.ceil(o*s)),c=[];for(let d=0;d<=l;d++){const h=t+d/l*o,f=Ia(e,h,i);c.push({time:h,value:f,cc:a})}return c}function _i(e,t,r,a=2,s,i=200){const o=[];for(let l=0;l<=i;l++){const c=l/i*a,d=Ea(e,c,s);o.push({x:l/i*t,y:(1-d)*r})}return o}function su(e){return JSON.stringify(e,null,2)}function iu(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const Kr=140,vn=24,ou=[{cc:1,label:"Mod Wheel"},{cc:7,label:"Volume"},{cc:10,label:"Pan"},{cc:11,label:"Expression"},{cc:64,label:"Sustain"},{cc:74,label:"Brightness"}],Fi=({layerId:e=0,ccNumber:t=1,duration:r=8,zoom:a=1,automation:s,onChangeCCNumber:i,points:o,onChange:l})=>{const c=u.useRef({getEvents:()=>[],setEvents:()=>{},addEvent:()=>{},removeEvent:()=>{},updateEvent:()=>{},clearLane:()=>{},exportLane:()=>"",importLane:()=>{},undo:()=>{},redo:()=>{},canUndo:!1,canRedo:!1}).current,d=s??c,{t:h}=Te(),f=u.useRef(null),[p,y]=u.useState("pencil"),[m,x]=u.useState(!1),v=u.useRef([]),[g,S]=u.useState(null),[b,k]=u.useState(!1),[j,N]=u.useState(Dr()),R=u.useRef(null),w=d.getEvents(e),M=w.filter($=>$.cc===t),I=Math.max(400,r*30*a),A=u.useCallback($=>$/I*r,[I,r]),T=u.useCallback($=>Math.round(Math.max(0,Math.min(127,127-($-vn)/Kr*127))),[]),O=u.useCallback($=>$/r*I,[I,r]),E=u.useCallback($=>vn+(127-$)/127*Kr,[]),V=u.useCallback(()=>{const $=f.current;if(!$)return;const P=$.getContext("2d");if(!P)return;const F=$.width,D=$.height;P.clearRect(0,0,F,D),P.fillStyle=Se.resolveCssColor("var(--nice-bg, #1a1a2e)",P.canvas),P.fillRect(0,0,F,D),P.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",P.canvas),P.lineWidth=1;for(let B=0;B<=127;B+=16){const G=E(B);P.beginPath(),P.moveTo(0,G),P.lineTo(F,G),P.stroke()}P.fillStyle=Se.resolveCssColor("var(--nice-overlay-light-30, rgba(255, 255, 255, 0.3))",P.canvas),P.font="10px monospace",P.textBaseline="middle";for(const B of[0,32,64,96,127])P.fillText(String(B),2,E(B));P.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-4, rgba(255, 255, 255, 0.04))",P.canvas);for(let B=0;B<=r;B++){const G=O(B);P.beginPath(),P.moveTo(G,0),P.lineTo(G,D),P.stroke()}const C=[...M].sort((B,G)=>B.time-G.time);if(C.length>0){P.beginPath(),P.moveTo(O(C[0].time),D-vn);for(const B of C)P.lineTo(O(B.time),E(B.value));P.lineTo(O(C[C.length-1].time),D-vn),P.closePath(),P.fillStyle=Se.resolveCssColor("var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",P.canvas),P.fill(),P.beginPath(),P.strokeStyle=Se.resolveCssColor("var(--nice-primary, #3b82f6)",P.canvas),P.lineWidth=2;for(let B=0;B<C.length;B++){const G=O(C[B].time),H=E(C[B].value);B===0?P.moveTo(G,H):((C[B].handleType??"linear")==="step"&&P.lineTo(G,E(C[B-1].value)),P.lineTo(G,H))}P.stroke();for(const B of C){const G=O(B.time),H=E(B.value),X=g===B.id;P.beginPath(),P.arc(G,H,X?6:4,0,Math.PI*2),P.fillStyle=Se.resolveCssColor(X?"var(--nice-primary-light, #60a5fa)":"var(--nice-primary, #3b82f6)",P.canvas),P.fill(),P.strokeStyle=Se.resolveCssColor("var(--nice-bg, #fff)",P.canvas),P.lineWidth=1.5,P.stroke()}}P.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-15, rgba(255, 255, 255, 0.15))",P.canvas),P.lineWidth=1,P.setLineDash([4,4]);const L=E(0);P.beginPath(),P.moveTo(0,L),P.lineTo(F,L),P.stroke(),P.setLineDash([])},[M,r,I,O,E,g]);u.useEffect(()=>{V()},[V]);const ee=$=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const F=$.clientX-P.left,D=$.clientY-P.top;p==="pencil"?(x(!0),v.current=[{time:A(F),value:T(D)}]):(x(!0),v.current=[{time:A(F),value:T(D)}])},z=$=>{var B;const P=(B=f.current)==null?void 0:B.getBoundingClientRect();if(!P)return;const F=$.clientX-P.left,D=$.clientY-P.top;m&&v.current.push({time:A(F),value:T(D)});const C=[...M].sort((G,H)=>G.time-H.time);let L=null;for(const G of C){const H=O(G.time),X=E(G.value);if(Math.abs(F-H)<8&&Math.abs(D-X)<8){L=G.id;break}}S(L)},q=()=>{if(!m)return;x(!1);const $=v.current;if($.length===0)return;const P=ru({mode:p,cc:t,resolution:.02,smoothing:p==="pencil"?.3:0},$);P.length>0&&d.setEvents(e,[...w,...P]),v.current=[]},K=$=>{var C;const P=(C=f.current)==null?void 0:C.getBoundingClientRect();if(!P)return;const F=$.clientX-P.left,D=$.clientY-P.top;for(const L of M){const B=O(L.time),G=E(L.value);if(Math.abs(F-B)<8&&Math.abs(D-G)<8){d.removeEvent(e,L.id);return}}d.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:T(D),time:A(F)})},re=()=>{const P=zi(j,0,r,t,Math.ceil(r*20),120).map((F,D)=>({...F,id:Date.now()+D}));d.setEvents(e,[...w,...P]),k(!1)},_=()=>{const $=d.exportLane(e),P=new Blob([$],{type:"application/json"}),F=URL.createObjectURL(P),D=document.createElement("a");D.href=F,D.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(F)},U=$=>{var F;const P=(F=$.target.files)==null?void 0:F[0];P&&(P.text().then(D=>{d.importLane(e,D)}),R.current&&(R.current.value=""))};return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:h("ccLane.title","CC Automation Lane")}),n.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:t,onChange:$=>i(Number($.target.value)),children:ou.map($=>n.jsxs("option",{value:$.cc,children:[$.label," (CC",$.cc,")"]},$.cc))}),n.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map($=>n.jsx("button",{className:`btn ${p===$?"btn-primary":"btn-outline-secondary"}`,onClick:()=>y($),style:{fontSize:11,textTransform:"capitalize"},children:$},$))}),n.jsxs("div",{className:"btn-group btn-group-sm",children:[n.jsx("button",{className:"btn btn-outline-secondary",onClick:d.undo,disabled:!d.canUndo,title:"Undo",children:n.jsx(W.NtdUndo,{size:14})}),n.jsx("button",{className:"btn btn-outline-secondary",onClick:d.redo,disabled:!d.canRedo,title:"Redo",children:n.jsx(W.NtdRedo,{size:14})})]}),n.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>k(!b),title:"Apply LFO modulation",children:"LFO"}),n.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:_,title:"Export CC lane as JSON",children:"Export"}),n.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var $;return($=R.current)==null?void 0:$.click()},title:"Import CC lane from JSON",children:"Import"}),n.jsx("input",{ref:R,type:"file",accept:".json",style:{display:"none"},onChange:U}),n.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>d.setEvents(e,w.filter($=>$.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginLeft:"auto"},children:[M.length," ",h("ccLane.events","events")]})]}),b&&n.jsx("div",{className:"mb-2 p-2",style:{background:"var(--nice-bg-secondary, #161b22)",borderRadius:6,border:"1px solid var(--nice-border, #30363d)"},children:n.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[n.jsxs("label",{style:{fontSize:12},children:["Wave:",n.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:j.waveform,onChange:$=>N(P=>({...P,waveform:$.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map($=>n.jsx("option",{value:$,children:$},$))})]}),n.jsxs("label",{style:{fontSize:12},children:["Rate:",n.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:.01,max:20,step:.1,value:j.rate,onChange:$=>N(P=>({...P,rate:Number($.target.value)}))})]}),n.jsxs("label",{style:{fontSize:12},children:["Depth:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:j.depth,onChange:$=>N(P=>({...P,depth:Number($.target.value)})),style:{width:80}}),n.jsx("span",{style:{fontSize:11,marginLeft:4},children:j.depth.toFixed(2)})]}),n.jsxs("label",{style:{fontSize:12},children:["Center:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:j.center,onChange:$=>N(P=>({...P,center:Number($.target.value)})),style:{width:80}}),n.jsx("span",{style:{fontSize:11,marginLeft:4},children:j.center.toFixed(2)})]}),n.jsx("button",{className:"btn btn-sm btn-primary",onClick:re,children:"Apply LFO"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>k(!1),children:"Cancel"})]})}),n.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:n.jsx("canvas",{ref:f,width:I,height:Kr+vn*2,style:{cursor:m?"crosshair":g?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:ee,onMouseMove:z,onMouseUp:q,onMouseLeave:()=>{m&&q()},onDoubleClick:K,role:"img","aria-label":"CC automation lane editor canvas"})}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:4},children:h("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Oi={"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":1/1.5,"1/8T":.5/1.5,"1/16T":.25/1.5},la={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function lu(e,t){const r=[];for(let a=0;a<t;a++)for(const s of e)r.push({...s,pitch:s.pitch+a*12});return r}function Bi(e,t){if(e.length===0)return[];const r=lu(e,t.octaves),a=[...r].sort((o,l)=>o.pitch-l.pitch),s=[...r].sort((o,l)=>l.pitch-o.pitch);let i;switch(t.mode){case"up":i=a;break;case"down":i=s;break;case"updown":i=[...a,...s.slice(1,-1)];break;case"downup":i=[...s,...a.slice(1,-1)];break;case"random":i=[...r].sort(()=>Math.random()-.5);break;case"as-played":i=[...r].sort((o,l)=>o.originalOrder-l.originalOrder);break;case"chord":i=r;break;default:i=a}if(t.repeats>1){const o=[];for(const l of i)for(let c=0;c<t.repeats;c++)o.push(l);i=o}return i}function cu(e,t,r,a=0,s=1){const i=Bi(e,t);if(i.length===0)return[];const o=60/r,l=Oi[t.rate]*o,c=l*t.gate,d=[],h=t.mode==="chord",f=h?s:i.length*s;for(let p=0;p<f;p++){const y=p%2===1?l*t.swing*.5:0,m=a+p*l+y;if(h)for(const x of i){const v=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:x.velocity;d.push({pitch:x.pitch,velocity:v,startTime:m,duration:c,step:p})}else{const x=p%i.length,v=i[x],g=t.velocityPattern?t.velocityPattern[p%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:g,startTime:m,duration:c,step:p})}}return d}function Gi(){return[{mode:"up",label:"Up",description:"Notes played low to high"},{mode:"down",label:"Down",description:"Notes played high to low"},{mode:"updown",label:"Up/Down",description:"Alternates up then down"},{mode:"downup",label:"Down/Up",description:"Alternates down then up"},{mode:"random",label:"Random",description:"Random note order"},{mode:"as-played",label:"As Played",description:"Order in which notes were pressed"},{mode:"chord",label:"Chord",description:"All notes played simultaneously"}]}function Wi(){return Object.keys(Oi)}const Ui=({config:e=la,onChange:t=()=>{},active:r=!1,onToggleActive:a=()=>{}})=>{const{t:s}=Te(),i=Gi(),o=Wi(),l=c=>t({...e,...c});return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:r?1:.6},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:s("arp.title","Arpeggiator")}),n.jsx("button",{className:`btn btn-sm ${r?"btn-success":"btn-outline-secondary"}`,onClick:a,children:r?"ON":"OFF"}),n.jsx("button",{className:`btn btn-sm ${e.latch?"btn-warning":"btn-outline-secondary"}`,onClick:()=>l({latch:!e.latch}),title:"Latch — keep arp running after releasing keys",children:"Latch"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(la),title:"Reset to defaults",children:"Reset"})]}),n.jsxs("div",{className:"row g-2",children:[n.jsxs("div",{className:"col-12",children:[n.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.mode","Mode")}),n.jsx("div",{className:"btn-group btn-group-sm w-100",children:i.map(c=>n.jsx("button",{className:`btn ${e.mode===c.mode?"btn-primary":"btn-outline-secondary"}`,onClick:()=>l({mode:c.mode}),title:c.description,style:{fontSize:11},children:c.label},c.mode))})]}),n.jsxs("div",{className:"col-6",children:[n.jsx("label",{style:{fontSize:12},className:"mb-1",children:s("arp.rate","Rate")}),n.jsx("select",{className:"form-select form-select-sm",style:{background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:o.map(c=>n.jsx("option",{value:c,children:c},c))})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.octaves","Octaves"),": ",e.octaves]}),n.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[s("arp.repeats","Repeats"),": ",e.repeats]}),n.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},du=["sine","triangle","sawtooth","square","random","sample-hold"],uu=["1/1","1/2","1/4","1/8","1/16","1/32"],xn=200,Qt=48,qi=({config:e,onChange:t,index:r,onRemove:a})=>{const{t:s}=Te(),i=u.useRef(null),o=c=>t({...e,...c}),l=u.useCallback(()=>{const c=i.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,xn,Qt),d.fillStyle=Se.resolveCssColor("var(--nice-bg-secondary, #161b22)",d.canvas),d.fillRect(0,0,xn,Qt),d.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",d.canvas),d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,Qt/2),d.lineTo(xn,Qt/2),d.stroke(),d.setLineDash([]);const h=_i(e,xn,Qt);if(h.length>0){d.beginPath(),d.strokeStyle=Se.resolveCssColor(e.enabled?"var(--nice-primary, #3b82f6)":"var(--nice-text-secondary, #484f58)",d.canvas),d.lineWidth=1.5;for(let f=0;f<h.length;f++){const p=h[f].x,y=h[f].y;f===0?d.moveTo(p,y):d.lineTo(p,y)}d.stroke()}},[e]);return u.useEffect(()=>{l()},[l]),n.jsxs("div",{className:"card p-2 mb-2",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8,opacity:e.enabled?1:.5},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsxs("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)",fontSize:13},children:[s("lfo.title","LFO")," ",r!==void 0?`#${r+1}`:""]}),n.jsx("button",{className:`btn btn-sm ${e.enabled?"btn-success":"btn-outline-secondary"}`,onClick:()=>o({enabled:!e.enabled}),style:{fontSize:11,padding:"1px 8px"},children:e.enabled?"ON":"OFF"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Dr()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),a&&n.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:a,style:{fontSize:11,padding:"1px 8px"},"aria-label":s("lfo.remove","Remove LFO"),title:s("lfo.remove","Remove LFO"),children:n.jsx(W.NtdClose,{size:12})})]}),n.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[n.jsx("canvas",{ref:i,width:xn,height:Qt,style:{borderRadius:4,border:"1px solid var(--nice-border, #30363d)",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),n.jsxs("div",{className:"flex-grow-1",children:[n.jsx("div",{className:"mb-1",children:n.jsx("div",{className:"btn-group btn-group-sm w-100",children:du.map(c=>n.jsx("button",{className:`btn ${e.waveform===c?"btn-primary":"btn-outline-secondary"}`,onClick:()=>o({waveform:c}),style:{fontSize:10,textTransform:"capitalize",padding:"1px 4px"},children:c==="sample-hold"?"S&H":c.slice(0,3)},c))})}),n.jsxs("div",{className:"row g-1",children:[n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),n.jsx("input",{type:"range",className:"form-range",min:.01,max:20,step:.1,value:e.rate,onChange:c=>o({rate:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.depth,onChange:c=>o({depth:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.center,onChange:c=>o({center:Number(c.target.value)}),style:{height:16}})]}),n.jsxs("div",{className:"col-6",children:[n.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),n.jsx("input",{type:"range",className:"form-range",min:0,max:360,step:1,value:e.phase,onChange:c=>o({phase:Number(c.target.value)}),style:{height:16}})]})]}),n.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[n.jsxs("label",{style:{fontSize:10},children:[n.jsx("input",{type:"checkbox",checked:e.syncToBpm,onChange:c=>o({syncToBpm:c.target.checked}),className:"form-check-input me-1",style:{marginTop:0,width:12,height:12}}),"BPM Sync"]}),e.syncToBpm&&n.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>o({syncDivision:c.target.value}),children:uu.map(c=>n.jsx("option",{value:c,children:c},c))}),n.jsxs("label",{style:{fontSize:10},children:["CC:",n.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>o({targetCC:Number(c.target.value)})})]})]})]})]})]})},hu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function pu(e){const t=Math.floor(e/12)-1;return`${hu[e%12]}${t}`}const Vi=({seq:e,steps:t,tracks:r,bpm:a,pattern:s,onChange:i})=>{const{t:o}=Te();if(!e)return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),n.jsx("small",{style:{color:"var(--nice-text-muted, #8b949e)"},children:"Provide a `seq` prop (useStepSequencer) for live editing."})]});const{pattern:l,currentStep:c,playing:d}=e,h=u.useMemo(()=>l.steps.slice(0,l.length),[l]);return n.jsxs("div",{className:"card p-3 mb-3",style:{background:"var(--nice-bg, #0d1117)",color:"var(--nice-text, #e6edf3)",borderRadius:8},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[n.jsx("h6",{className:"mb-0",style:{color:"var(--nice-primary, #58a6ff)"},children:o("stepSeq.title","Step Sequencer")}),n.jsx("button",{className:`btn btn-sm ${d?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60,display:"inline-flex",alignItems:"center",gap:4},children:d?n.jsxs(n.Fragment,{children:[n.jsx(W.NtdStop,{size:12})," Stop"]}):n.jsxs(n.Fragment,{children:[n.jsx(W.NtdPlay,{size:12})," Play"]})}),n.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",n.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"var(--nice-bg-secondary, #161b22)",color:"var(--nice-text, #e6edf3)",border:"1px solid var(--nice-border, #30363d)"},min:20,max:300,value:l.bpm,onChange:f=>e.setBpm(Number(f.target.value))})]}),n.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",n.jsx("input",{type:"range",min:0,max:1,step:.01,value:l.swing,onChange:f=>e.setSwing(Number(f.target.value)),style:{width:60}}),n.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(l.swing*100),"%"]})]}),n.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(f=>n.jsx("button",{className:`btn ${l.length===f?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(f),style:{fontSize:11},children:f},f))})]}),n.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),n.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),n.jsxs("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:["Shift ",n.jsx(W.NtdArrowRight,{size:12})]}),n.jsxs("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:[n.jsx(W.NtdArrowLeft,{size:12})," Shift"]}),n.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),n.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),n.jsx("div",{style:{overflowX:"auto"},children:n.jsx("div",{style:{display:"flex",gap:2,minWidth:l.length*36},children:h.map((f,p)=>{const y=f.active,m=c===p,x=p%4===0;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[n.jsx("span",{style:{fontSize:9,color:x?"var(--nice-text-muted, #8b949e)":"var(--nice-text-secondary, #30363d)"},children:p+1}),n.jsx("button",{onClick:()=>e.toggle(p),style:{width:32,height:32,borderRadius:4,border:m?"2px solid var(--nice-warning, #f0c040)":"1px solid var(--nice-border, #30363d)",background:y?`hsl(${210+f.velocity/127*40}, 80%, ${35+f.velocity/127*20}%)`:x?"var(--nice-bg-secondary, #21262d)":"var(--nice-bg-secondary, #161b22)",cursor:"pointer",padding:0,color:y?"var(--nice-text-primary, #fff)":"var(--nice-text-secondary, #484f58)",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:y?pu(f.note):""}),n.jsx("div",{style:{width:32,height:20,background:"var(--nice-bg-secondary, #161b22)",borderRadius:2,position:"relative",overflow:"hidden"},children:n.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${f.velocity/127*100}%`,background:y?"var(--nice-primary-tint-60, rgba(59, 130, 246, 0.6))":"var(--nice-primary-tint-15, rgba(59, 130, 246, 0.15))",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${f.velocity}`,onMouseDown:v=>{v.preventDefault();const g=v.target.parentElement.getBoundingClientRect(),S=k=>{const j=k.clientY-g.top,N=Math.round(Math.max(1,Math.min(127,(1-j/g.height)*127)));e.setVelocity(p,N)},b=()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",b)}})}),y&&f.probability<1&&n.jsxs("span",{style:{fontSize:8,color:"var(--nice-warning, #f0c040)"},children:[Math.round(f.probability*100),"%"]})]},p)})})}),n.jsx("div",{style:{fontSize:11,color:"var(--nice-text-muted, #8b949e)",marginTop:6},children:o("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})};function fu(e,t,r){const[a,s]=u.useState("interval"),[i,o]=u.useState(30),l=u.useRef(null),c=u.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),r("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),r("error")}},[e,t,r]);return u.useEffect(()=>{(a==="onChange"||a==="both")&&c()},[e,a,c]),u.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(a==="interval"||a==="both")&&i>0&&(l.current=window.setInterval(c,i*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[a,i,c]),{autoSaveMode:a,setAutoSaveMode:s,autoSaveInterval:i,setAutoSaveInterval:o}}function mu(e,t,r){const a=u.useRef(null),[s,i]=u.useState(!1),[o,l]=u.useState(0),[c,d]=u.useState(10),[h,f]=u.useState(!1),[p,y]=u.useState(120),m=u.useCallback((R,w)=>`L${R}-C${w}`,[]),x=u.useCallback((R,w)=>{if(!a.current||!w.audioBuffer)return;const M=m(R,w.id),I=e[R];a.current.addClip({id:M,buffer:w.audioBuffer,startTime:w.start,offset:0,duration:w.duration,layerId:R,volume:(I==null?void 0:I.volume)??1,pan:(I==null?void 0:I.pan)??0,stretchFactor:w.stretchFactor||1,effectChain:(I==null?void 0:I.effectChain)||[]})},[e,m]),v=u.useCallback((R,w)=>{var M;(M=a.current)==null||M.removeClip(m(R,w))},[m]);u.useEffect(()=>{Object.entries(t).forEach(([R,w])=>{const M=Number(R);w==null||w.forEach(I=>x(M,I))})},[t,e,x]),u.useEffect(()=>{a.current&&Object.entries(r).forEach(([R,w])=>{const M=Number(R);a.current.setMidiCCEvents(M,w)})},[r]);const g=u.useCallback(()=>{a.current&&(s?a.current.pause():a.current.play())},[s]),S=u.useCallback(()=>{var R;(R=a.current)==null||R.stop()},[]),b=u.useCallback(R=>{var w;(w=a.current)==null||w.seek(R)},[]),k=u.useCallback(()=>{if(!a.current)return;const R=!h;f(R),a.current.setLoopRegion(0,c,R)},[h,c]),j=u.useCallback(R=>{var M;const w=Math.max(1,c+R);d(w),(M=a.current)==null||M.setLoopRegion(0,w,h)},[c,h]),N=u.useCallback(async(R,w=1024)=>{const M=await R.arrayBuffer(),I=new(window.AudioContext||window.webkitAudioContext),A=await I.decodeAudioData(M.slice(0)),T=A.getChannelData(0),O=T.length,E=Math.max(1,Math.floor(O/w)),V=[];for(let ee=0;ee<w;ee++){const z=ee*E;if(z>=O)break;V.push(T[z])}return I.close(),{waveform:V.map(ee=>Math.max(-1,Math.min(1,ee))),duration:A.duration,buffer:A}},[]);return{engineRef:a,isPlaying:s,setIsPlaying:i,currentTime:o,setCurrentTime:l,duration:c,setDuration:d,isLooping:h,setIsLooping:f,bpm:p,setBpm:y,handlePlayPause:g,handleStop:S,handleSeek:b,handleToggleLoop:k,handleAdjustDuration:j,upsertEngineClip:x,removeEngineClip:v,makeEngineClipId:m,blobToWaveform:N}}class La{constructor(){this.stream=null,this.mediaRecorder=null,this.audioChunks=[],this.isRecording=!1,this.audioContext=null,this.analyser=null,this.gainNode=null,this.monitorGain=null,this.levelRaf=null}async startRecording(t={}){if(this.isRecording)return;this.levelCallback=t.onLevel,this.stream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});const r=t.mimeType||"audio/webm";this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:r}),this.audioChunks=[],this.audioContext=new(window.AudioContext||window.webkitAudioContext);let s=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,s.connect(this.gainNode),s=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,s.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,s.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const i=()=>{if(!this.analyser)return;const o=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(o);let l=0;for(let d=0;d<o.length;d++){const h=(o[d]-128)/128;l+=h*h}const c=Math.sqrt(l/o.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(i))};this.mediaRecorder.ondataavailable=o=>{o.data&&o.data.size>0&&this.audioChunks.push(o.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(i)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const r=this.mediaRecorder;r.onstop=()=>{const a=new Blob(this.audioChunks,{type:r.mimeType});this.cleanup(),t(a)},r.stop(),this.isRecording=!1})}cleanup(){this.levelRaf&&(cancelAnimationFrame(this.levelRaf),this.levelRaf=null),this.levelCallback=void 0,this.monitorGain&&(this.monitorGain.disconnect(),this.monitorGain=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}function gu(e){const[t,r]=u.useState(!1),[a,s]=u.useState(!1),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(null),f=u.useRef(null),p=u.useRef(null),y=u.useRef(0),m=u.useRef(null),x=u.useRef(null),v=u.useCallback(()=>{m.current&&(clearInterval(m.current),m.current=null),x.current&&(clearTimeout(x.current),x.current=null)},[]),g=u.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(f.current||(f.current=new La),y.current=p.current??e.currentTime,r(!0),o(0),await f.current.startRecording({onLevel:o}))},[e,t]),S=u.useCallback(async()=>{var T;if(v(),s(!1),c(0),p.current=null,!f.current){r(!1),o(0);return}const j=await f.current.stopRecording();if(r(!1),o(0),!j||!e.activeLayer)return;const{waveform:N,duration:R,buffer:w}=await e.blobToWaveform(j),M=e.activeLayer.id;e.setWaveforms(O=>({...O,[M]:N}));const I=Math.max(0,y.current||0),A={id:Date.now(),label:"Recording",start:I,duration:R,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(T=e.layerSettings[M])==null?void 0:T.color,blob:j,blobUrl:URL.createObjectURL(j),audioBuffer:w};e.setLayerClips(O=>({...O,[M]:[...O[M]||[],A]})),e.upsertEngineClip(M,A),e.setSelectedClip({layerId:M,clipId:A.id})},[e,v]),b=u.useCallback(j=>{if(j<=0){g();return}s(!0),c(j);const N=performance.now();m.current=window.setInterval(()=>{const R=(performance.now()-N)/1e3;c(Math.max(0,j-R))},100),x.current=window.setTimeout(()=>{v(),s(!1),c(0),p.current||g()},j*1e3)},[g,v]),k=u.useCallback(async()=>{if(t||a){await S();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const j=Math.max(0,e.countInBars)*4*(60/e.bpm),N=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;N&&(p.current=N),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),N?j>0&&b(j):b(j)},[t,a,e,S,b]);return{isRecording:t,isCountIn:a,monitorLevel:i,countInRemaining:l,punchOut:d,setPunchOut:h,armedPunchInRef:p,recorderRef:f,clearCountInTimers:v,startRecordingNow:g,stopRecordingFlow:S,handleRecord:k}}var Hi=(e=>(e.Recorder="Recorder",e.AudioClip="Audio Clip",e.SpeechSynth="Speech Synth",e.Stream="Stream",e.KeyboardPad="Keyboard/Pads",e.Keyboard="Keyboard",e.AudioClipCompact="AudioClip",e))(Hi||{});const yu={};class Qn{constructor(t,r,a,s={}){this.type=t,this.name=r,this.component=yu[t]??(()=>null),this.audioType=a,this.parameters=s}}new Qn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new Qn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new Qn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new Qn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function Ki(e,t,r,a,s){r(i=>t?[...i,t]:i),a([]),s(e)}function bu(e,t,r,a){t(s=>{if(s.length===0)return s;const i=s[s.length-1];return r(o=>e?[e,...o]:o),a(i),s.slice(0,-1)})}function vu(e,t,r,a){r(s=>{if(s.length===0)return s;const i=s[0];return t(o=>e?[...o,e]:o),a(i),s.slice(1)})}class xu{constructor(t={}){this.undoStack=[],this.redoStack=[],this.maxSize=t.maxSize??100,this.onChange=t.onChange}push(t,r,a,s){this.undoStack.push({label:t,category:r,timestamp:Date.now(),oldState:a,newState:s}),this.undoStack.length>this.maxSize&&this.undoStack.shift(),this.redoStack.length=0}undo(){var r;const t=this.undoStack.pop();return t?(this.redoStack.push(t),(r=this.onChange)==null||r.call(this,t,"undo"),t.oldState):null}redo(){var r;const t=this.redoStack.pop();return t?(this.undoStack.push(t),(r=this.onChange)==null||r.call(this,t,"redo"),t.newState):null}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get undoLabel(){return this.undoStack.length>0?this.undoStack[this.undoStack.length-1].label:null}get redoLabel(){return this.redoStack.length>0?this.redoStack[this.redoStack.length-1].label:null}get undoCount(){return this.undoStack.length}get redoCount(){return this.redoStack.length}getHistory(){return[...this.undoStack].reverse()}clear(){this.undoStack.length=0,this.redoStack.length=0}undoTo(t){const r=Math.min(t+1,this.undoStack.length);let a=null;for(let s=0;s<r;s++)a=this.undo();return a}}const Su=ot.scoped("useProjectCRUD");function ku(e){const{project:t,activeSection:r,setProject:a,setActiveSection:s,setLayers:i,setActiveLayer:o,setUndoStack:l,setRedoStack:c}=e,d=u.useCallback(v=>Ki(v,t,l,c,a),[t,l,c,a]),h=u.useCallback(async()=>{var b;if(!t)return;const v=(((b=t.sections)==null?void 0:b.length)??0)+1,S={id:await e.addSection(t.id,"Section",v),projectId:t.id,name:"Section",orderNumber:v,layers:[]};d({...t,sections:[...t.sections||[],S]}),s(S)},[t,d,s]),f=u.useCallback(async v=>{var b,k,j;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(v);const S=(t.sections??[]).filter(N=>N.id!==v);d({...t,sections:S}),s(S[0]??null),i(((b=S[0])==null?void 0:b.layers)??[]),o(((j=(k=S[0])==null?void 0:k.layers)==null?void 0:j[0])??null)},[t,d,s,i,o,e]),p=u.useCallback(async()=>{var g;if(!r)return;const v={id:-Date.now(),name:"New Layer",sectionId:r.id,audioSource:Hi.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};i(S=>[...S,v]),o(v);try{const S=await e.addLayer(r.id,v.name,v.audioSource,v.audioSourceParameters);i(b=>b.map(k=>k.id===v.id?{...v,id:S}:k)),t&&d({...t,sections:((g=t.sections)==null?void 0:g.map(b=>b.id===r.id?{...b,layers:[...(b.layers??[]).filter(k=>k.id!==S),{...v,id:S}]}:b))??[]})}catch(S){i(b=>b.filter(k=>k.id!==v.id)),Su.error("Failed to add layer:",S)}},[r,t,d,i,o]),y=u.useCallback(async v=>{var S,b;if((S=e.layerSettings[v])!=null&&S.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[v]||[]).forEach(k=>e.removeEngineClip(v,k.id)),e.setLayerMidiNotes(k=>{const j={...k};return delete j[v],j}),await e.deleteLayer(v),i(k=>k.filter(j=>j.id!==v)),o(k=>(k==null?void 0:k.id)===v?null:k),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(k=>k.id===(r==null?void 0:r.id)?{...k,layers:(k.layers??[]).filter(j=>j.id!==v)}:k))??[]}))},[t,r,d,i,o,e]),m=u.useCallback(async()=>{if(!t)return;const v=e.projectVolume===""?void 0:Number(e.projectVolume);if(Number.isNaN(v)){e.setStatusType("error"),e.setStatusMessage("Volume musi byc liczba");return}if(!e.projectName.trim()){e.setStatusType("error"),e.setStatusMessage("Nazwa projektu nie moze byc pusta");return}await e.updateProject(t.id,{name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),d({...t,name:e.projectName||t.name,isTemplate:e.projectIsTemplate,volume:v}),e.setStatusType("success"),e.setStatusMessage("Project saved")},[t,e,d]),x=u.useCallback(async()=>{var S;if(!r)return;const v=e.sectionName||r.name,g=e.sectionOrder===""?r.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(g)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(r.id,{name:v,orderNumber:g}),s({...r,name:v,orderNumber:g}),t&&d({...t,sections:((S=t.sections)==null?void 0:S.map(b=>b.id===r.id?{...b,name:v,orderNumber:g}:b))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[r,t,e,d,s]);return{handleAddSection:h,handleDeleteSection:f,handleAddLayer:p,handleDeleteLayer:y,handleSaveProject:m,handleSaveSection:x}}const Yi=u.createContext(null);function wu(){const e=u.useContext(Yi);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const Da=({value:e,children:t})=>n.jsx(Yi.Provider,{value:e,children:t});Da.displayName="EditorTrackProvider";const cn=(e,t)=>t&&t>0?e*15/t:e/10,za=e=>{for(const t of e){const r=t.trim();if(r.toUpperCase().startsWith("#BPM:")){const a=parseFloat(r.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},Cu=(e,t)=>{const r=t??za(e),a=[];let s="",i=0,o="",l=!0;function c(){o.trim()!==""&&(s.length>0&&(s+=" "),s+=o.trim()),o=""}return e.forEach(d=>{if(!(d.startsWith("#")||d.startsWith("E"))){if(d.startsWith("-"))c(),s.trim().length>0&&(a.push({text:s.trim(),timestamp:i}),s=""),l=!0;else if(d.startsWith(":")||d.startsWith("*")){const h=d.indexOf(" "),f=d.indexOf(" ",h+1),p=d.indexOf(" ",f+1),y=d.indexOf(" ",p+1);if(y===-1)return;const m=cn(parseFloat(d.substring(h+1,f)),r);s===""&&(i=m);const x=d.substring(y+1);if(x.trim()==="~")return;let v=x;v.startsWith("~")&&(v=v.substring(1)),l?(c(),o=v.trimEnd()):o+=v.trimEnd(),l=x.endsWith(" ")}}}),c(),s.trim().length>0&&a.push({text:s.trim(),timestamp:i}),a},ju=(e,t)=>{const r=t??za(e),a=[];let s=[],i="",o=0,l=!0,c=null,d="";function h(){c&&d.trim()!==""&&(c.text=d.trim(),s.push({...c}),i.length>0&&(i+=" "),i+=c.text),c=null,d=""}return e.forEach(f=>{if(!(f.startsWith("#")||f.startsWith("E"))){if(f.startsWith("-"))h(),i.trim().length>0&&(a.push({text:i.trim(),timestamp:o,words:s}),i="",s=[]),l=!0;else if(f.startsWith(":")||f.startsWith("*")){const p=f.startsWith("*"),y=f.indexOf(" "),m=f.indexOf(" ",y+1),x=f.indexOf(" ",m+1),v=f.indexOf(" ",x+1);if(v===-1)return;const g=cn(parseFloat(f.substring(y+1,m)),r),S=cn(parseFloat(f.substring(m+1,x)),r),b=g+S;i===""&&(o=g);const k=f.substring(v+1);if(k.trim()==="~"){c&&(c.endTime=b);return}let j=k;j.startsWith("~")&&(j=j.substring(1)),l?(h(),d=j.trimEnd(),c={text:"",startTime:g,endTime:b,isGolden:p}):c?(d+=j.trimEnd(),c.endTime=b,p&&(c.isGolden=!0)):(d=j.trimEnd(),c={text:"",startTime:g,endTime:b,isGolden:p}),l=k.endsWith(" ")}}}),h(),i.trim().length>0&&a.push({text:i.trim(),timestamp:o,words:s}),a},Xi=(e,t)=>{const r=t??za(e),a=[];let s=[],i=0;function o(){s.length>0&&(a.push({timestamp:i,syllables:[...s]}),s=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){o();const c=l.trim().split(/\s+/);if(c.length>=2){const d=parseFloat(c[1]);isFinite(d)&&(i=cn(d,r))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),h=l.indexOf(" ",d+1),f=l.indexOf(" ",h+1),p=l.indexOf(" ",f+1);if(p===-1)return;const y=parseFloat(l.substring(d+1,h)),m=parseFloat(l.substring(h+1,f)),x=cn(y,r),v=x+cn(m,r);s.length===0&&(i=x);const g=l.substring(p+1);if(g.trim()==="~"){s.length>0&&(s[s.length-1].endTime=v);return}let S=g;S.startsWith("~")&&(S=S.substring(1));const b=g.endsWith(" "),k=b?S.slice(0,-1):S;s.push({text:k,startTime:x,endTime:v,isGolden:c,hasTrailingSpace:b})}}}),o(),a},Mu=(e,t,r=3)=>{const a=[];let s=-1;for(let i=0;i<e.length;i++){const o=e[i].timestamp,l=e[i+1]?e[i+1].timestamp:o+5;if(t>=o&&t<l){s=i;break}}if(s>=0){const i=Math.max(0,s-(r-1));for(let o=i;o<=s;o++)a.push(e[o].text)}return a},Ru=(e,t)=>{const r=[];for(const a of e)for(const s of a.words)t>=s.startTime&&t<=s.endTime&&r.push(s);return r},Ns="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",Ts="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Nu="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Tu="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",$u=({song:e,currentTime:t=0})=>{const r=u.useMemo(()=>!e||!e.notes.length?[]:Xi(e.notes.map(l=>l.noteLine),e.bpm??void 0),[e]),a=t-((e==null?void 0:e.gap)??0)/1e3;let s=-1;for(let l=0;l<r.length;l++){const c=r[l].timestamp,d=l+1<r.length?r[l+1].timestamp:c+30;if(a>=c&&a<d){s=l;break}}const i=s>=0?r[s]:null,o=s>=0&&s+1<r.length?r[s+1]:null;return n.jsx("div",{className:"karaoke-lyrics",style:{textAlign:"center",fontSize:"28px",marginTop:"20px",minHeight:"80px",textShadow:"var(--karaoke-outline, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000)",fontWeight:700,fontStyle:"italic",fontFamily:"var(--karaoke-font-family, Arial)"},children:i?n.jsxs(n.Fragment,{children:[n.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:Nu,background:"var(--karaoke-active-bg, linear-gradient(90deg, transparent 0%, rgba(0,229,255,0.08) 20%, rgba(255,230,0,0.06) 80%, transparent 100%))",borderRadius:8,padding:"2px 10px",transition:"text-shadow 0.3s ease, background 0.3s ease"},children:i.syllables.map((l,c)=>{let d=0;a>=l.endTime?d=1:a>l.startTime&&(d=(a-l.startTime)/(l.endTime-l.startTime));const h=Math.round(d*100),f=l.text+(l.hasTrailingSpace?" ":""),p=d>0&&d<1,y=l.isGolden;return d<=0?n.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:f},c):d>=1?n.jsx("span",{style:{background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ns,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:y?`drop-shadow(${Ts})`:"none",transition:"filter 0.2s ease"},children:f},c):n.jsxs("span",{style:{position:"relative",display:"inline",filter:p?y?`drop-shadow(${Ts})`:`drop-shadow(${Tu})`:"none",transition:"filter 0.15s ease"},children:[n.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:f}),n.jsx("span",{style:{position:"absolute",left:0,top:0,background:y?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":Ns,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-h}% 0 0)`,pointerEvents:"none"},children:f})]},c)})}),o&&n.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:o.syllables.map((l,c)=>n.jsx("span",{style:{color:l.isGolden?"var(--karaoke-golden-next, rgba(255,215,0,0.5))":"var(--karaoke-next-dim, #777)"},children:l.text+(l.hasTrailingSpace?" ":"")},c))})]}):r.length>0?n.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:n.jsx(W.NtdMusic,{size:20})}):n.jsxs("p",{style:{color:"var(--karaoke-waiting-text, #999)",display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdMicrophone,{size:18})," Waiting for lyrics..."]})})},_a=u.memo($u),Yr={},Pu=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(Yr==null?void 0:Yr.VITE_DEBUG_KARAOKE)==="true";function ca(e,t,...r){(Pu||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:var(--nice-color-accent-hover, #6c3483);color:var(--nice-text-on-primary, #FFF);padding: var(--nice-space-px, 1px) var(--nice-space-1, 4px);border-radius:var(--nice-radius-sm, 3px);font-weight:bold","color:var(--nice-color-accent-hover, #6c3483);font-weight:bold",...r)}const Zi=e=>{for(const t of e){const r=t.trim();if(r.toUpperCase().startsWith("#BPM:")){const a=parseFloat(r.substring(5).replace(",","."));if(isFinite(a)&&a>0)return a}}return null},$s=(e,t)=>t&&t>0?e*15/t:e/10,Hn=(e,t)=>{const r=t??Zi(e),a=[];let s=[];return e.forEach(i=>{const o=i.split(" ");if(!(o.length<4))if(i.startsWith("-"))s.length>0&&(a.push(s),s=[]);else{const l=(o[0]||"").charAt(0),c=l==="*"||l==="G";s.push({startTime:$s(parseFloat(o[1]),r),duration:$s(parseFloat(o[2]),r),pitch:parseInt(o[3],10),isGold:c})}}),s.length>0&&a.push(s),a},Qi=(e,t)=>{let a=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;a-t>6;)a-=12;for(;a-t<-6;)a+=12}return a},Au=ot.scoped("karaokeScoringConfig"),Fa={easy:{semitoneTolerance:2,preWindow:.25,postExtra:.3,difficultyMult:.9},normal:{semitoneTolerance:1,preWindow:.15,postExtra:.2,difficultyMult:1},hard:{semitoneTolerance:0,preWindow:.08,postExtra:.12,difficultyMult:1.05}},Eu="karaoke.scoringPresets";function Iu(){try{const e=localStorage.getItem(Eu);return e?JSON.parse(e):null}catch(e){return Au.warn("Failed to parse scoring presets overrides",e),null}}function Ji(e){const t={...Fa},r=Iu();return r&&Object.keys(r).forEach(a=>{const s=r[a];s&&(t[a]={...t[a],...s})}),e&&Object.keys(e).forEach(a=>{const s=e[a];s&&(t[a]={...t[a],...s})}),t}exports.ScoringPresets=Ji();const Lu=async e=>{try{let t=null;if(e?t=await e.getKaraokeScoringConfig():(console.debug("[karaokeScoringConfig] No fetcher provided, using defaults"),t=null),t&&t.presets)return exports.ScoringPresets=Ji(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},zr=(e="normal")=>exports.ScoringPresets[e]||Fa.normal,Du=3,te=Du;function qt(e){const t=e/2|0;return{w:t,out:`M${t} 0H${t}V${e}H${t}A${t} ${t} 0 0 1 0 ${t}A${t} ${t} 0 0 1 ${t} 0Z`,inn:`M${t} ${te}V${e-te}A${t-te} ${t-te} 0 0 1 ${te} ${t}A${t-te} ${t-te} 0 0 1 ${t} ${te}Z`}}function dn(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M${te} ${te}H${te+1}V${e-te}H${te}Z`}}function Oa(e){const t=Math.min(14,e*.22)|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t}Q0 ${e} 0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}V${te+a}Q${te} ${te} ${te+a} ${te}Z`}}function Mr(e){const t=e*.3|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}L${te} ${e-te-a}V${te+a}Z`}}function Ot(e){const t=e*.42|0,r=t+2,a=Math.max(t-(te*1.4|0),2);return{w:r,out:`M${t} 0H${r}V${e}H${t}L0 ${e/2}Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+a}L${te} ${e/2}Z`}}function Rr(e){const t=e*.3|0,r=t+4,a=Math.max(t-te,1);return{w:r,out:`M${t} 0H${r}V${e}H${t*.6|0}L0 ${e-t}V${t}Q0 0 ${t} 0Z`,inn:`M${te+a} ${te}H${r}V${e-te}H${te+(a*.6|0)}L${te} ${e-te-a}V${te+a}Q${te} ${te} ${te+a} ${te}Z`}}function Ba(e){const t=e*.16|0,r=t*2+4;return{w:r,out:`M${t*1.5|0} 0H${r}V${e}H${t*1.5|0}C${t*2.5|0} ${e*.35|0} ${t*2.5|0} ${e*.65|0} ${t*1.5|0} ${e}Z`,inn:`M${te+(t*1.2|0)} ${te}H${r}V${e-te}H${te+(t*1.2|0)}C${te+(t*2.2|0)} ${e*.37|0} ${te+(t*2.2|0)} ${e*.63|0} ${te+(t*1.2|0)} ${e-te}Z`}}function Ga(e){const t=e*.32|0,r=t+3,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${te} ${te}H${r}V${e-te}H${te+a}Q${te} ${e-te} ${te} ${e-te-a}Z`}}function Nr(e){const t=e*.14|0,r=t*3+2;return{w:r,out:`M${t*2} 0H${r}V${e}H${t*2}C${t*.5|0} ${e*.8|0} ${t*3} ${e*.55|0} ${t*.5|0} ${e*.35|0}S${t} 0 ${t*2} 0Z`,inn:`M${te+(t*1.8|0)} ${te}H${r}V${e-te}H${te+(t*1.8|0)}C${te+(t*.4|0)} ${e*.78|0} ${te+(t*2.8|0)} ${e*.55|0} ${te+(t*.4|0)} ${e*.37|0}S${te+(t*.9|0)} ${te} ${te+(t*1.8|0)} ${te}Z`}}function Wa(e){const t=e*.09|0,r=e*.35|0;return{w:r,out:`M${t*3} 0H${r}V${e}H${t*3}L${t} ${e-t*2}L${t*2} ${e*.65|0}L0 ${e/2|0}L${t*2} ${e*.35|0}L${t} ${t*2}Z`,inn:`M${te+(t*2.5|0)} ${te}H${r}V${e-te}H${te+(t*2.5|0)}L${te+(t*.7|0)} ${e-te-(t*1.6|0)}L${te+(t*1.7|0)} ${e*.64|0}L${te} ${e/2|0}L${te+(t*1.7|0)} ${e*.36|0}L${te+(t*.7|0)} ${te+(t*1.6|0)}Z`}}function hr(e){const t=e*.42|0,r=t+2;return{w:r,out:`M${t} 0H${r}V${e}H0Z`,inn:`M${te+t-(te*1.3|0)} ${te}H${r}V${e-te}H${te+1}Z`}}function da(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r}V${e}H${t}Z`,inn:`M${te} ${te}H${r}V${e-te}H${te+t-(te*1.3|0)+1}Z`}}function _t(e){const t=e/2|0;return{w:t,out:`M0 0A${t} ${t} 0 0 1 ${t} ${t}A${t} ${t} 0 0 1 0 ${e}Z`,inn:`M0 ${te}A${t-te} ${t-te} 0 0 1 ${t-te} ${t}A${t-te} ${t-te} 0 0 1 0 ${e-te}Z`}}function un(e){return{w:te+1,out:`M0 0H${te+1}V${e}H0Z`,inn:`M0 ${te}H1V${e-te}H0Z`}}function eo(e){const t=Math.min(14,e*.22)|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}Q${r} 0 ${r} ${t}V${e-t}Q${r} ${e} ${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}Q${r-te} ${te} ${r-te} ${te+a}V${e-te-a}Q${r-te} ${e-te} ${r-te-a} ${e-te}H0Z`}}function hn(e){const t=e*.3|0,r=t+2,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}L${r} ${t}V${e-t}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}L${r-te} ${te+a}V${e-te-a}L${r-te-a} ${e-te}H0Z`}}function $t(e){const t=e*.42|0,r=t+2,a=Math.max(t-(te*1.4|0),2);return{w:r,out:`M0 0H${r-t}L${r} ${e/2}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}L${r-te} ${e/2}L${r-te-a} ${e-te}H0Z`}}function to(e){const t=e*.3|0,r=t+4,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r-t}Q${r} 0 ${r} ${t}V${e-t}L${r-(t*.6|0)} ${e}H0Z`,inn:`M0 ${te}H${r-te-a}Q${r-te} ${te} ${r-te} ${te+a}V${e-te-a}L${r-te-(a*.6|0)} ${e-te}H0Z`}}function no(e){const t=e*.16|0,r=t*2+4;return{w:r,out:`M0 0H${r-(t*1.5|0)}C${r-(t*2.5|0)} ${e*.35|0} ${r-(t*2.5|0)} ${e*.65|0} ${r-(t*1.5|0)} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*1.2|0)}C${r-te-(t*2.2|0)} ${e*.37|0} ${r-te-(t*2.2|0)} ${e*.63|0} ${r-te-(t*1.2|0)} ${e-te}H0Z`}}function ro(e){const t=e*.32|0,r=t+3,a=Math.max(t-te,1);return{w:r,out:`M0 0H${r}V${e-t}Q${r} ${e} ${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te}V${e-te-a}Q${r-te} ${e-te} ${r-te-a} ${e-te}H0Z`}}function Ua(e){const t=e*.14|0,r=t*3+2;return{w:r,out:`M0 0H${r-t*2}C${r-t} 0 ${r+(t*.3|0)} ${e*.2|0} ${r-(t*.5|0)} ${e*.35|0}S${r-(t*.5|0)} ${e*.8|0} ${r-t*2} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*1.8|0)}C${r-te-(t*.9|0)} ${te} ${r-te+(t*.1|0)} ${e*.22|0} ${r-te-(t*.4|0)} ${e*.37|0}S${r-te-(t*.4|0)} ${e*.78|0} ${r-te-(t*1.8|0)} ${e-te}H0Z`}}function Tr(e){const t=e*.09|0,r=e*.35|0;return{w:r,out:`M0 0H${r-t*3}L${r-t} ${t*2}L${r-t*2} ${e*.35|0}L${r} ${e/2|0}L${r-t*2} ${e*.65|0}L${r-t} ${e-t*2}L${r-t*3} ${e}H0Z`,inn:`M0 ${te}H${r-te-(t*2.5|0)}L${r-te-(t*.7|0)} ${te+(t*1.6|0)}L${r-te-(t*1.7|0)} ${e*.36|0}L${r-te} ${e/2|0}L${r-te-(t*1.7|0)} ${e*.64|0}L${r-te-(t*.7|0)} ${e-te-(t*1.6|0)}L${r-te-(t*2.5|0)} ${e-te}H0Z`}}function ua(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r}L${r-t} ${e}H0Z`,inn:`M0 ${te}H${r-te}L${r-te-t+(te*1.3|0)} ${e-te}H0Z`}}function pr(e){const t=e*.42|0,r=t+2;return{w:r,out:`M0 0H${r-t}L${r} ${e}H0Z`,inn:`M0 ${te}H${r-te-t+(te*1.3|0)}L${r-te} ${e-te}H0Z`}}const qa=[{name:"Pill",L:qt,R:_t},{name:"Sharp",L:dn,R:un},{name:"Soft",L:Oa,R:eo},{name:"Chamfer",L:Mr,R:hn},{name:"Arrow",L:Ot,R:$t},{name:"Shield",L:Rr,R:to},{name:"Bracket",L:Ba,R:no},{name:"Tab",L:Ga,R:ro},{name:"Wave",L:Nr,R:Ua},{name:"Ornate",L:Wa,R:Tr}],ao=[{name:"Pill→Arrow",L:qt,R:$t},{name:"Arrow→Pill",L:Ot,R:_t},{name:"Pill→Sharp",L:qt,R:un},{name:"Sharp→Pill",L:dn,R:_t},{name:"Pill→Chamfer",L:qt,R:hn},{name:"Chamfer→Pill",L:Mr,R:_t},{name:"Arrow→Sharp",L:Ot,R:un},{name:"Sharp→Arrow",L:dn,R:$t},{name:"Arrow→Chamfer",L:Ot,R:hn},{name:"Chamfer→Arrow",L:Mr,R:$t},{name:"Soft→Arrow",L:Oa,R:$t},{name:"Shield→Chamfer",L:Rr,R:hn},{name:"Pill→Wave",L:qt,R:Ua},{name:"Wave→Arrow",L:Nr,R:$t},{name:"Tab→Pill",L:Ga,R:_t},{name:"Ornate→Sharp",L:Wa,R:un},{name:"Sharp→Ornate",L:dn,R:Tr},{name:"Bracket→Arrow",L:Ba,R:$t},{name:"Shield→Pill",L:Rr,R:_t},{name:"Wave→Ornate",L:Nr,R:Tr}],so=[{name:"Skew ╲",L:hr,R:ua},{name:"Skew ╱",L:da,R:pr},{name:"◇ Romb",L:Ot,R:$t},{name:"╲→Pill",L:hr,R:_t},{name:"Pill→╲",L:qt,R:ua},{name:"╱→Sharp",L:da,R:un},{name:"Sharp→╱",L:dn,R:pr},{name:"╲→Arrow",L:hr,R:$t},{name:"Arrow→╱",L:Ot,R:pr},{name:"◇→Chamfer",L:Ot,R:hn}],Wn=[...qa,...ao,...so],io=qa[0];function Rn(e){return Wn.find(t=>t.name===e)||io}const $r=[{name:"Flames",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M6 0C8 3 10 5 9 9C8 12 6 14 6 16C6 14 4 12 3 9C2 5 4 3 6 0Z" fill="${t}" opacity=".5"/><path d="M3 6C4 8 5 10 3 14C1 10 2 8 3 6Z" fill="${a}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${a}" opacity=".3"/></pattern>`}},{name:"Zigzag",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 5L5 0L10 5L5 10Z" fill="${r||t}" fill-opacity=".15" stroke="${t}" stroke-width="1.2" opacity=".55"/></pattern>`},{name:"Scales",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="12" height="8" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="8" rx="6" ry="4.5" fill="none" stroke="${t}" stroke-width="1" opacity=".5"/><ellipse cx="0" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".3"/></pattern>`}},{name:"Hex",mk:(e,t,r)=>`<pattern id="${e}" width="18" height="20" patternUnits="userSpaceOnUse"><path d="M9 2L16 6V14L9 18L2 14V6Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M9 12L13.5 14.5V19L9 21.5L4.5 19V14.5Z" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Dots",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="8" height="8" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2" fill="${t}" opacity=".5"/><circle cx="0" cy="0" r="1" fill="${a}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${a}" opacity=".3"/></pattern>`}},{name:"Stars",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 1L8.8 5.2L13.2 5.2L9.7 7.8L11 12.2L7 9.4L3 12.2L4.3 7.8L.8 5.2L5.2 5.2Z" fill="${t}" opacity=".45" stroke="${r||t}" stroke-width=".4" stroke-opacity=".3"/></pattern>`},{name:"Diamonds",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 .5L9.5 5L5 9.5L.5 5Z" fill="${r||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Waves",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4Q4 0 8 4Q12 8 16 4" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 6Q4 2 8 6Q12 10 16 6" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Crosses",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M5 2V8" stroke="${t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/><path d="M2 5H8" stroke="${r||t}" stroke-width="1.3" stroke-linecap="round" opacity=".5"/></pattern>`},{name:"Triangles",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M6 1L11 9H1Z" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Chevrons",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M0 7L6 1.5L12 7" fill="none" stroke="${t}" stroke-width="1.2" opacity=".55"/><path d="M0 10L6 4.5L12 10" fill="none" stroke="${r||t}" stroke-width=".7" opacity=".25"/></pattern>`},{name:"Hatch ╲",mk:(e,t,r)=>`<pattern id="${e}" width="6" height="6" patternUnits="userSpaceOnUse"><path d="M0 6L6 0" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M-1 1L1 -1M5 7L7 5" stroke="${r||t}" stroke-width=".8" opacity=".3"/></pattern>`},{name:"Hatch ╳",mk:(e,t,r)=>`<pattern id="${e}" width="7" height="7" patternUnits="userSpaceOnUse"><path d="M0 7L7 0" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 0L7 7" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Grid",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M10 0V10" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M0 10H10" fill="none" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Bricks",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><line x1="7" y1="0" x2="7" y2="4" stroke="${r||t}" stroke-width=".8" opacity=".4"/></pattern>`},{name:"Hearts",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M6 10C4 8 1 6.5 1 4C1 2.3 2.8 1 4.5 2.2L6 4L7.5 2.2C9.2 1 11 2.3 11 4C11 6.5 8 8 6 10Z" fill="${t}" opacity=".4" stroke="${r||t}" stroke-width=".5" stroke-opacity=".3"/></pattern>`},{name:"Arrows",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="10" patternUnits="userSpaceOnUse"><path d="M3 2L9 5L3 8" fill="${r||"none"}" fill-opacity=".15" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/></pattern>`},{name:"Bolts",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="16" patternUnits="userSpaceOnUse"><path d="M7 1L4 7H8L3 15" fill="none" stroke="${t}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity=".5"/><circle cx="5" cy="11" r="1" fill="${r||t}" opacity=".3"/></pattern>`},{name:"Leaves",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M7 2C10 4 12 7 10 11C8 13 5 12 4 10C3 7 4 4 7 2Z" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M7 3L6 10" stroke="${a}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${a}" stroke-width=".4" opacity=".25"/></pattern>`}},{name:"Spirals",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 4A4 4 0 0 1 12 8A3.5 3.5 0 0 1 8.5 11.5A2.5 2.5 0 0 1 6 9A1.5 1.5 0 0 1 7.5 7.5" fill="none" stroke="${t}" stroke-width="1.2" stroke-linecap="round" opacity=".45"/><circle cx="8" cy="8" r="1" fill="${r||t}" opacity=".25"/></pattern>`},{name:"Moons",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="14" patternUnits="userSpaceOnUse"><path d="M9 2A5 5 0 1 0 9 12" fill="none" stroke="${t}" stroke-width="1" opacity=".4"/><path d="M9 2A3.5 3.5 0 0 1 9 12" fill="none" stroke="${r||t}" stroke-width="1" opacity=".3"/></pattern>`},{name:"Rings",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="6" cy="6" r="4" fill="none" stroke="${t}" stroke-width="1.2" opacity=".5"/><circle cx="6" cy="6" r="2" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".25"/></pattern>`},{name:"Teeth",mk:(e,t,r)=>`<pattern id="${e}" width="8" height="10" patternUnits="userSpaceOnUse"><path d="M0 10V4L4 0L8 4V10" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`},{name:"Swirl",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="10" patternUnits="userSpaceOnUse"><path d="M0 5C3 0 6 0 8 5C10 10 13 10 16 5" fill="none" stroke="${t}" stroke-width="1.3" opacity=".5"/><path d="M0 7C3 2 6 2 8 7C10 12 13 12 16 7" fill="none" stroke="${r||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Chain",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="16" patternUnits="userSpaceOnUse"><ellipse cx="5" cy="4" rx="3.5" ry="4" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><ellipse cx="5" cy="12" rx="3.5" ry="4" fill="none" stroke="${r||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Feathers",mk:(e,t,r)=>`<pattern id="${e}" width="12" height="18" patternUnits="userSpaceOnUse"><path d="M6 1C9 5 10 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M6 1C3 5 2 9 6 17" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><path d="M4 5L6 4L8 5M4 9L6 8L8 9M4 13L6 12L8 13" stroke="${r||t}" stroke-width=".5" opacity=".3"/></pattern>`},{name:"DNA",mk:(e,t,r)=>`<pattern id="${e}" width="14" height="18" patternUnits="userSpaceOnUse"><path d="M3 0C3 4.5 11 4.5 11 9S3 13.5 3 18" fill="none" stroke="${t}" stroke-width="1" opacity=".45"/><path d="M11 0C11 4.5 3 4.5 3 9S11 13.5 11 18" fill="none" stroke="${r||t}" stroke-width="1" opacity=".45"/></pattern>`},{name:"Bubbles",mk:(e,t,r)=>{const a=r||t;return`<pattern id="${e}" width="18" height="18" patternUnits="userSpaceOnUse"><circle cx="5" cy="5" r="3.5" fill="none" stroke="${t}" stroke-width=".8" opacity=".4"/><circle cx="14" cy="12" r="4.5" fill="none" stroke="${a}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${a}" opacity=".25"/></pattern>`}},{name:"Celtic",mk:(e,t,r)=>`<pattern id="${e}" width="16" height="16" patternUnits="userSpaceOnUse"><path d="M8 2C12 2 14 4 14 8C14 12 12 14 8 14C4 14 2 12 2 8C2 4 4 2 8 2Z" fill="none" stroke="${t}" stroke-width=".8" opacity=".35"/><path d="M4 4L12 12M12 4L4 12" stroke="${r||t}" stroke-width=".6" opacity=".2"/></pattern>`},{name:"Squares",mk:(e,t,r)=>`<pattern id="${e}" width="10" height="10" patternUnits="userSpaceOnUse"><rect x="1.5" y="1.5" width="7" height="7" rx="1" fill="${r||"none"}" fill-opacity=".12" stroke="${t}" stroke-width="1" opacity=".5"/></pattern>`}];function Nn(e){return $r.find(t=>t.name===e)||null}const Kt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},_r={...Kt,glass:85},Fr={...Kt,patternName:"Stars"},Or={...Kt,patternName:"Stars"},Br={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},oo={filledBar:{...Kt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br},disableGoldNotes:!1},pn={capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,emptyGlass:85,filledTextureUrl:null,emptyTextureUrl:null,textureScale:1,emptyPreset:"custom",goldPatternName:"Stars",goldPatternColor:null,goldHitPatternName:"Stars",goldHitPatternColor:null,goldEmptyTextureUrl:null,goldFilledTextureUrl:null,fontFamily:null,fontSize:18,fontColor:null,fontOutlineColor:null,fontOutlineWidth:0,fontShadow:null},Ps="nice2dev-player-bar-style",As="nice2dev-player-karaoke-settings";function fn(e){return e!=null?`${As}-${e}`:As}function qn(e){return e!=null?`${Ps}-${e}`:Ps}function Es(e){return{filledBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.filledTextureUrl,textureScale:e.textureScale},emptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.patternName,patternColor:e.patternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:e.emptyGlass,textureUrl:e.emptyTextureUrl,textureScale:e.textureScale},goldFilledBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldHitPatternName,patternColor:e.goldHitPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldFilledTextureUrl,textureScale:e.textureScale},goldEmptyBar:{color:null,capStyleName:e.capStyleName,patternName:e.goldPatternName,patternColor:e.goldPatternColor,patternOnly:e.patternOnly,highlight:e.highlight,glow:e.glow,glass:0,textureUrl:e.goldEmptyTextureUrl,textureScale:e.textureScale},font:{fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,outlineColor:e.fontOutlineColor,outlineWidth:e.fontOutlineWidth,shadow:e.fontShadow}}}function Is(e){const t=oo,r=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i},a=(s,i)=>!i||typeof i!="object"?{...s}:{...s,...i};return{filledBar:r(t.filledBar,e.filledBar),emptyBar:r(t.emptyBar,e.emptyBar),goldFilledBar:r(t.goldFilledBar,e.goldFilledBar),goldEmptyBar:r(t.goldEmptyBar,e.goldEmptyBar),font:a(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function Va(e){try{const t=localStorage.getItem(fn(e));if(t){const a=JSON.parse(t);return Is(a)}const r=localStorage.getItem(qn(e));if(r){const a=JSON.parse(r),s=Es({...pn,...a});return localStorage.setItem(fn(e),JSON.stringify(s)),s}if(e!=null){const a=localStorage.getItem(fn());if(a)return Is(JSON.parse(a));const s=localStorage.getItem(qn());if(s)return Es({...pn,...JSON.parse(s)})}}catch{}return{filledBar:{...Kt},emptyBar:{..._r},goldFilledBar:{...Or},goldEmptyBar:{...Fr},font:{...Br}}}function zu(e,t){const r=JSON.stringify(e);localStorage.setItem(fn(t),r)}let Ls=!1;async function _u(e){if(Ls||(Ls=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(fn())||localStorage.setItem(fn(),t)}catch{}}function Fu(e){const t=new Map;for(const r of e)t.set(r,Va(r));return t}function lo(e){try{const t=localStorage.getItem(qn(e));if(t)return{...pn,...JSON.parse(t)};if(e!=null){const r=localStorage.getItem(qn());if(r)return{...pn,...JSON.parse(r)}}}catch{}return{...pn}}function Ou(e,t){localStorage.setItem(qn(t),JSON.stringify(e))}function Bu(e){const t=new Map;for(const r of e)t.set(r,lo(r));return t}const Gu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Wu=/[&<>"']/g;function Uu(e){return e.replace(Wu,t=>Gu[t])}function qu(e){const t=e.trim().toLowerCase();return!!(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:image/")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))}const Vu=3,Qe=Vu;function Pr(e){const t=parseInt(e.slice(1,3),16)/255,r=parseInt(e.slice(3,5),16)/255,a=parseInt(e.slice(5,7),16)/255,s=Math.max(t,r,a),i=Math.min(t,r,a);let o=0,l=0;const c=(s+i)/2;if(s!==i){const d=s-i;switch(l=c>.5?d/(2-s-i):d/(s+i),s){case t:o=((r-a)/d+(r<a?6:0))/6;break;case r:o=((a-t)/d+2)/6;break;case a:o=((t-r)/d+4)/6;break}}return[Math.round(o*360),Math.round(l*100),Math.round(c*100)]}function Ar(e){let t=e.replace("#","");return t.length===3&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]),"#"+t.toLowerCase()}function ut(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
2
2
  $1`).split(`
3
- `).filter(Boolean).map(n=>{const a=n[0],s=n.slice(1).trim().split(/[\s,]+/).map(Number);if(a==="H")return`H${s[0]+t}`;if(a==="V"||a==="Z")return n;if("MLCSQT".includes(a.toUpperCase())){for(let i=0;i<s.length;i+=2)s[i]+=t;return a+s.join(" ")}return a==="A"&&s.length>=7?(s[5]+=t,a+s.join(" ")):n}).join("")}function co(e){const{width:t,height:n,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:u=null,patternOnly:h=!1,textureUrl:p=null,textureScale:f=1}=e,y=p&&Gu(p)?Bu(p):null,[m,v,x]=Tr($r(s)),g="c"+Math.random().toString(36).slice(2,7),k=a.L(n),b=a.R(n),S=t-k.w-b.w;if(S<4)return"";if(h&&c){const X=`hsl(${m},${v}%,${x}%)`,ie=`hsl(${m},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,le=u||ie,te=k.w,V=k.w+S,K=k.inn,oe=`M${te} ${Xe}H${V}V${n-Xe}H${te}Z`,ne=dt(b.inn,V),he=k.out,J=`M${te} 0H${V}V${n}H${te}Z`,de=dt(b.out,V),me=c.mk(g+"pat",le,u||void 0),xe=Math.round(256*f),ce=Math.round(256*f),ye=y?`<pattern id="${g}tex" patternUnits="userSpaceOnUse" width="${xe}" height="${ce}"><image href="${y}" width="${xe}" height="${ce}" preserveAspectRatio="none"/></pattern>`:"",Se=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${g}tex)" opacity=".85" clip-path="url(#${g}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
3
+ `).filter(Boolean).map(r=>{const a=r[0],s=r.slice(1).trim().split(/[\s,]+/).map(Number);if(a==="H")return`H${s[0]+t}`;if(a==="V"||a==="Z")return r;if("MLCSQT".includes(a.toUpperCase())){for(let i=0;i<s.length;i+=2)s[i]+=t;return a+s.join(" ")}return a==="A"&&s.length>=7?(s[5]+=t,a+s.join(" ")):r}).join("")}function co(e){const{width:t,height:r,capStyle:a,color:s,highlight:i=70,glow:o=55,glass:l=0,pattern:c=null,patternColor:d=null,patternOnly:h=!1,textureUrl:f=null,textureScale:p=1}=e,y=f&&qu(f)?Uu(f):null,[m,x,v]=Pr(Ar(s)),g="c"+Math.random().toString(36).slice(2,7),S=a.L(r),b=a.R(r),k=t-S.w-b.w;if(k<4)return"";if(h&&c){const X=`hsl(${m},${x}%,${v}%)`,oe=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(v+30,95)}%)`,le=d||oe,ne=S.w,Z=S.w+k,Y=S.inn,se=`M${ne} ${Qe}H${Z}V${r-Qe}H${ne}Z`,ae=ut(b.inn,Z),ue=S.out,J=`M${ne} 0H${Z}V${r}H${ne}Z`,de=ut(b.out,Z),me=c.mk(g+"pat",le,d||void 0),ve=Math.round(256*p),ce=Math.round(256*p),ye=y?`<pattern id="${g}tex" patternUnits="userSpaceOnUse" width="${ve}" height="${ce}"><image href="${y}" width="${ve}" height="${ce}" preserveAspectRatio="none"/></pattern>`:"",ke=y?`<rect x="0" y="0" width="${t}" height="${r}" fill="url(#${g}tex)" opacity=".85" clip-path="url(#${g}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}" viewBox="0 0 ${t} ${r}"><defs>
4
4
  ${me}
5
5
  ${ye}
6
- <clipPath id="${g}c"><path d="${K}"/><path d="${oe}"/><path d="${ne}"/></clipPath>
6
+ <clipPath id="${g}c"><path d="${Y}"/><path d="${se}"/><path d="${ae}"/></clipPath>
7
7
  </defs>
8
- <path d="${he}" fill="rgba(255,255,255,.18)"/><path d="${J}" fill="rgba(255,255,255,.18)"/><path d="${de}" fill="rgba(255,255,255,.18)"/>
9
- <path d="${K}" fill="${X}" opacity=".22"/><path d="${oe}" fill="${X}" opacity=".22"/><path d="${ne}" fill="${X}" opacity=".22"/>
10
- ${Se}
11
- <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${g}pat)" clip-path="url(#${g}c)"/>
12
- </svg>`}const M=`hsl(${m},${Math.min(v+10,100)}%,${Math.max(x-22,4)}%)`,R=`hsl(${m},${v}%,${x}%)`,N=`hsl(${m},${Math.max(v-12,0)}%,${Math.min(x+18,88)}%)`,C=`hsl(${m},${Math.min(v+20,100)}%,${Math.min(x+30,93)}%)`,w=`hsl(${m},${Math.max(v-20,0)}%,${Math.min(x+30,95)}%)`,O=u||w,$=i/100*.78,E=o/100*.65,_=1-l/100*.87,L=Xe,U=n-Xe,Z=L+(U-L)*.44,A=L+(U-L)*.58,q=k.w,H=k.w+S,re=k.out,D=`M${q} 0H${H}V${n}H${q}Z`,W=dt(b.out,H),j=k.inn,F=`M${q} ${Xe}H${H}V${n-Xe}H${q}Z`,I=dt(b.inn,H),P=c?c.mk(g+"pat",O,u||void 0):"",T=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${g}pat)" clip-path="url(#${g}c)"/>`:"",z=Math.round(256*f),B=Math.round(256*f),G=y?`<pattern id="${g}tex" patternUnits="userSpaceOnUse" width="${z}" height="${B}"><image href="${y}" width="${z}" height="${B}" preserveAspectRatio="none"/></pattern>`:"",Y=y?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${g}tex)" opacity="${_*.9}" clip-path="url(#${g}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
13
- ${P}
8
+ <path d="${ue}" fill="rgba(255,255,255,.18)"/><path d="${J}" fill="rgba(255,255,255,.18)"/><path d="${de}" fill="rgba(255,255,255,.18)"/>
9
+ <path d="${Y}" fill="${X}" opacity=".22"/><path d="${se}" fill="${X}" opacity=".22"/><path d="${ae}" fill="${X}" opacity=".22"/>
10
+ ${ke}
11
+ <rect x="0" y="0" width="${t}" height="${r}" fill="url(#${g}pat)" clip-path="url(#${g}c)"/>
12
+ </svg>`}const j=`hsl(${m},${Math.min(x+10,100)}%,${Math.max(v-22,4)}%)`,N=`hsl(${m},${x}%,${v}%)`,R=`hsl(${m},${Math.max(x-12,0)}%,${Math.min(v+18,88)}%)`,w=`hsl(${m},${Math.min(x+20,100)}%,${Math.min(v+30,93)}%)`,M=`hsl(${m},${Math.max(x-20,0)}%,${Math.min(v+30,95)}%)`,I=d||M,A=i/100*.78,T=o/100*.65,O=1-l/100*.87,E=Qe,V=r-Qe,ee=E+(V-E)*.44,z=E+(V-E)*.58,q=S.w,K=S.w+k,re=S.out,_=`M${q} 0H${K}V${r}H${q}Z`,U=ut(b.out,K),$=S.inn,P=`M${q} ${Qe}H${K}V${r-Qe}H${q}Z`,F=ut(b.inn,K),D=c?c.mk(g+"pat",I,d||void 0):"",C=c?`<rect x="0" y="0" width="${t}" height="${r}" fill="url(#${g}pat)" clip-path="url(#${g}c)"/>`:"",L=Math.round(256*p),B=Math.round(256*p),G=y?`<pattern id="${g}tex" patternUnits="userSpaceOnUse" width="${L}" height="${B}"><image href="${y}" width="${L}" height="${B}" preserveAspectRatio="none"/></pattern>`:"",H=y?`<rect x="0" y="0" width="${t}" height="${r}" fill="url(#${g}tex)" opacity="${O*.9}" clip-path="url(#${g}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}" viewBox="0 0 ${t} ${r}"><defs>
13
+ ${D}
14
14
  ${G}
15
- <linearGradient id="${g}b" x1="0" y1="0" x2="0" y2="${n}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
16
- <linearGradient id="${g}f" x1="0" y1="${L}" x2="0" y2="${U}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${N}"/><stop offset=".5" stop-color="${R}"/><stop offset="1" stop-color="${M}"/></linearGradient>
17
- <linearGradient id="${g}h" x1="0" y1="${L}" x2="0" y2="${Z}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="var(--nice-bg, #fff)" stop-opacity="${$}"/><stop offset=".5" stop-color="var(--nice-bg, #fff)" stop-opacity="${$*.25}"/><stop offset="1" stop-color="var(--nice-bg, #fff)" stop-opacity="0"/></linearGradient>
18
- <linearGradient id="${g}g" x1="0" y1="${A}" x2="0" y2="${U}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${C}" stop-opacity="0"/><stop offset=".6" stop-color="${C}" stop-opacity="${E*.6}"/><stop offset="1" stop-color="${C}" stop-opacity="${E}"/></linearGradient>
19
- <clipPath id="${g}c"><path d="${j}"/><path d="${F}"/><path d="${I}"/></clipPath>
15
+ <linearGradient id="${g}b" x1="0" y1="0" x2="0" y2="${r}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="rgba(255,255,255,.55)"/><stop offset=".3" stop-color="rgba(255,255,255,.35)"/><stop offset="1" stop-color="rgba(255,255,255,.08)"/></linearGradient>
16
+ <linearGradient id="${g}f" x1="0" y1="${E}" x2="0" y2="${V}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${R}"/><stop offset=".5" stop-color="${N}"/><stop offset="1" stop-color="${j}"/></linearGradient>
17
+ <linearGradient id="${g}h" x1="0" y1="${E}" x2="0" y2="${ee}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${A}"/><stop offset=".5" stop-color="#fff" stop-opacity="${A*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
18
+ <linearGradient id="${g}g" x1="0" y1="${z}" x2="0" y2="${V}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${w}" stop-opacity="0"/><stop offset=".6" stop-color="${w}" stop-opacity="${T*.6}"/><stop offset="1" stop-color="${w}" stop-opacity="${T}"/></linearGradient>
19
+ <clipPath id="${g}c"><path d="${$}"/><path d="${P}"/><path d="${F}"/></clipPath>
20
20
  </defs>
21
- <path d="${re}" fill="url(#${g}b)"/><path d="${D}" fill="url(#${g}b)"/><path d="${W}" fill="url(#${g}b)"/>
22
- <path d="${j}" fill="url(#${g}f)" opacity="${_}"/><path d="${F}" fill="url(#${g}f)" opacity="${_}"/><path d="${I}" fill="url(#${g}f)" opacity="${_}"/>
23
- ${Y}
24
- ${T}
25
- <rect x="0" y="${A}" width="${t}" height="${U-A}" fill="url(#${g}g)" clip-path="url(#${g}c)"/>
26
- <rect x="0" y="${L}" width="${t}" height="${Z-L}" fill="url(#${g}h)" clip-path="url(#${g}c)"/>
27
- </svg>`}function tt(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let a=0,s=0;for(const i of n){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),u=Math.abs(l[1]),h=l[3]!==0,p=l[4]!==0,f=l[5],y=l[6],m=a,v=s;if(Math.abs(m-f)<.001&&Math.abs(v-y)<.001||c<.001||u<.001){e.lineTo(f,y),a=f,s=y;break}const x=(c+u)/2,g=(m-f)/2,k=(v-y)/2,b=g*g+k*k,S=b>x*x?Math.sqrt(b):x,M=S*S,R=Math.sqrt(Math.max(0,(M-b)/b)),N=h!==p?1:-1,C=(m+f)/2+N*R*k,w=(v+y)/2-N*R*g,O=Math.atan2(v-w,m-C),$=Math.atan2(y-w,f-C);e.arc(C,w,S,O,$,!p),a=f,s=y;break}case"Z":e.closePath();break}}}function Rn(e,t,n,a,s,i,o,l=70,c=55,u=0,h,p,f=!1,y,m){const[v,x,g]=Tr($r(o)),k=i.L(s),b=i.R(s),S=a-k.w-b.w;if(S<0){const[j,,F]=Tr($r(o));e.save(),e.translate(t,n),e.globalAlpha=1-u/100*.87,e.fillStyle=`hsl(${j},50%,${Math.min(F+10,80)}%)`;const I=Math.min(a/2,s/2);e.beginPath(),e.moveTo(I,0),e.lineTo(a-I,0),e.quadraticCurveTo(a,0,a,I),e.lineTo(a,s-I),e.quadraticCurveTo(a,s,a-I,s),e.lineTo(I,s),e.quadraticCurveTo(0,s,0,s-I),e.lineTo(0,I),e.quadraticCurveTo(0,0,I,0),e.closePath(),e.fill(),e.restore();return}const M=k.w,R=k.w+S;if(f){const j=`hsla(${v},${x}%,${g}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),tt(e,k.out),e.fill(),e.fillRect(M,0,S,s),e.beginPath(),tt(e,dt(b.out,R)),e.fill(),e.fillStyle=j,e.beginPath(),tt(e,k.inn),e.fill(),e.fillRect(M,Xe,S,s-2*Xe),e.beginPath(),tt(e,dt(b.inn,R)),e.fill(),y&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,S,s-2*Xe),tt(e,dt(b.inn,R)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,S,s-2*Xe),tt(e,dt(b.inn,R)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.restore();return}const N=`hsl(${v},${Math.min(x+10,100)}%,${Math.max(g-22,4)}%)`,C=`hsl(${v},${x}%,${g}%)`,w=`hsl(${v},${Math.max(x-12,0)}%,${Math.min(g+18,88)}%)`,O=`hsl(${v},${Math.min(x+20,100)}%,${Math.min(g+30,93)}%)`,$=l/100*.78,E=c/100*.65,_=1-u/100*.87,L=Xe,U=s-Xe,Z=U-L,A=L+Z*.44,q=L+Z*.58;e.save(),e.translate(t,n);const H=e.createLinearGradient(0,0,0,s);H.addColorStop(0,"rgba(255,255,255,0.55)"),H.addColorStop(.3,"rgba(255,255,255,0.35)"),H.addColorStop(1,"rgba(255, 255, 255, 0.08)"),e.fillStyle=H,e.beginPath(),tt(e,k.out),e.fill(),e.fillRect(M,0,S,s),e.beginPath(),tt(e,dt(b.out,R)),e.fill();const re=e.createLinearGradient(0,L,0,U);re.addColorStop(0,w),re.addColorStop(.5,C),re.addColorStop(1,N),e.globalAlpha=_,e.fillStyle=re,e.beginPath(),tt(e,k.inn),e.fill(),e.fillRect(M,Xe,S,s-2*Xe),e.beginPath(),tt(e,dt(b.inn,R)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,S,s-2*Xe),tt(e,dt(b.inn,R)),e.clip(),e.globalAlpha=_*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,S,s-2*Xe),tt(e,dt(b.inn,R)),e.clip(),e.globalAlpha=_*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),tt(e,k.inn),e.rect(M,Xe,S,s-2*Xe),tt(e,dt(b.inn,R)),e.clip();const D=e.createLinearGradient(0,q,0,U);D.addColorStop(0,"transparent"),D.addColorStop(.6,O.replace(")",`, ${E*.6})`).replace("hsl","hsla")),D.addColorStop(1,O.replace(")",`, ${E})`).replace("hsl","hsla")),e.fillStyle=D,e.fillRect(0,q,a,U-q);const W=e.createLinearGradient(0,L,0,A);W.addColorStop(0,`rgba(255,255,255,${$})`),W.addColorStop(.5,`rgba(255,255,255,${$*.25})`),W.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=W,e.fillRect(0,L,a,A-L),e.restore(),e.restore()}function Uu(e){const{ctx:t,ballX:n,height:a,playerColor:s,currentTime:i}=e;t.save(),t.globalCompositeOperation="source-over";const o=t.createLinearGradient(Math.max(0,n-60),0,n,0);o.addColorStop(0,"transparent"),o.addColorStop(1,s),t.globalAlpha=.18,t.fillStyle=o,t.fillRect(Math.max(0,n-60),0,60,a),t.globalAlpha=.9,t.strokeStyle=s,t.lineWidth=3,t.shadowColor=s,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,a),t.stroke();const l=6+Math.sin(i*6)*2;t.fillStyle=e.ballIsGold?"var(--nice-warning, #FFD700)":s,t.beginPath(),t.moveTo(n,e.ballY-l),t.lineTo(n+l*.7,e.ballY),t.lineTo(n,e.ballY+l),t.lineTo(n-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?"var(--nice-warning, #FFD700)":s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function qu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,u=s*1.5,h=l*4;t.save();for(let f=0;f<c;f++){const y=(h+f*2.1)%(Math.PI*2),m=Math.sin(y)*.5+.5,v=u+m*s*3,x=(1-m)*.5;t.globalAlpha=x,t.strokeStyle=o?"var(--nice-warning, #FFD700)":i,t.lineWidth=2-m,t.beginPath(),t.arc(n,a,v,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=o?"var(--nice-warning, #FFD700)":i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?"var(--nice-warning-bg, #fff0a8)":i;const p=s*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,a,p,0,Math.PI*2),t.fill();for(const f of e.visibleNotes){if(!f.isSung)continue;const y=(l*6+f.x*.01)%(Math.PI*2),m=.15+Math.sin(y)*.1;t.globalAlpha=m,t.fillStyle=f.isGold?"var(--nice-warning, #FFD700)":i,t.fillRect(f.x,f.y,f.w,f.h)}t.restore()}function Vu(e){const{ctx:t,ballX:n,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,u=l*5%(Math.PI*2),h=-Math.abs(Math.sin(u))*c,p=a+h;t.save(),t.globalAlpha=.3,t.fillStyle="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))";const f=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(n,a+s*.5,s*f*1.5,s*.3*f,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const y=5;for(let x=0;x<y;x++){const g=(x+1)*.04,k=(l-g)*5%(Math.PI*2),b=a+-Math.abs(Math.sin(k))*c,S=.15*(1-x/y),M=s*(.6-x*.08);t.globalAlpha=S,t.fillStyle=i,t.beginPath(),t.arc(n-x*3,b,Math.max(2,M),0,Math.PI*2),t.fill()}t.restore(),t.save();const m=1+Math.abs(Math.sin(u))*.15,v=1/m;if(t.translate(n,p),t.scale(v,m),t.shadowColor=o?"var(--nice-warning, #FFD700)":i,t.shadowBlur=12,t.fillStyle=o?"var(--nice-warning-bg, #fff0a8)":i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle="var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.stroke(),t.restore(),Math.abs(Math.sin(u))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=o?"var(--nice-warning, #FFD700)":i;for(let x=0;x<4;x++){const g=x/4*Math.PI*2+l,k=n+Math.cos(g)*(s+4),b=a+Math.sin(g)*2;t.beginPath(),t.arc(k,b,2,0,Math.PI*2),t.fill()}t.restore()}}function Hu(e,t){switch(e){case"wipe":return Uu(t),!0;case"pulse":return qu(t),!0;case"bounce":return Vu(t),!0;case"ball":default:return!1}}const Ku=1e3,Yu=20,Zu=70,Xu=5,Is=26,Ls="rgba(255,215,70,0.98)",Ds=new Map,Qu=(e,t,n,a,s)=>{const i=`g${s}`,o=`<?xml version="1.0" encoding="UTF-8"?>
21
+ <path d="${re}" fill="url(#${g}b)"/><path d="${_}" fill="url(#${g}b)"/><path d="${U}" fill="url(#${g}b)"/>
22
+ <path d="${$}" fill="url(#${g}f)" opacity="${O}"/><path d="${P}" fill="url(#${g}f)" opacity="${O}"/><path d="${F}" fill="url(#${g}f)" opacity="${O}"/>
23
+ ${H}
24
+ ${C}
25
+ <rect x="0" y="${z}" width="${t}" height="${V-z}" fill="url(#${g}g)" clip-path="url(#${g}c)"/>
26
+ <rect x="0" y="${E}" width="${t}" height="${ee-E}" fill="url(#${g}h)" clip-path="url(#${g}c)"/>
27
+ </svg>`}function nt(e,t){const r=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!r)return;let a=0,s=0;for(const i of r){const o=i[0],l=i.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(o){case"M":a=l[0],s=l[1],e.moveTo(a,s);break;case"L":a=l[0],s=l[1],e.lineTo(a,s);break;case"H":a=l[0],e.lineTo(a,s);break;case"V":s=l[0],e.lineTo(a,s);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),a=l[4],s=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break;case"S":{e.bezierCurveTo(a,s,l[0],l[1],l[2],l[3]),a=l[2],s=l[3];break}case"A":{const c=Math.abs(l[0]),d=Math.abs(l[1]),h=l[3]!==0,f=l[4]!==0,p=l[5],y=l[6],m=a,x=s;if(Math.abs(m-p)<.001&&Math.abs(x-y)<.001||c<.001||d<.001){e.lineTo(p,y),a=p,s=y;break}const v=(c+d)/2,g=(m-p)/2,S=(x-y)/2,b=g*g+S*S,k=b>v*v?Math.sqrt(b):v,j=k*k,N=Math.sqrt(Math.max(0,(j-b)/b)),R=h!==f?1:-1,w=(m+p)/2+R*N*S,M=(x+y)/2-R*N*g,I=Math.atan2(x-M,m-w),A=Math.atan2(y-M,p-w);e.arc(w,M,k,I,A,!f),a=p,s=y;break}case"Z":e.closePath();break}}}function Tn(e,t,r,a,s,i,o,l=70,c=55,d=0,h,f,p=!1,y,m){const[x,v,g]=Pr(Ar(o)),S=i.L(s),b=i.R(s),k=a-S.w-b.w;if(k<0){const[$,,P]=Pr(Ar(o));e.save(),e.translate(t,r),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${$},50%,${Math.min(P+10,80)}%)`;const F=Math.min(a/2,s/2);e.beginPath(),e.moveTo(F,0),e.lineTo(a-F,0),e.quadraticCurveTo(a,0,a,F),e.lineTo(a,s-F),e.quadraticCurveTo(a,s,a-F,s),e.lineTo(F,s),e.quadraticCurveTo(0,s,0,s-F),e.lineTo(0,F),e.quadraticCurveTo(0,0,F,0),e.closePath(),e.fill(),e.restore();return}const j=S.w,N=S.w+k;if(p){const $=`hsla(${x},${v}%,${g}%,0.22)`;e.save(),e.translate(t,r),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),nt(e,S.out),e.fill(),e.fillRect(j,0,k,s),e.beginPath(),nt(e,ut(b.out,N)),e.fill(),e.fillStyle=$,e.beginPath(),nt(e,S.inn),e.fill(),e.fillRect(j,Qe,k,s-2*Qe),e.beginPath(),nt(e,ut(b.inn,N)),e.fill(),y&&(e.save(),e.beginPath(),nt(e,S.inn),e.rect(j,Qe,k,s-2*Qe),nt(e,ut(b.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),nt(e,S.inn),e.rect(j,Qe,k,s-2*Qe),nt(e,ut(b.inn,N)),e.clip(),e.globalAlpha=.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.restore();return}const R=`hsl(${x},${Math.min(v+10,100)}%,${Math.max(g-22,4)}%)`,w=`hsl(${x},${v}%,${g}%)`,M=`hsl(${x},${Math.max(v-12,0)}%,${Math.min(g+18,88)}%)`,I=`hsl(${x},${Math.min(v+20,100)}%,${Math.min(g+30,93)}%)`,A=l/100*.78,T=c/100*.65,O=1-d/100*.87,E=Qe,V=s-Qe,ee=V-E,z=E+ee*.44,q=E+ee*.58;e.save(),e.translate(t,r);const K=e.createLinearGradient(0,0,0,s);K.addColorStop(0,"rgba(255,255,255,0.55)"),K.addColorStop(.3,"rgba(255,255,255,0.35)"),K.addColorStop(1,"rgba(255, 255, 255, 0.08)"),e.fillStyle=K,e.beginPath(),nt(e,S.out),e.fill(),e.fillRect(j,0,k,s),e.beginPath(),nt(e,ut(b.out,N)),e.fill();const re=e.createLinearGradient(0,E,0,V);re.addColorStop(0,M),re.addColorStop(.5,w),re.addColorStop(1,R),e.globalAlpha=O,e.fillStyle=re,e.beginPath(),nt(e,S.inn),e.fill(),e.fillRect(j,Qe,k,s-2*Qe),e.beginPath(),nt(e,ut(b.inn,N)),e.fill(),e.globalAlpha=1,y&&(e.save(),e.beginPath(),nt(e,S.inn),e.rect(j,Qe,k,s-2*Qe),nt(e,ut(b.inn,N)),e.clip(),e.globalAlpha=O*.9,e.fillStyle=y,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),m&&(e.save(),e.beginPath(),nt(e,S.inn),e.rect(j,Qe,k,s-2*Qe),nt(e,ut(b.inn,N)),e.clip(),e.globalAlpha=O*.85,e.fillStyle=m,e.fillRect(0,0,a,s),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),nt(e,S.inn),e.rect(j,Qe,k,s-2*Qe),nt(e,ut(b.inn,N)),e.clip();const _=e.createLinearGradient(0,q,0,V);_.addColorStop(0,"transparent"),_.addColorStop(.6,I.replace(")",`, ${T*.6})`).replace("hsl","hsla")),_.addColorStop(1,I.replace(")",`, ${T})`).replace("hsl","hsla")),e.fillStyle=_,e.fillRect(0,q,a,V-q);const U=e.createLinearGradient(0,E,0,z);U.addColorStop(0,`rgba(255,255,255,${A})`),U.addColorStop(.5,`rgba(255,255,255,${A*.25})`),U.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=U,e.fillRect(0,E,a,z-E),e.restore(),e.restore()}const Vt="var(--nice-warning, #FFD700)",uo="var(--nice-warning-bg, #fff0a8)";function Hu(e){const{ctx:t,ballX:r,height:a,playerColor:s,currentTime:i}=e;t.save(),t.globalCompositeOperation="source-over";const o=t.createLinearGradient(Math.max(0,r-60),0,r,0);o.addColorStop(0,"transparent"),o.addColorStop(1,s),t.globalAlpha=.18,t.fillStyle=o,t.fillRect(Math.max(0,r-60),0,60,a),t.globalAlpha=.9,t.strokeStyle=s,t.lineWidth=3,t.shadowColor=s,t.shadowBlur=12,t.beginPath(),t.moveTo(r,0),t.lineTo(r,a),t.stroke();const l=6+Math.sin(i*6)*2;t.fillStyle=e.ballIsGold?Se.resolveCssColor(Vt,t.canvas):s,t.beginPath(),t.moveTo(r,e.ballY-l),t.lineTo(r+l*.7,e.ballY),t.lineTo(r,e.ballY+l),t.lineTo(r-l*.7,e.ballY),t.closePath(),t.fill(),t.restore(),t.save(),t.globalCompositeOperation="source-atop",t.globalAlpha=.35;for(const c of e.visibleNotes)c.isSung&&(t.fillStyle=c.isGold?Se.resolveCssColor(Vt,t.canvas):s,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Ku(e){const{ctx:t,ballX:r,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=3,d=s*1.5,h=l*4;t.save();for(let p=0;p<c;p++){const y=(h+p*2.1)%(Math.PI*2),m=Math.sin(y)*.5+.5,x=d+m*s*3,v=(1-m)*.5;t.globalAlpha=v,t.strokeStyle=o?Se.resolveCssColor(Vt,t.canvas):i,t.lineWidth=2-m,t.beginPath(),t.arc(r,a,x,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=o?Se.resolveCssColor(Vt,t.canvas):i,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=o?Se.resolveCssColor(uo,t.canvas):i;const f=s*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(r,a,f,0,Math.PI*2),t.fill();for(const p of e.visibleNotes){if(!p.isSung)continue;const y=(l*6+p.x*.01)%(Math.PI*2),m=.15+Math.sin(y)*.1;t.globalAlpha=m,t.fillStyle=p.isGold?Se.resolveCssColor(Vt,t.canvas):i,t.fillRect(p.x,p.y,p.w,p.h)}t.restore()}function Yu(e){const{ctx:t,ballX:r,ballY:a,ballRadius:s,playerColor:i,ballIsGold:o,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,d=l*5%(Math.PI*2),h=-Math.abs(Math.sin(d))*c,f=a+h;t.save(),t.globalAlpha=.3,t.fillStyle=Se.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",t.canvas);const p=1-Math.abs(h)/(c+20);t.beginPath(),t.ellipse(r,a+s*.5,s*p*1.5,s*.3*p,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const y=5;for(let v=0;v<y;v++){const g=(v+1)*.04,S=(l-g)*5%(Math.PI*2),b=a+-Math.abs(Math.sin(S))*c,k=.15*(1-v/y),j=s*(.6-v*.08);t.globalAlpha=k,t.fillStyle=i,t.beginPath(),t.arc(r-v*3,b,Math.max(2,j),0,Math.PI*2),t.fill()}t.restore(),t.save();const m=1+Math.abs(Math.sin(d))*.15,x=1/m;if(t.translate(r,f),t.scale(x,m),t.shadowColor=o?Se.resolveCssColor(Vt,t.canvas):i,t.shadowBlur=12,t.fillStyle=o?Se.resolveCssColor(uo,t.canvas):i,t.beginPath(),t.arc(0,0,s,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle=Se.resolveCssColor("var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",t.canvas),t.stroke(),t.restore(),Math.abs(Math.sin(d))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=o?Se.resolveCssColor(Vt,t.canvas):i;for(let v=0;v<4;v++){const g=v/4*Math.PI*2+l,S=r+Math.cos(g)*(s+4),b=a+Math.sin(g)*2;t.beginPath(),t.arc(S,b,2,0,Math.PI*2),t.fill()}t.restore()}}function Xu(e,t){switch(e){case"wipe":return Hu(t),!0;case"pulse":return Ku(t),!0;case"bounce":return Yu(t),!0;case"ball":default:return!1}}const Zu=1e3,Qu=20,Ju=70,eh=5,Ds=26,zs="rgba(255,215,70,0.98)",_s=new Map,th=(e,t,r,a,s)=>{const i=`g${s}`,o=`<?xml version="1.0" encoding="UTF-8"?>
28
28
  <svg xmlns='http://www.w3.org/2000/svg' width='${a}' height='${a}' viewBox='0 0 ${a} ${a}'>
29
29
  <defs>
30
30
  <radialGradient id='g${i}' cx='50%' cy='40%' r='60%'>
31
- <stop offset='0%' stop-color='hsl(${e} ${t}% ${n}%)' stop-opacity='1'/>
32
- <stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,n+10)}%)' stop-opacity='0.9'/>
31
+ <stop offset='0%' stop-color='hsl(${e} ${t}% ${r}%)' stop-opacity='1'/>
32
+ <stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,r+10)}%)' stop-opacity='0.9'/>
33
33
  <stop offset='100%' stop-color='transparent' stop-opacity='0'/>
34
34
  </radialGradient>
35
35
  </defs>
36
36
  <g transform='translate(${a/2}, ${a/2})'>
37
37
  <circle cx='0' cy='0' r='${a*.45}' fill='url(#g${i})' />
38
38
  </g>
39
- </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},Ju=(e,t,n,a,s)=>{const i=`${e}-${t}-${n}-${Math.round(a)}-${s}`;let o=Ds.get(i);return o||(o=new Image,o.src=Qu(e,t,n,a,s),Ds.set(i,o),o)},eh=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(n,a,s),o=Math.min(n,a,s);let l=0,c=0;const u=(i+o)/2;if(i!==o){const h=i-o;switch(c=u>.5?h/(2-i-o):h/(i+o),i){case n:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-n)/h+2;break;case s:l=(n-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(u*100)}},th=(e,t,n,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${a})`;function Xn(e){try{const t=la(e),[n,a,s]=Au(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(n)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function nh(e,t,n,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+a-o,n),e.quadraticCurveTo(t+a,n,t+a,n+o),e.lineTo(t+a,n+s-o),e.quadraticCurveTo(t+a,n+s,t+a-o,n+s),e.lineTo(t+o,n+s),e.quadraticCurveTo(t,n+s,t,n+s-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}const an=new Map,Nn=new Set,hr=new Set;function qa(e){const t=an.get(e);return t?Promise.resolve(t):hr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):Nn.has(e)?new Promise((n,a)=>{const s=()=>{an.has(e)?n(an.get(e)):hr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):(Nn.add(e),new Promise((n,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{an.set(e,s),Nn.delete(e),n(s)},s.onerror=()=>{Nn.delete(e),hr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function rh(e){return an.get(e)??null}function Tn(e,t,n=1){const a=an.get(t);if(!a)return!Nn.has(t)&&!hr.has(t)&&qa(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(n!==1){const i=new DOMMatrix;i.scaleSelf(n,n),s.setTransform(i)}return s}function ah(e){for(const t of e)t&&qa(t).catch(()=>{})}const $n=new Map,tn=new Set;function uo(e,t,n){return`${e}|${t}|${n??""}`}function sh(e,t,n){const a=uo(e.name,t,n),s=$n.get(a);if(s)return Promise.resolve(s);if(tn.has(a))return new Promise((m,v)=>{const x=()=>{$n.has(a)?m($n.get(a)):tn.has(a)?requestAnimationFrame(x):v(new Error(`Pattern render failed: ${a}`))};x()});tn.add(a);const i="p",o=e.mk(i,t,n??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),u=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${u}" height="${h}"><defs>${o}</defs><rect width="${u}" height="${h}" fill="url(#${i})"/></svg>`,f=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(f);return new Promise((m,v)=>{const x=new Image;x.onload=()=>{$n.set(a,x),tn.delete(a),URL.revokeObjectURL(y),m(x)},x.onerror=()=>{tn.delete(a),URL.revokeObjectURL(y),v(new Error(`Failed to render pattern tile: ${e.name}`))},x.src=y})}function Pn(e,t,n,a){const s=uo(t.name,n,a),i=$n.get(s);return i?e.createPattern(i,"repeat"):(tn.has(s)||sh(t,n,a).catch(()=>{}),null)}let Mt=null,at=null,ft=null,It=null,St=null,qe=null,_s="",Fs=0,zs="";const ua=(e,t,n,a,s,i,o,l,c,u,h,p,f,y,m,v,x,g,k,b,S,M,R,N)=>{e.clearRect(0,0,t,n);const C=N??null,w=(C==null?void 0:C.filledBar)??Vt,O=(C==null?void 0:C.emptyBar)??Lr,$=(C==null?void 0:C.goldFilledBar)??_r,E=(C==null?void 0:C.goldEmptyBar)??Dr,_=(C==null?void 0:C.font)??Fr,L=Cn(w.capStyleName),U=Cn(O.capStyleName),Z=Cn($.capStyleName),A=Cn(E.capStyleName),q=w.patternName?Mn(w.patternName):null,H=O.patternName?Mn(O.patternName):null,re=$.patternName?Mn($.patternName):null,D=E.patternName?Mn(E.patternName):null,W=q?Pn(e,q,w.patternColor??w.color??"var(--nice-bg, #fff)",w.patternColor):null,j=H?Pn(e,H,O.patternColor??O.color??"var(--nice-border, #d1d5db)",O.patternColor):null,F=re?Pn(e,re,$.patternColor??"var(--nice-warning, #FFD700)",$.patternColor):null,I=D?Pn(e,D,E.patternColor??"var(--nice-warning, #FFD700)",E.patternColor):null;zs!==i&&(zs=i,oa("RENDER",`?? Renderer using settings for "${i}" � filled: cap=${w.capStyleName}, glass=${w.glass} | empty: cap=${O.capStyleName}, glass=${O.glass} | goldFilled: cap=${$.capStyleName}, pattern=${$.patternName??"none"} | goldEmpty: cap=${E.capStyleName}, pattern=${E.patternName??"none"} | hasSettings=${!!C}`,{filledBar:w,emptyBar:O,goldFilledBar:$,goldEmptyBar:E,filledOverlay:!!W,emptyOverlay:!!j,goldFilledOverlay:!!F,goldEmptyOverlay:!!I}));const P=w.textureUrl?Tn(e,w.textureUrl,w.textureScale):null,T=O.textureUrl?Tn(e,O.textureUrl,O.textureScale):null,z=$.textureUrl?Tn(e,$.textureUrl,$.textureScale):null,B=E.textureUrl?Tn(e,E.textureUrl,E.textureScale):null,G=typeof document<"u"?la(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",Y=Xn(G||"var(--nice-warning, #ffcc00)"),X=pe=>la(pe),ie=_.fontFamily||"Arial",le=_.fontSize||18,te=X(_.fontColor||"var(--btn-text, #fff)"),V=_.outlineColor?X(_.outlineColor):null,K=typeof _.outlineWidth=="number"?_.outlineWidth:0,oe=_.shadow||null;typeof document<"u"&&((!Mt||Mt.width!==t||Mt.height!==n)&&(Mt=document.createElement("canvas"),Mt.width=t,Mt.height=n,at=Mt.getContext("2d")),at&&at.clearRect(0,0,t,n),(!ft||ft.width!==t||ft.height!==n)&&(ft=document.createElement("canvas"),ft.width=t,ft.height=n,It=ft.getContext("2d")),It&&It.clearRect(0,0,t,n),(!St||St.width!==t||St.height!==n)&&(St=document.createElement("canvas"),St.width=t,St.height=n,qe=St.getContext("2d")),qe&&qe.clearRect(0,0,t,n));const ne=k?-k:0,he=b||t;e.fillStyle=G,e.font=`bold ${le}px ${ie}`;const de=e.measureText(i).width+20;if(e.fillRect(ne+10,5,de,25),e.save(),e.fillStyle=te,oe){const pe=oe.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);pe&&(e.shadowOffsetX=parseInt(pe[1],10),e.shadowOffsetY=parseInt(pe[2],10),e.shadowBlur=parseInt(pe[3],10),e.shadowColor=pe[4])}if(e.fillText(i,ne+20,22),V&&K>0&&(e.lineWidth=K,e.strokeStyle=V,e.strokeText(i,ne+20,22)),e.restore(),x){const pe=X(g||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${ie}`;const ve=e.measureText(x).width,Ue=8,Ee=ne+10+de+6,Ce=20,Re=7,Oe=ve+Ue*2,Be=4;e.beginPath(),e.moveTo(Ee+Be,Re),e.lineTo(Ee+Oe-Be,Re),e.quadraticCurveTo(Ee+Oe,Re,Ee+Oe,Re+Be),e.lineTo(Ee+Oe,Re+Ce-Be),e.quadraticCurveTo(Ee+Oe,Re+Ce,Ee+Oe-Be,Re+Ce),e.lineTo(Ee+Be,Re+Ce),e.quadraticCurveTo(Ee,Re+Ce,Ee,Re+Ce-Be),e.lineTo(Ee,Re+Be),e.quadraticCurveTo(Ee,Re,Ee+Be,Re),e.closePath(),e.fillStyle=pe,e.fill(),e.fillStyle=te,e.fillText(x,Ee+Ue,Re+14),e.font=`bold ${le}px ${ie}`}const me=120;if(e.fillStyle=G,e.fillRect(ne+he-me-10,5,me,25),e.fillStyle=te,e.fillText(`${o} pts`,ne+he-me+15,22),S&&S.currentCombo>=5){const pe=S.currentCombo>=50?"3x":S.currentCombo>=30?"2.5x":S.currentCombo>=20?"2x":S.currentCombo>=10?"1.5x":"",ve=`${S.currentCombo} combo${pe?" "+pe:""}`;e.font=`bold 12px ${ie}`;const Ee=e.measureText(ve).width+16,Ce=ne+he-me-10-Ee-6;e.fillStyle=X(S.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,nh(e,Ce,7,Ee,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(S.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(ve,Ce+8,22),e.font=`bold 14px ${ie}`}if(M&&M.length>0){const pe=M[M.length-1];if(pe.label){const ve=`${M.length}-${pe.label}`;ve!==_s&&(_s=ve,Fs=Date.now());const Ue=Date.now()-Fs;if(Ue<2500){const Ee=Ue<2e3?1:1-(Ue-2e3)/500,Ce={Perfect:X("var(--success, #00e676)"),Great:X("var(--success, #66bb6a)"),Good:X("var(--accent-primary, #ffeb3b)"),OK:X("var(--warning, #ff9800)"),Bad:X("var(--error, #ef5350)"),Awful:X("var(--error, #b71c1c)")};e.save(),e.globalAlpha=Ee,e.font=`bold ${Math.round(le*1.2)}px ${ie}`;const Re=pe.label,Oe=e.measureText(Re).width,Be=ne+he/2-Oe/2;e.fillStyle=Ce[Re]||te,e.shadowColor="var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.shadowBlur=6,e.fillText(Re,Be,58),V&&K>0&&(e.lineWidth=K,e.strokeStyle=V,e.strokeText(Re,Be,58)),e.restore()}}}const xe=s-2,ce=s+5,ye=40;let Se=1/0,ae=-1/0;if(a.forEach(pe=>{pe.forEach(ve=>{ve.pitch<Se&&(Se=ve.pitch),ve.pitch>ae&&(ae=ve.pitch)})}),c&&Array.isArray(c)&&c.length>0){let pe=null;isFinite(Se)&&isFinite(ae)&&(pe=Math.round((Se+ae)/2));let ve=1/0,Ue=-1/0;c.forEach(({t:Ee,hz:Ce})=>{if(!Ce||Ce<=0)return;let Re=pe;for(const Be of a)for(const Qe of Be)Ee>=Qe.startTime&&Ee<=Qe.startTime+Qe.duration&&(Re=Qe.pitch);const Oe=Qi(Ce,Re);Oe<ve&&(ve=Oe),Oe>Ue&&(Ue=Oe)}),ve!==1/0&&Ue!==-1/0&&(ve<Se&&(Se=Math.floor(ve-2)),Ue>ae&&(ae=Math.ceil(Ue+2)))}(!isFinite(Se)||!isFinite(ae))&&(Se=40,ae=80),Se===ae&&(Se=Math.max(0,Se-6),ae=ae+6);const ue=pe=>{const ve=n-ye-10;return ye+ve-(pe-Se)/(ae-Se)*ve},ze=Ir(f||"normal"),Ye=(n-ye-10)/Math.max(1,ae-Se),je=Math.max(10,Math.round(Ye*(1+2*ze.semitoneTolerance)*.3)),Ve=Math.max(5,Math.round(je*.45));((pe,ve,Ue,Ee,Ce,Re)=>{pe.lineWidth=1;for(let Oe=Math.ceil(Ce);Oe<=Math.floor(Re);Oe++){const Be=ue(Oe);pe.strokeStyle=X(Oe%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),pe.beginPath(),pe.moveTo(0,Math.round(Be)+.5),pe.lineTo(ve,Math.round(Be)+.5),pe.stroke()}})(e,t,n-ye,ye,Se,ae),It&&It.clearRect(0,0,t,n);const et=(s-xe)/(ce-xe)*t;let Ze=n*.5,At=!1,pt=!1;const Et=(pe,ve,Ue,Ee,Ce,Re,Oe=0)=>{const Be=(Ae,Fe,ge,Me,Pe,Ge)=>{const De=Math.min(Ge,Me/2,Pe/2);Ae.beginPath(),Ae.moveTo(Fe+De,ge),Ae.lineTo(Fe+Me-De,ge),Ae.quadraticCurveTo(Fe+Me,ge,Fe+Me,ge+De),Ae.lineTo(Fe+Me,ge+Pe-De),Ae.quadraticCurveTo(Fe+Me,ge+Pe,Fe+Me-De,ge+Pe),Ae.lineTo(Fe+De,ge+Pe),Ae.quadraticCurveTo(Fe,ge+Pe,Fe,ge+Pe-De),Ae.lineTo(Fe,ge+De),Ae.quadraticCurveTo(Fe,ge,Fe+De,ge),Ae.closePath()},Qe=Math.max(2,je/2);Ee.forEach(Ae=>{if(Ae.startTime+Ae.duration<Ce||Ae.startTime>Re)return;const Fe=(Ae.startTime-Ce)/(Re-Ce)*ve,ge=Ae.duration/(Re-Ce)*ve,Me=ue(Ae.pitch)-je/2,Pe=[];if(Array.isArray(p)){const Ge=Ae.startTime+Ae.duration;p.forEach(De=>{if(De.pitch!==Ae.pitch||De.noteStart!=null&&De.noteEnd!=null&&(Math.abs(De.noteStart-Ae.startTime)>.01||Math.abs(De.noteEnd-Ge)>.01))return;const nt=Math.max(De.start,Ae.startTime),Ke=Math.min(De.end,Ge);if(nt>=Ke)return;const Gt=(nt-Ce)/(Re-Ce)*ve,Kt=(Ke-Ce)/(Re-Ce)*ve;Pe.push({x1:Gt,x2:Kt,frac:De.frac})})}if(Ae.isGold){pe.save();const Ge=m&&m.shadowColor?m.shadowColor:Ls,De=m&&typeof m.glowBlur=="number"?m.glowBlur:Is;pe.shadowColor=Ge,pe.shadowBlur=Math.max(4,De-12),pe.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Be(pe,Fe-1,Me-1,ge+2,je+2,Qe),pe.fill(),pe.restore();const nt=Xn("var(--gold-base, #b4af9f)");Rn(pe,Fe,Me,ge,je,A,E.color??nt,E.highlight,E.glow,E.glass,D,E.patternColor,E.patternOnly,B,I),pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),pe.globalAlpha=.18,pe.fillStyle=X("var(--success, #FFD700)"),pe.fillRect(Fe,Me,ge,Math.max(1,je*.25)),pe.globalAlpha=1,pe.restore(),Pe.length>0&&(pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),Pe.forEach(Ke=>{const Gt=Math.max(1,Ke.x2-Ke.x1);Rn(pe,Ke.x1,Me,Gt,je,Z,$.color??"var(--nice-warning, #FFD700)",$.highlight,$.glow,$.glass,re,$.patternColor,$.patternOnly,z,F)}),pe.restore()),Pe.length===0&&(pe.lineWidth=1,pe.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Be(pe,Fe+.5,Me+.5,ge-1,Math.max(1,je-1),Qe),pe.stroke())}else{const Ge=Xn("var(--note-base, #d1d5db)");Rn(pe,Fe,Me,ge,je,U,O.color??Ge,O.highlight,O.glow,O.glass,H,O.patternColor,O.patternOnly,T,j),Pe.length>0&&(pe.save(),Be(pe,Fe,Me,ge,je,Qe),pe.clip(),Pe.forEach(De=>{const nt=Math.max(1,De.x2-De.x1);Rn(pe,De.x1,Me,nt,je,L,w.color??Y,w.highlight,w.glow,w.glass,q,w.patternColor,w.patternOnly,P,W)}),pe.restore())}It&&(It.fillStyle="var(--nice-bg, #fff)",It.fillRect(Fe,Me,ge,je))})};if(a.forEach(pe=>{Et(e,t,n-ye,pe,xe,ce,ye);for(const ve of pe)if(s>=ve.startTime&&s<=ve.startTime+ve.duration){Ze=ue(ve.pitch),At=!0,pt=!!ve.isGold;break}}),!At){let pe=null,ve=null;for(const Ue of a)for(const Ee of Ue)Ee.startTime>s&&(!pe||Ee.startTime<pe.startTime)&&(pe=Ee),Ee.startTime<=s&&(!ve||Ee.startTime>ve.startTime)&&(ve=Ee);pe?(Ze=ue(pe.pitch),pt=!!pe.isGold):ve?(Ze=ue(ve.pitch),pt=!!ve.isGold):Ze=n*.5}const ct=G||X("var(--accent-primary, #ffcc00)"),fe=1+Math.sin((s||0)*8)*.06,be=Ve*fe,_e=[];for(const pe of a)for(const ve of pe){if(ve.startTime+ve.duration<xe||ve.startTime>ce)continue;const Ue=(ve.startTime-xe)/(ce-xe)*t,Ee=ve.duration/(ce-xe)*t,Ce=ue(ve.pitch)-je/2,Re=ve.startTime+ve.duration<=s;_e.push({x:Ue,y:Ce,w:Ee,h:je,isGold:ve.isGold,isSung:Re})}if(!Hu(R||"ball",{ctx:e,ballX:et,ballY:Ze,ballRadius:be,playerColor:ct,ballIsGold:pt,currentTime:s,height:n,visibleNotes:_e})){Mt&&e.drawImage(Mt,0,0),St&&e.drawImage(St,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const pe=Math.max(18,be*5),ve=e.createRadialGradient(et,Ze,0,et,Ze,pe);if(ve.addColorStop(0,ct),ve.addColorStop(1,"transparent"),e.fillStyle=ve,e.beginPath(),e.arc(et,Ze,pe,0,Math.PI*2),e.fill(),e.restore(),y&&at&&ft&&(at.save(),at.globalCompositeOperation="source-over",at.globalAlpha=.95,at.fillStyle=ct,at.beginPath(),at.arc(et,Ze,be+4,0,Math.PI*2),at.fill(),at.restore(),at.save(),at.globalCompositeOperation="destination-in",at.drawImage(ft,0,0),at.restore(),e.drawImage(Mt,0,0)),y&&qe&&ft)try{const Ce=Xn(ct),{h:Re,s:Oe,l:Be}=eh(Ce),Ae=th(Re,Math.max(10,Math.round(Oe*(typeof h=="number"?h:.25))),Be,.85);qe.save(),qe.globalCompositeOperation="multiply",qe.globalAlpha=.65,qe.fillStyle=Ae,qe.beginPath(),qe.arc(et,Ze,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}catch{qe.save(),qe.globalCompositeOperation="source-over",qe.globalAlpha=.6,qe.fillStyle=ct,qe.beginPath(),qe.arc(et,Ze,Math.max(8,be+6),0,Math.PI*2),qe.fill(),qe.restore(),qe.save(),qe.globalCompositeOperation="destination-out",qe.drawImage(ft,0,0),qe.restore(),e.drawImage(St,0,0)}const Ue=m&&m.shadowColor?m.shadowColor:Ls,Ee=m&&typeof m.glowBlur=="number"?m.glowBlur:Is;e.save(),pt?(e.shadowColor=Ue,e.shadowBlur=Ee,e.fillStyle=X("var(--gold-light, #FFF0A8)")):(e.shadowColor=ct,e.shadowBlur=10,e.fillStyle=ct),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(et,Ze,be,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=X("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(v)&&v.length>0){const pe=Date.now(),ve=m&&typeof m.lifeMs=="number"?m.lifeMs:Ku,Ue=(Ce,Re,Oe,Be=5)=>{const Qe=Oe,Ae=Oe*.45;e.beginPath();let Fe=Math.PI/2*3,ge=Ce,Me=Re;const Pe=Math.PI/Be;e.moveTo(Ce,Re-Qe);for(let Ge=0;Ge<Be;Ge++)ge=Ce+Math.cos(Fe)*Qe,Me=Re+Math.sin(Fe)*Qe,e.lineTo(ge,Me),Fe+=Pe,ge=Ce+Math.cos(Fe)*Ae,Me=Re+Math.sin(Fe)*Ae,e.lineTo(ge,Me),Fe+=Pe;e.lineTo(Ce,Re-Qe),e.closePath()},Ee=Ce=>{let Re=Ce>>>0;return()=>(Re=Re*1664525+1013904223>>>0,(Re&2147483647)/2147483647)};v.forEach(Ce=>{const Re=pe-Ce.createdAt;if(Re<0||Re>ve)return;const Oe=Re/ve,Be=(Ce.noteStart-(s-2))/7*t,Qe=ue(Ce.notePitch),Ae=Ee(Ce.seed||Math.floor(Ce.createdAt%1e5)),Fe=m&&typeof m.count=="number"?m.count:Yu,ge=m&&typeof m.baseSpeed=="number"?m.baseSpeed:Zu,Me=m&&typeof m.baseSize=="number"?m.baseSize:Xu;for(let Pe=0;Pe<Fe;Pe++){const Ge=Ae(),De=Ae(),nt=Pe/Fe*Math.PI*2+Ge*Math.PI*.6+Oe*1.5,Ke=6+ge*(1-Oe)*(.5+De*.8),Gt=Be+Math.cos(nt)*Ke,Kt=Qe+Math.sin(nt)*Ke*(.8+Ge*.6),Ct=Math.max(1,Me*(1-Oe)*(.5+De)),xs=40+Math.round(20*Ae()),vs=70+Math.round(20*Ae()),Gr=Math.max(0,1-Oe)*(.9-Ae()*.3),Oc=Math.max(6,Ct*2.6),Wr=Ju(xs,vs,60,Math.round(Oc),(Ce.seed||0)+Pe);Wr&&Wr.complete?(e.save(),e.translate(Gt,Kt+4),e.rotate(nt+Oe*4+(Ae()-.5)*1.2),e.globalAlpha=Gr,e.drawImage(Wr,-Ct/2,-Ct/2,Ct,Ct),e.restore()):(e.save(),e.translate(Gt,Kt+4),e.rotate(nt+Oe*4),e.fillStyle=`hsla(${xs}, ${vs}%, 60%, ${Gr})`,e.fillRect(-Ct/2,-Ct/2,Ct,Ct),e.restore()),Ae()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Oe),e.fillStyle=`hsla(${30+Math.round(10*Ae())}, ${60+Math.round(30*Ae())}%, ${70+Math.round(10*Ae())}%, ${Gr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Oe)})`,e.lineWidth=.8,Ue(Gt,Kt+4,Ct*(1.4+Ae())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:et,ballY:Ze,ballIsGold:pt}},Va=({song:e,currentTime:t,playerRef:n,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{isPlaying:u=!1,playerName:h="Ziom",score:p=1e4,playerBgColor:f="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:m,goldSettings:v,difficultyLevel:x,algorithmLabel:g,algorithmColor:k,latencyMs:b=null,top:S,animationMode:M,karaokeSettings:R=null}=a,N=d.useRef(null),C=d.useRef(null),[w,O]=d.useState({width:600,height:150,top:250,visibleWidth:600}),[$,E]=d.useState(0),_=d.useRef(0),L=d.useRef(null),U=d.useRef(null),Z=d.useRef(null),A=d.useRef(t),q=d.useRef(performance.now()),H=d.useRef(e),re=d.useRef(w),D=d.useRef(s),W=d.useRef(u),j=d.useRef(0),F=d.useRef(!1),I=d.useRef(null),P=d.useRef(null),T=()=>{const z=(e==null?void 0:e.id)??null;if(z!==P.current||!I.current){P.current=z;const B=e.notes.map(te=>te.noteLine);I.current=qn(B,e.bpm??void 0);const G=I.current.reduce((te,V)=>te+V.length,0),Y=I.current.reduce((te,V)=>te+V.filter(K=>K.isGold).length,0),X=I.current.flat().map(te=>te.pitch),ie=X.length?Math.min(...X):0,le=X.length?Math.max(...X):0;oa("BARS",`?? Parsed notes for "${e.title}" — ${I.current.length} verses, ${G} notes (including ${Y} golden), pitch range: ${ie}–${le}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:B.length,verseCount:I.current.length,totalNotes:G,goldCount:Y,minPitch:ie,maxPitch:le})}return I.current};return d.useEffect(()=>{const z=(G,Y,X)=>G+(Y-G)*X,B=G=>{U.current===null&&(U.current=G);const Y=Math.min(.1,(G-(U.current||G))/1e3);U.current=G;const X=j.current,ie=_.current,le=1-Math.exp(-12*Y),te=Math.abs(ie-X)<.25?ie:z(X,ie,le);Math.abs(te-X)>1e-4&&(E(te),j.current=te,N.current&&(N.current.style.transform=`translateX(${te}px)`)),L.current=requestAnimationFrame(B)};return L.current=requestAnimationFrame(B),()=>{L.current&&cancelAnimationFrame(L.current),L.current=null,U.current=null}},[]),d.useEffect(()=>{const z=()=>{if(!n.current)return;const B=n.current.getBoundingClientRect(),G=2/Math.max(1,y),Y=Math.round(B.width*G),X=Math.round(B.width),ie=Y*(150/600);O({width:Y,height:ie,top:30,visibleWidth:X})};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[n,y]),d.useEffect(()=>{var X;if(u||!N.current)return;const z=N.current.getContext("2d");if(!z)return;const B=T(),G=t-(e.gap??0)/1e3,Y=ua(z,w.width,w.height,B,G,h,p,f,s,e.id,m??void 0,i,x??void 0,u,v??void 0,o,g,k,j.current,w.visibleWidth,l,c,M,R);if(Y&&N.current){const ie=w.visibleWidth||(((X=C.current)==null?void 0:X.getBoundingClientRect().width)??w.width),le=w.width;let te=Math.round(ie/2-Y.ballX);const V=ie-le;te=Math.max(V,Math.min(0,te)),_.current=te}},[t,e,w,s,u,i,o,M,R]),d.useEffect(()=>{A.current=t,q.current=performance.now()},[t]),d.useEffect(()=>{H.current=e},[e]),d.useEffect(()=>{re.current=w},[w]),d.useEffect(()=>{D.current=s},[s]),d.useEffect(()=>{W.current=u},[u]),d.useEffect(()=>{const z=()=>{var oe;const B=N.current,G=H.current,Y=re.current;if(!B||!G||!Y)return;const X=B.getContext("2d");if(!X)return;const ie=T(),le=Math.min(.5,(performance.now()-q.current)/1e3),V=(W.current?A.current+le:A.current)-(G.gap??0)/1e3,K=ua(X,Y.width,Y.height,ie,V,h,p,f,D.current,G.id,m??void 0,i,x??void 0,W.current,v??void 0,o,g,k,j.current,Y.visibleWidth,l,c,M,R);if(K){const ne=Y.visibleWidth||(((oe=C.current)==null?void 0:oe.getBoundingClientRect().width)??Y.width),he=Y.width;let J=Math.round(ne/2-K.ballX);const de=ne-he;J=Math.max(de,Math.min(0,J)),_.current=J}};if(u){F.current||(F.current=!0,oa("BARS",`? Drawing bars in RAF loop � canvas: ${re.current.width}�${re.current.height}px, player: ${h}`,{canvasSize:re.current}));const B=()=>{z(),Z.current=requestAnimationFrame(B)};return Z.current=requestAnimationFrame(B),()=>{Z.current&&cancelAnimationFrame(Z.current),Z.current=null}}F.current=!1},[u,h,p,f,m,i,x,v,o,M,R]),r.jsxs("div",{ref:C,style:{position:"absolute",left:"50%",top:`${S??w.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:w.visibleWidth,height:w.height,overflow:"hidden"},children:[r.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),r.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-on-dark, #fff)"},children:typeof b<"u"&&b!==null?(()=>{const z=b,B=z<=120?"var(--latency-good, #10b981)":z<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",G=`${z}ms`;return r.jsxs("div",{className:z>250?"av-latency-pulse":"",style:{background:B,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[r.jsx("span",{style:{display:"inline-block",transform:"translateY(-1px)"},children:"??"}),r.jsx("span",{children:G})]})})():r.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"�"})}),r.jsx("canvas",{ref:N,width:w.width,height:w.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${p??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${$}px)`,willChange:"transform"}})]})},ho="/textures/seamless/256x256";function $t(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${ho}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function Lt(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${ho}/${e}/${e}_${i}-256x256.png`}})}}const Ha=[$t("Fire",8,"🔥"),$t("Metal",8,"⚙️"),$t("Ice",8,"❄️"),$t("Stone",8,"🪨"),$t("Wood",8,"🪵"),$t("Tile",8,"🧱"),$t("Concrete",8,"🏗️"),$t("Trees",8,"🌲"),$t("Grass",8,"🌿"),Lt("Wall",24,"🏠"),Lt("Rust",24,"🟤"),Lt("Woven",24,"🧵"),Lt("Ground",24,"🟫"),Lt("Pebbles",24,"🫧"),Lt("Plant",24,"🌱"),Lt("Roof",24,"🏛️"),Lt("Misc",24,"🎨")],po=Ha.flatMap(e=>e.entries);function ih(e){return po.find(t=>t.url===e)}const oh={color:"var(--nice-primary, #2196f3)",highlight:"var(--nice-bg, #fff)",glow:0,capStyle:"flat",pattern:null,texture:null},fo=({fill:e=oh,onChange:t=()=>{},previewColor:n="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=Te(),[l,c]=d.useState(null),u=(g,k)=>{t({...e,[g]:k})},h=d.useMemo(()=>{const g=e.color||n||"var(--nice-primary, #2196f3)";return(k,b,S)=>{const M=Bn.find(N=>N.name===k)||Bn[0],R=b?Nr.find(N=>N.name===b)??null:null;return co({width:80,height:22,capStyle:M,color:g,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:R,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:S??null,textureScale:e.textureScale})}},[e,n]),p=`2px solid ${a}`,f=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=d.useRef(null),m=d.useRef(null),v=d.useCallback((g,k)=>{g.current&&g.current.scrollBy({left:k*180,behavior:"smooth"})},[]),x={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-border, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return r.jsxs("div",{style:{padding:"4px 0"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx(rt.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.barColor","Color")}),r.jsx(rt.Form.Check,{type:"checkbox",id:`bar-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.color,onChange:g=>u("color",g.target.checked?null:n||"var(--nice-primary, #2196f3)"),className:"mb-0"}),e.color&&r.jsx("input",{type:"color",value:e.color,onChange:g=>u("color",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),r.jsx(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.capShape","Cap shape")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...x,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>v(y,-1),children:"�"}),r.jsx("button",{type:"button",style:{...x,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>v(y,1),children:"�"}),r.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Bn.map(g=>{const k=e.capStyleName===g.name;return r.jsx("div",{title:g.name,onClick:()=>u("capStyleName",g.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:k?f:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(g.name,null)}},g.name)})})]}),r.jsx(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.pattern","Pattern")}),r.jsxs("div",{style:{position:"relative",marginBottom:10},children:[r.jsx("button",{type:"button",style:{...x,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>v(m,-1),children:"�"}),r.jsx("button",{type:"button",style:{...x,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>v(m,1),children:"�"}),r.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[r.jsx("div",{title:"None",onClick:()=>u("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-text-secondary, #555)":p,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":f,fontSize:12,lineHeight:"22px",color:"var(--nice-border, #ccc)"},children:"�"}),Nr.map(g=>{const k=e.patternName===g.name;return r.jsx("div",{title:g.name,onClick:()=>u("patternName",g.name),style:{cursor:"pointer",flexShrink:0,border:k?p:"1px solid var(--nice-text-secondary, #555)",borderRadius:6,padding:3,background:k?f:"var(--nice-text, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,g.name)}},g.name)})]})]}),r.jsx(rt.Form.Check,{type:"switch",id:`bar-pattern-only-${a}`,label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:g=>u("patternOnly",g.target.checked),className:"mb-2"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[r.jsx(rt.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:o("playerForm.patternColor","Pattern color")}),r.jsx(rt.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:g=>u("patternColor",g.target.checked?null:n||"var(--nice-bg, #fff)"),className:"mb-0"}),e.patternColor&&r.jsx("input",{type:"color",value:e.patternColor,onChange:g=>u("patternColor",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&r.jsxs(r.Fragment,{children:[r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.highlight,onChange:g=>u("highlight",parseInt(g.target.value)),className:"mb-2"}),r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.glow","Glow"),": ",e.glow,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.glow,onChange:g=>u("glow",parseInt(g.target.value)),className:"mb-2"})]}),r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),r.jsx(rt.Form.Range,{min:0,max:100,value:e.glass,onChange:g=>u("glass",parseInt(g.target.value)),className:"mb-2"}),r.jsx(rt.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"var(--nice-border, #ccc)"},children:o("playerForm.texture","Texture")}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[r.jsx("button",{type:"button",className:`btn btn-sm ${e.textureUrl?"btn-outline-secondary":"btn-primary"}`,onClick:()=>{u("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Ha.map(g=>r.jsx("button",{type:"button",className:`btn btn-sm ${(l==null?void 0:l.name)===g.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>c(k=>(k==null?void 0:k.name)===g.name?null:g),title:g.name,children:g.icon},g.name))]}),l&&r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(g=>{const k=e.textureUrl===g.url;return r.jsx("div",{title:g.label,onClick:()=>u("textureUrl",k?null:g.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:k?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${g.url})`,backgroundSize:"cover",boxShadow:k?`0 0 6px ${a}`:void 0}},g.url)})}),e.textureUrl&&r.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-text-muted, #aaa)"}}),r.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&r.jsxs(r.Fragment,{children:[r.jsxs(rt.Form.Label,{style:{fontSize:13,color:"var(--nice-border, #ccc)"},children:[o("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"�"]}),r.jsx(rt.Form.Range,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:g=>u("textureScale",parseInt(g.target.value)/100),className:"mb-2"})]})]})},st=it.scoped("AudioPitchAnalyzer");function mo({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=Te(),[o,l]=d.useState("pitchy"),[c,u]=d.useState(null),[h,p]=d.useState(t),[f,y]=d.useState({}),[m,v]=d.useState({}),[x,g]=d.useState([]),[k,b]=d.useState([]),[S,M]=d.useState(!1),[R,N]=d.useState(null),[C]=d.useState(null),[w]=d.useState(null),[O,$]=d.useState(null),E=d.useRef(null);function _(D){try{if(D instanceof Error){let j=`${D.message}
40
- ${D.stack??""}`;const F=D;if(F!=null&&F.attemptedUrls)try{j+=`
41
- Attempted URLs: ${Array.isArray(F.attemptedUrls)?F.attemptedUrls.join(", "):String(F.attemptedUrls)}`}catch{j+=`
42
- Attempted URLs: ${String(F.attemptedUrls)}`}return j}const W=D;return W!=null&&W.attemptedUrls?`Error: ${String(W.message??W)}
43
- Attempted URLs: ${Array.isArray(W.attemptedUrls)?W.attemptedUrls.join(", "):String(W.attemptedUrls)}`:String(D)}catch{return"Unknown error"}}function L(D){if(!D||D<=0)return null;const W=12*Math.log2(D/440)+69;return Math.round(W-12)}async function U(D){var j;const W=(j=D.target.files)==null?void 0:j[0];W&&await Z(W,h)}async function Z(D,W){N(null),b([]),M(!0);try{const j=await D.arrayBuffer(),F=window.AudioContext??window.webkitAudioContext,P=await new F().decodeAudioData(j),T=P.getChannelData(0);u(T);const z=P.sampleRate,B=Math.floor(z*.1),G=B,Y=()=>{const K=[],oe=ra.PitchDetector.forFloat32Array(B);for(let ne=0;ne<T.length-B;ne+=G){const he=T.slice(ne,ne+B),[J,de]=oe.findPitch(he,z),me=L(J);me&&J>50&&J<2e3&&de>.7&&K.push({start:ne/z,duration:B/z,pitch:me,freq:J})}return K},X=()=>{const K=[];for(let oe=0;oe<T.length-B;oe+=G){const ne=T.slice(oe,oe+B),he=q(ne,z),J=L(he);J&&he>50&&he<2e3&&K.push({start:oe/z,duration:B/z,pitch:J,freq:he})}return K};if(W){M(!0),N(null);const K={};try{const oe={};try{K.pitchy=Y(),oe.pitchy=null}catch(ne){K.pitchy=[],oe.pitchy=_(ne),st.warn("pitchy failed",ne)}try{K["ultrastar-wp"]=X(),oe["ultrastar-wp"]=null}catch(ne){K["ultrastar-wp"]=[],oe["ultrastar-wp"]=_(ne),st.warn("ultrastar-wp failed",ne)}K.aubio=[],oe.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const he=(await a(D)).track??[];K.crepe=he.map((J,de)=>{var me;return{start:J.t,duration:(me=he[de+1])!=null&&me.t?he[de+1].t-J.t:.1,pitch:L(J.hz)??0,freq:J.hz}}),oe.crepe=null}catch(ne){K.crepe=[],oe.crepe=_(ne),st.warn("crepe failed",ne)}try{if(!s)throw new Error("Librosa backend not configured");const he=(await s(new File([D],D.name,{type:D.type}))).track??[];K.librosa=he.map((J,de)=>{var me;return{start:J.t,duration:(me=he[de+1])!=null&&me.t?he[de+1].t-J.t:.1,pitch:L(J.hz)??0,freq:J.hz}}),oe.librosa=null}catch(ne){K.librosa=[],oe.librosa=_(ne),st.warn("librosa failed",ne)}v(oe),y(K),b(K[o]??[])}catch(oe){st.error("compareAll overall failed",oe);const ne=oe instanceof Error?oe.message:String(oe);N(i("audioPitch.errorComparing")+ne)}finally{M(!1)}return}const ie=[],le=[];let te=0;if(o==="pitchy"){const K=ra.PitchDetector.forFloat32Array(B);for(let oe=0;oe<T.length-B;oe+=G){const ne=T.slice(oe,oe+B);let he=0;for(let xe=0;xe<ne.length;xe++)he+=ne[xe]*ne[xe];he=Math.sqrt(he/ne.length),le.push(he);const[J,de]=K.findPitch(ne,z),me=L(J);me&&J>50&&J<2e3&&de>.7&&(ie.push({start:oe/z,duration:B/z,pitch:me,freq:J}),te++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const K=await a(D);if(!K.track||K.track.length===0)N(i("audioPitch.crepeNoNotes")),st.warn("Crepe: No notes detected in audio file.");else{const oe=K.track.map((ne,he)=>{const J=L(ne.hz);return J&&ne.hz>50&&ne.hz<2e3?{start:ne.t,duration:he<K.track.length-1?K.track[he+1].t-ne.t:.1,pitch:J,freq:ne.hz}:null}).filter(ne=>ne!==null);if(b(oe),e)try{e(oe)}catch(ne){st.error("Error in onSegments:",ne)}g([]),u(null);return}}catch(K){N(i("audioPitch.crepeBackendError")),$(_(K)),st.error("Crepe: Error calling backend:",K)}else if(o==="librosa")try{await A(D),g([]),u(null);return}catch(K){N(i("audioPitch.librosaBackendError")),$(_(K)),st.error("Librosa: Error calling backend:",K)}else if(o==="ultrastar-wp")for(let K=0;K<T.length-B;K+=G){const oe=T.slice(K,K+B);let ne=0;for(let de=0;de<oe.length;de++)ne+=oe[de]*oe[de];ne=Math.sqrt(ne/oe.length),le.push(ne);const he=q(oe,z),J=L(he);J&&he>50&&he<2e3&&(ie.push({start:K/z,duration:B/z,pitch:J,freq:he}),te++)}g(le);const V=H(ie);if(b(V),e)try{e(V)}catch(K){st.error("Error in onSegments:",K)}V.length===0&&o!=="crepe"&&(N(i("audioPitch.noNotesDetected")),st.warn("No notes detected in audio file."))}catch(j){N(i("audioPitch.errorAnalyzing")+(j instanceof Error?j.message:String(j))),$(_(j)),st.error("Error analyzing audio file:",j)}finally{M(!1)}}d.useEffect(()=>{n&&Z(n,!0)},[n]);async function A(D){try{if(!s)throw new Error("Librosa backend not configured");const W=new File([D],"capture.wav",{type:"audio/wav"}),F=((await s(W)).track??[]).map(I=>({t:I.t,hz:I.hz}));if(e){const I=F.map((P,T)=>{var G;const z=((G=F[T+1])==null?void 0:G.t)??P.t+.1,B=L(P.hz)??0;return{start:P.t,duration:Math.max(.05,z-P.t),pitch:B,freq:P.hz}});e(I),b(I)}}catch(W){st.warn("Librosa analysis failed, falling back to local detectors",W);const F=(typeof W=="object"&&W!==null?W:{}).attemptedUrls;F&&st.error("Librosa attempted URLs:",F);const I=F?Array.isArray(F)?F.join(", "):String(F):null,P=W instanceof Error?W.message:String(W);N(i("audioPitch.librosaBackendError")+": "+P+(I?" (attempted: "+I+")":"")),$(_(W))}}function q(D,W){const I=Math.floor(W/50),P=Math.max(2,Math.floor(W/2e3));let T=0;for(let Y=0;Y<D.length;Y++)T+=D[Y]*D[Y];if(T<=1e-8)return 0;let z=-1,B=0;const G=1e-10;for(let Y=P;Y<=Math.min(I,D.length-2);Y++){let X=0;const ie=D.length-Y;for(let te=0;te<ie;te++)X+=D[te]*D[te+Y];const le=X/(ie+G)/(T/D.length+G);le>B&&(B=le,z=Y)}return z>0&&B>.01?W/z:0}function H(D){if(D.length===0)return[];const W=[];let j=D[0];for(let F=1;F<D.length;F++){const I=D[F];I.pitch===j.pitch&&Math.abs(I.freq-j.freq)<1?j.duration+=I.duration:(W.push(j),j=I)}return W.push(j),W}function re(){try{const D=Object.keys(f).length>0?Object.keys(f):["pitchy","ultrastar-wp","aubio","crepe","librosa"],W=(()=>{let te=0;for(const V of D){const K=f[V]??[];for(const oe of K)te=Math.max(te,oe.start+(oe.duration||0))}return te||0})(),j=(te,V)=>!te||!V?1/0:1200*Math.log2(te/V),F=(te,V)=>{if(!te||!V)return!1;const K=Math.round(Math.log2(V/te)),oe=te*Math.pow(2,K),ne=Math.abs(j(oe,V));return Math.abs(K)>=1&&ne<50},I=te=>{const V={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!te||te.length===0)return V;V.count=te.length,V.totalDur=te.reduce((he,J)=>he+(J.duration||0),0);const K=te.map(he=>he.freq).filter(Boolean);if(K.length===0)return V;const oe=K.reduce((he,J)=>he+J,0)/K.length,ne=K.reduce((he,J)=>he+(J-oe)*(J-oe),0)/K.length;return V.meanFreq=oe,V.stdFreq=Math.sqrt(ne||0),V.meanDur=V.totalDur/V.count,V.voicedFraction=W>0?V.totalDur/W:null,V},P=(te,V)=>{let K=0,oe=0;const ne=[];for(const J of te){const de=J.start,me=J.start+(J.duration||.05);let xe=null,ce=0;for(const ye of V){const Se=ye.start,ae=ye.start+(ye.duration||.05),ue=Math.max(0,Math.min(me,ae)-Math.max(de,Se));ue>ce&&(ce=ue,xe=ye)}if(xe&&ce>0){const ye=Math.abs(j(J.freq,xe.freq));ne.push(ye),ye<50&&K++,F(J.freq,xe.freq)&&oe++}}const he=ne.length?ne.reduce((J,de)=>J+de,0)/ne.length:null;return{matches:K,compared:te.length,meanCents:he,octaveErrors:oe}},T=[];T.push("# AudioPitchAnalyzer � Comparative Report"),T.push(`Generated: ${new Date().toISOString()}`),T.push(""),T.push("## Summary"),T.push(`- Selected algorithm in UI: **${o}**`),T.push(`- Total analyzed duration (approx): **${W.toFixed(3)} s**`),T.push(""),T.push("## Per-algorithm statistics"),T.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),T.push("|---|---:|---:|---:|---:|---:|---:|");const z={};for(const te of D){const V=f[te]??[],K=I(V);z[te]=K,T.push(`| ${te} | ${K.count||0} | ${(K.totalDur||0).toFixed(3)} | ${K.voicedFraction!==null?(K.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${K.meanFreq?K.meanFreq.toFixed(1):"N/A"} | ${K.stdFreq?K.stdFreq.toFixed(1):"N/A"} | ${K.meanDur?K.meanDur.toFixed(3):"N/A"} |`)}T.push(""),T.push("## Pairwise agreement (reference -> test)");const B=D.includes("crepe")?"crepe":D.includes("librosa")?"librosa":D.includes("pitchy")?"pitchy":D[0];T.push(`Reference algorithm: **${B}**`),T.push(""),T.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),T.push("|---|---:|---:|---:|---:|---:|");for(const te of D){if(te===B)continue;const V=P(f[B]??[],f[te]??[]),K=V.compared?(V.matches/V.compared*100).toFixed(1)+"%":"N/A";T.push(`| ${B} -> ${te} | ${V.matches} | ${V.compared} | ${K} | ${V.meanCents!==null?V.meanCents.toFixed(1):"N/A"} | ${V.octaveErrors} |`)}T.push(""),T.push("## Observations and analysis"),T.push("- The table above gives an overview of voiced coverage and per-algorithm mean frequencies. High voiced fraction indicates the algorithm detected many tonal regions; low fraction indicates conservative voicing or failures in noisy/quiet sections."),T.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),T.push("- Mean cents difference (reference vs test) indicates systematic tuning offsets or frequency bias; values <50 cents are generally acceptable for musical content, but for scoring you may want <20 cents."),T.push("");for(const te of D){T.push(`### ${te}`);const V=z[te];T.push(`- Segments: ${V.count||0}`),T.push(`- Total voiced (s): ${(V.totalDur||0).toFixed(3)}`),T.push(`- Voiced fraction: ${V.voicedFraction!==null?(V.voicedFraction*100).toFixed(1)+"%":"N/A"}`),T.push(`- Mean frequency: ${V.meanFreq?V.meanFreq.toFixed(2)+" Hz":"N/A"}`),T.push(`- Std frequency: ${V.stdFreq?V.stdFreq.toFixed(2)+" Hz":"N/A"}`),T.push("")}T.push("## Conclusions & recommendation");const G=[];for(const te of D){if(te===B){G.push({alg:te,score:100});continue}const V=P(f[B]??[],f[te]??[]),K=V.compared?V.matches/V.compared:0,oe=V.compared?V.octaveErrors/V.compared:0,ne=K-oe*.5;G.push({alg:te,score:ne})}G.sort((te,V)=>V.score-te.score),T.push(`- Based on this recording, recommended authoritative detector: **${G[0].alg}** (best agreement with reference).`),T.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),T.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),T.push(""),T.push("## Raw data (per-algorithm segments)");for(const te of D){const V=f[te]??[];T.push(`### ${te} � ${V.length} segments`);for(const oe of V)T.push(`- ${oe.start.toFixed(3)} .. ${(oe.start+(oe.duration||0)).toFixed(3)} : ${oe.freq.toFixed(2)} Hz (pitch ${oe.pitch})`);const K=m[te];K&&T.push(`- Error: ${K}`),T.push("")}const Y=T.join(`
44
- `),X=new Blob([Y],{type:"text/markdown;charset=utf-8"}),ie=URL.createObjectURL(X),le=document.createElement("a");le.href=ie,le.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(le),le.click(),le.remove(),URL.revokeObjectURL(ie)}catch(D){st.error("generateScientificReport error",D),st.warn(i("audioPitch.reportError")+String(D))}}return r.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid var(--nice-border, #ccc)",borderRadius:8},children:[r.jsx("h3",{children:i("audioPitch.title")}),r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:i("audioPitch.algorithm")}),r.jsxs("select",{id:"pitch-algorithm-select",value:o,onChange:D=>l(D.target.value),style:{marginRight:16},children:[r.jsx("option",{value:"ultrastar-wp",children:"Ultrastar WP (autokorelacja)"}),r.jsx("option",{value:"crepe",children:"crepe (AI)"}),r.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),r.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),r.jsxs("label",{style:{marginRight:8},children:[r.jsx("input",{type:"checkbox",checked:h,onChange:D=>p(D.target.checked)})," ",i("audioPitch.compareAll")]}),r.jsx("input",{type:"file",accept:"audio/*",ref:E,onChange:U,disabled:S})]}),S&&r.jsx("div",{children:i("audioPitch.analyzing")}),r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:i("audioPitch.method")})," ",o]}),R&&r.jsxs("div",{style:{color:"red",marginTop:8},children:[r.jsxs("b",{children:[o,": "]}),r.jsx("div",{children:R}),O&&r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:O})]}),C&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("b",{children:"Aubio diagnostics"}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:C}),w&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Probe:"})," ",w]})]}),(Object.keys(f).length>0||Object.keys(m).length>0)&&r.jsxs("div",{style:{marginTop:12},children:[r.jsx("button",{onClick:()=>re(),children:i("audioPitch.downloadReport")}),Object.entries(m).length>0&&r.jsxs("div",{style:{marginTop:8},children:[r.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(m).filter(([D,W])=>W).map(([D,W])=>r.jsxs("div",{style:{marginTop:6},children:[r.jsxs("b",{children:[D,":"]}),r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:W})]},D))]})]}),k.length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("b",{children:i("audioPitch.resultUltrastar")}),r.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[k.map(D=>`: ${Math.round(D.start*10)} ${Math.round(D.duration*10)} ${D.pitch} [${D.freq.toFixed(1)} Hz]`).join(`
39
+ </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(o)}`},nh=(e,t,r,a,s)=>{const i=`${e}-${t}-${r}-${Math.round(a)}-${s}`;let o=_s.get(i);return o||(o=new Image,o.src=th(e,t,r,a,s),_s.set(i,o),o)},rh=e=>{const t=e.replace("#",""),r=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,a=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,s=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,i=Math.max(r,a,s),o=Math.min(r,a,s);let l=0,c=0;const d=(i+o)/2;if(i!==o){const h=i-o;switch(c=d>.5?h/(2-i-o):h/(i+o),i){case r:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-r)/h+2;break;case s:l=(r-a)/h+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},ah=(e,t,r,a=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(r)}%, ${a})`;function Jn(e){try{const t=Se.resolveCssColor(e),[r,a,s]=ed(t),i=o=>o.toString(16).padStart(2,"0");return`#${i(r)}${i(a)}${i(s)}`.toLowerCase()}catch{return"var(--nice-warning, #ffcc00)"}}function sh(e,t,r,a,s,i){const o=Math.min(i,a/2,s/2);e.beginPath(),e.moveTo(t+o,r),e.lineTo(t+a-o,r),e.quadraticCurveTo(t+a,r,t+a,r+o),e.lineTo(t+a,r+s-o),e.quadraticCurveTo(t+a,r+s,t+a-o,r+s),e.lineTo(t+o,r+s),e.quadraticCurveTo(t,r+s,t,r+s-o),e.lineTo(t,r+o),e.quadraticCurveTo(t,r,t+o,r),e.closePath()}const on=new Map,$n=new Set,fr=new Set;function Ha(e){const t=on.get(e);return t?Promise.resolve(t):fr.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):$n.has(e)?new Promise((r,a)=>{const s=()=>{on.has(e)?r(on.get(e)):fr.has(e)?a(new Error(`Texture failed: ${e}`)):requestAnimationFrame(s)};s()}):($n.add(e),new Promise((r,a)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>{on.set(e,s),$n.delete(e),r(s)},s.onerror=()=>{$n.delete(e),fr.add(e),a(new Error(`Failed to load texture: ${e}`))},s.src=e}))}function ih(e){return on.get(e)??null}function Pn(e,t,r=1){const a=on.get(t);if(!a)return!$n.has(t)&&!fr.has(t)&&Ha(t).catch(()=>{}),null;const s=e.createPattern(a,"repeat");if(!s)return null;if(r!==1){const i=new DOMMatrix;i.scaleSelf(r,r),s.setTransform(i)}return s}function oh(e){for(const t of e)t&&Ha(t).catch(()=>{})}const An=new Map,rn=new Set;function ho(e,t,r){return`${e}|${t}|${r??""}`}function lh(e,t,r){const a=ho(e.name,t,r),s=An.get(a);if(s)return Promise.resolve(s);if(rn.has(a))return new Promise((m,x)=>{const v=()=>{An.has(a)?m(An.get(a)):rn.has(a)?requestAnimationFrame(v):x(new Error(`Pattern render failed: ${a}`))};v()});rn.add(a);const i="p",o=e.mk(i,t,r??void 0),l=o.match(/width="(\d+)"/),c=o.match(/height="(\d+)"/),d=l?parseInt(l[1],10):16,h=c?parseInt(c[1],10):16,f=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${h}"><defs>${o}</defs><rect width="${d}" height="${h}" fill="url(#${i})"/></svg>`,p=new Blob([f],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(p);return new Promise((m,x)=>{const v=new Image;v.onload=()=>{An.set(a,v),rn.delete(a),URL.revokeObjectURL(y),m(v)},v.onerror=()=>{rn.delete(a),URL.revokeObjectURL(y),x(new Error(`Failed to render pattern tile: ${e.name}`))},v.src=y})}function En(e,t,r,a){const s=ho(t.name,r,a),i=An.get(s);return i?e.createPattern(i,"repeat"):(rn.has(s)||lh(t,r,a).catch(()=>{}),null)}let Rt=null,st=null,mt=null,Pt=null,kt=null,Ve=null,Fs="",Os=0,Bs="";const ha=(e,t,r,a,s,i,o,l,c,d,h,f,p,y,m,x,v,g,S,b,k,j,N,R)=>{e.clearRect(0,0,t,r);const w=R??null,M=(w==null?void 0:w.filledBar)??Kt,I=(w==null?void 0:w.emptyBar)??_r,A=(w==null?void 0:w.goldFilledBar)??Or,T=(w==null?void 0:w.goldEmptyBar)??Fr,O=(w==null?void 0:w.font)??Br,E=Rn(M.capStyleName),V=Rn(I.capStyleName),ee=Rn(A.capStyleName),z=Rn(T.capStyleName),q=M.patternName?Nn(M.patternName):null,K=I.patternName?Nn(I.patternName):null,re=A.patternName?Nn(A.patternName):null,_=T.patternName?Nn(T.patternName):null,U=q?En(e,q,M.patternColor??M.color??"var(--nice-bg, #fff)",M.patternColor):null,$=K?En(e,K,I.patternColor??I.color??"var(--nice-border, #d1d5db)",I.patternColor):null,P=re?En(e,re,A.patternColor??"var(--nice-warning, #FFD700)",A.patternColor):null,F=_?En(e,_,T.patternColor??"var(--nice-warning, #FFD700)",T.patternColor):null;Bs!==i&&(Bs=i,ca("RENDER",`Renderer using settings for "${i}" — filled: cap=${M.capStyleName}, glass=${M.glass} | empty: cap=${I.capStyleName}, glass=${I.glass} | goldFilled: cap=${A.capStyleName}, pattern=${A.patternName??"none"} | goldEmpty: cap=${T.capStyleName}, pattern=${T.patternName??"none"} | hasSettings=${!!w}`,{filledBar:M,emptyBar:I,goldFilledBar:A,goldEmptyBar:T,filledOverlay:!!U,emptyOverlay:!!$,goldFilledOverlay:!!P,goldEmptyOverlay:!!F}));const D=M.textureUrl?Pn(e,M.textureUrl,M.textureScale):null,C=I.textureUrl?Pn(e,I.textureUrl,I.textureScale):null,L=A.textureUrl?Pn(e,A.textureUrl,A.textureScale):null,B=T.textureUrl?Pn(e,T.textureUrl,T.textureScale):null,G=typeof document<"u"?Se.resolveCssColor(l||"var(--nice-color-accent, #ffcc00)"):l||"var(--nice-color-accent, #ffcc00)",H=Jn(G||"var(--nice-warning, #ffcc00)"),X=pe=>Se.resolveCssColor(pe),oe=O.fontFamily||"Arial",le=O.fontSize||18,ne=X(O.fontColor||"var(--btn-text, #fff)"),Z=O.outlineColor?X(O.outlineColor):null,Y=typeof O.outlineWidth=="number"?O.outlineWidth:0,se=O.shadow||null;typeof document<"u"&&((!Rt||Rt.width!==t||Rt.height!==r)&&(Rt=document.createElement("canvas"),Rt.width=t,Rt.height=r,st=Rt.getContext("2d")),st&&st.clearRect(0,0,t,r),(!mt||mt.width!==t||mt.height!==r)&&(mt=document.createElement("canvas"),mt.width=t,mt.height=r,Pt=mt.getContext("2d")),Pt&&Pt.clearRect(0,0,t,r),(!kt||kt.width!==t||kt.height!==r)&&(kt=document.createElement("canvas"),kt.width=t,kt.height=r,Ve=kt.getContext("2d")),Ve&&Ve.clearRect(0,0,t,r));const ae=S?-S:0,ue=b||t;e.fillStyle=G,e.font=`bold ${le}px ${oe}`;const de=e.measureText(i).width+20;if(e.fillRect(ae+10,5,de,25),e.save(),e.fillStyle=ne,se){const pe=se.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);pe&&(e.shadowOffsetX=parseInt(pe[1],10),e.shadowOffsetY=parseInt(pe[2],10),e.shadowBlur=parseInt(pe[3],10),e.shadowColor=pe[4])}if(e.fillText(i,ae+20,22),Z&&Y>0&&(e.lineWidth=Y,e.strokeStyle=Z,e.strokeText(i,ae+20,22)),e.restore(),v){const pe=X(g||"var(--nice-text-secondary, #6b7280)");e.font=`bold 12px ${oe}`;const xe=e.measureText(v).width,qe=8,Ie=ae+10+de+6,Me=20,Ne=7,Be=xe+qe*2,Ge=4;e.beginPath(),e.moveTo(Ie+Ge,Ne),e.lineTo(Ie+Be-Ge,Ne),e.quadraticCurveTo(Ie+Be,Ne,Ie+Be,Ne+Ge),e.lineTo(Ie+Be,Ne+Me-Ge),e.quadraticCurveTo(Ie+Be,Ne+Me,Ie+Be-Ge,Ne+Me),e.lineTo(Ie+Ge,Ne+Me),e.quadraticCurveTo(Ie,Ne+Me,Ie,Ne+Me-Ge),e.lineTo(Ie,Ne+Ge),e.quadraticCurveTo(Ie,Ne,Ie+Ge,Ne),e.closePath(),e.fillStyle=pe,e.fill(),e.fillStyle=ne,e.fillText(v,Ie+qe,Ne+14),e.font=`bold ${le}px ${oe}`}const me=120;if(e.fillStyle=G,e.fillRect(ae+ue-me-10,5,me,25),e.fillStyle=ne,e.fillText(`${o} pts`,ae+ue-me+15,22),k&&k.currentCombo>=5){const pe=k.currentCombo>=50?"3x":k.currentCombo>=30?"2.5x":k.currentCombo>=20?"2x":k.currentCombo>=10?"1.5x":"",xe=`${k.currentCombo} combo${pe?" "+pe:""}`;e.font=`bold 12px ${oe}`;const Ie=e.measureText(xe).width+16,Me=ae+ue-me-10-Ie-6;e.fillStyle=X(k.currentCombo>=20?"var(--nice-color-success, #FFD700)":"var(--nice-color-warning, #ff9800)"),e.globalAlpha=.9,sh(e,Me,7,Ie,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=X(k.currentCombo>=20?"var(--nice-text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(xe,Me+8,22),e.font=`bold 14px ${oe}`}if(j&&j.length>0){const pe=j[j.length-1];if(pe.label){const xe=`${j.length}-${pe.label}`;xe!==Fs&&(Fs=xe,Os=Date.now());const qe=Date.now()-Os;if(qe<2500){const Ie=qe<2e3?1:1-(qe-2e3)/500,Me={Perfect:X("var(--nice-color-success, #00e676)"),Great:X("var(--nice-color-success, #66bb6a)"),Good:X("var(--nice-color-accent, #ffeb3b)"),OK:X("var(--nice-color-warning, #ff9800)"),Bad:X("var(--nice-color-error, #ef5350)"),Awful:X("var(--nice-color-error, #b71c1c)")};e.save(),e.globalAlpha=Ie,e.font=`bold ${Math.round(le*1.2)}px ${oe}`;const Ne=pe.label,Be=e.measureText(Ne).width,Ge=ae+ue/2-Be/2;e.fillStyle=Me[Ne]||ne,e.shadowColor=Se.resolveCssColor("var(--nice-overlay-50, rgba(0, 0, 0, 0.5))",e.canvas),e.shadowBlur=6,e.fillText(Ne,Ge,58),Z&&Y>0&&(e.lineWidth=Y,e.strokeStyle=Z,e.strokeText(Ne,Ge,58)),e.restore()}}}const ve=s-2,ce=s+5,ye=40;let ke=1/0,ie=-1/0;if(a.forEach(pe=>{pe.forEach(xe=>{xe.pitch<ke&&(ke=xe.pitch),xe.pitch>ie&&(ie=xe.pitch)})}),c&&Array.isArray(c)&&c.length>0){let pe=null;isFinite(ke)&&isFinite(ie)&&(pe=Math.round((ke+ie)/2));let xe=1/0,qe=-1/0;c.forEach(({t:Ie,hz:Me})=>{if(!Me||Me<=0)return;let Ne=pe;for(const Ge of a)for(const Je of Ge)Ie>=Je.startTime&&Ie<=Je.startTime+Je.duration&&(Ne=Je.pitch);const Be=Qi(Me,Ne);Be<xe&&(xe=Be),Be>qe&&(qe=Be)}),xe!==1/0&&qe!==-1/0&&(xe<ke&&(ke=Math.floor(xe-2)),qe>ie&&(ie=Math.ceil(qe+2)))}(!isFinite(ke)||!isFinite(ie))&&(ke=40,ie=80),ke===ie&&(ke=Math.max(0,ke-6),ie=ie+6);const he=pe=>{const xe=r-ye-10;return ye+xe-(pe-ke)/(ie-ke)*xe},Oe=zr(p||"normal"),Xe=(r-ye-10)/Math.max(1,ie-ke),je=Math.max(10,Math.round(Xe*(1+2*Oe.semitoneTolerance)*.3)),He=Math.max(5,Math.round(je*.45));((pe,xe,qe,Ie,Me,Ne)=>{pe.lineWidth=1;for(let Be=Math.ceil(Me);Be<=Math.floor(Ne);Be++){const Ge=he(Be);pe.strokeStyle=X(Be%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),pe.beginPath(),pe.moveTo(0,Math.round(Ge)+.5),pe.lineTo(xe,Math.round(Ge)+.5),pe.stroke()}})(e,t,r-ye,ye,ke,ie),Pt&&Pt.clearRect(0,0,t,r);const tt=(s-ve)/(ce-ve)*t;let Ze=r*.5,It=!1,ft=!1;const Lt=(pe,xe,qe,Ie,Me,Ne,Be=0)=>{const Ge=(Ee,Fe,ge,Re,Ae,We)=>{const ze=Math.min(We,Re/2,Ae/2);Ee.beginPath(),Ee.moveTo(Fe+ze,ge),Ee.lineTo(Fe+Re-ze,ge),Ee.quadraticCurveTo(Fe+Re,ge,Fe+Re,ge+ze),Ee.lineTo(Fe+Re,ge+Ae-ze),Ee.quadraticCurveTo(Fe+Re,ge+Ae,Fe+Re-ze,ge+Ae),Ee.lineTo(Fe+ze,ge+Ae),Ee.quadraticCurveTo(Fe,ge+Ae,Fe,ge+Ae-ze),Ee.lineTo(Fe,ge+ze),Ee.quadraticCurveTo(Fe,ge,Fe+ze,ge),Ee.closePath()},Je=Math.max(2,je/2);Ie.forEach(Ee=>{if(Ee.startTime+Ee.duration<Me||Ee.startTime>Ne)return;const Fe=(Ee.startTime-Me)/(Ne-Me)*xe,ge=Ee.duration/(Ne-Me)*xe,Re=he(Ee.pitch)-je/2,Ae=[];if(Array.isArray(f)){const We=Ee.startTime+Ee.duration;f.forEach(ze=>{if(ze.pitch!==Ee.pitch||ze.noteStart!=null&&ze.noteEnd!=null&&(Math.abs(ze.noteStart-Ee.startTime)>.01||Math.abs(ze.noteEnd-We)>.01))return;const rt=Math.max(ze.start,Ee.startTime),Ye=Math.min(ze.end,We);if(rt>=Ye)return;const Wt=(rt-Me)/(Ne-Me)*xe,Xt=(Ye-Me)/(Ne-Me)*xe;Ae.push({x1:Wt,x2:Xt,frac:ze.frac})})}if(Ee.isGold){pe.save();const We=m&&m.shadowColor?m.shadowColor:zs,ze=m&&typeof m.glowBlur=="number"?m.glowBlur:Ds;pe.shadowColor=We,pe.shadowBlur=Math.max(4,ze-12),pe.fillStyle=X("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Ge(pe,Fe-1,Re-1,ge+2,je+2,Je),pe.fill(),pe.restore();const rt=Jn("var(--gold-base, #b4af9f)");Tn(pe,Fe,Re,ge,je,z,T.color??rt,T.highlight,T.glow,T.glass,_,T.patternColor,T.patternOnly,B,F),pe.save(),Ge(pe,Fe,Re,ge,je,Je),pe.clip(),pe.globalAlpha=.18,pe.fillStyle=X("var(--nice-color-success, #FFD700)"),pe.fillRect(Fe,Re,ge,Math.max(1,je*.25)),pe.globalAlpha=1,pe.restore(),Ae.length>0&&(pe.save(),Ge(pe,Fe,Re,ge,je,Je),pe.clip(),Ae.forEach(Ye=>{const Wt=Math.max(1,Ye.x2-Ye.x1);Tn(pe,Ye.x1,Re,Wt,je,ee,A.color??"var(--nice-warning, #FFD700)",A.highlight,A.glow,A.glass,re,A.patternColor,A.patternOnly,L,P)}),pe.restore()),Ae.length===0&&(pe.lineWidth=1,pe.strokeStyle=X("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Ge(pe,Fe+.5,Re+.5,ge-1,Math.max(1,je-1),Je),pe.stroke())}else{const We=Jn("var(--note-base, #d1d5db)");Tn(pe,Fe,Re,ge,je,V,I.color??We,I.highlight,I.glow,I.glass,K,I.patternColor,I.patternOnly,C,$),Ae.length>0&&(pe.save(),Ge(pe,Fe,Re,ge,je,Je),pe.clip(),Ae.forEach(ze=>{const rt=Math.max(1,ze.x2-ze.x1);Tn(pe,ze.x1,Re,rt,je,E,M.color??H,M.highlight,M.glow,M.glass,q,M.patternColor,M.patternOnly,D,U)}),pe.restore())}Pt&&(Pt.fillStyle=Se.resolveCssColor("var(--nice-bg, #fff)",Pt.canvas),Pt.fillRect(Fe,Re,ge,je))})};if(a.forEach(pe=>{Lt(e,t,r-ye,pe,ve,ce,ye);for(const xe of pe)if(s>=xe.startTime&&s<=xe.startTime+xe.duration){Ze=he(xe.pitch),It=!0,ft=!!xe.isGold;break}}),!It){let pe=null,xe=null;for(const qe of a)for(const Ie of qe)Ie.startTime>s&&(!pe||Ie.startTime<pe.startTime)&&(pe=Ie),Ie.startTime<=s&&(!xe||Ie.startTime>xe.startTime)&&(xe=Ie);pe?(Ze=he(pe.pitch),ft=!!pe.isGold):xe?(Ze=he(xe.pitch),ft=!!xe.isGold):Ze=r*.5}const dt=G||X("var(--nice-color-accent, #ffcc00)"),fe=1+Math.sin((s||0)*8)*.06,be=He*fe,_e=[];for(const pe of a)for(const xe of pe){if(xe.startTime+xe.duration<ve||xe.startTime>ce)continue;const qe=(xe.startTime-ve)/(ce-ve)*t,Ie=xe.duration/(ce-ve)*t,Me=he(xe.pitch)-je/2,Ne=xe.startTime+xe.duration<=s;_e.push({x:qe,y:Me,w:Ie,h:je,isGold:xe.isGold,isSung:Ne})}if(!Xu(N||"ball",{ctx:e,ballX:tt,ballY:Ze,ballRadius:be,playerColor:dt,ballIsGold:ft,currentTime:s,height:r,visibleNotes:_e})){Rt&&e.drawImage(Rt,0,0),kt&&e.drawImage(kt,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const pe=Math.max(18,be*5),xe=e.createRadialGradient(tt,Ze,0,tt,Ze,pe);if(xe.addColorStop(0,dt),xe.addColorStop(1,"transparent"),e.fillStyle=xe,e.beginPath(),e.arc(tt,Ze,pe,0,Math.PI*2),e.fill(),e.restore(),y&&st&&mt&&(st.save(),st.globalCompositeOperation="source-over",st.globalAlpha=.95,st.fillStyle=dt,st.beginPath(),st.arc(tt,Ze,be+4,0,Math.PI*2),st.fill(),st.restore(),st.save(),st.globalCompositeOperation="destination-in",st.drawImage(mt,0,0),st.restore(),e.drawImage(Rt,0,0)),y&&Ve&&mt)try{const Me=Jn(dt),{h:Ne,s:Be,l:Ge}=rh(Me),Ee=ah(Ne,Math.max(10,Math.round(Be*(typeof h=="number"?h:.25))),Ge,.85);Ve.save(),Ve.globalCompositeOperation="multiply",Ve.globalAlpha=.65,Ve.fillStyle=Ee,Ve.beginPath(),Ve.arc(tt,Ze,Math.max(8,be+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(mt,0,0),Ve.restore(),e.drawImage(kt,0,0)}catch{Ve.save(),Ve.globalCompositeOperation="source-over",Ve.globalAlpha=.6,Ve.fillStyle=dt,Ve.beginPath(),Ve.arc(tt,Ze,Math.max(8,be+6),0,Math.PI*2),Ve.fill(),Ve.restore(),Ve.save(),Ve.globalCompositeOperation="destination-out",Ve.drawImage(mt,0,0),Ve.restore(),e.drawImage(kt,0,0)}const qe=m&&m.shadowColor?m.shadowColor:zs,Ie=m&&typeof m.glowBlur=="number"?m.glowBlur:Ds;e.save(),ft?(e.shadowColor=qe,e.shadowBlur=Ie,e.fillStyle=X("var(--gold-light, #FFF0A8)")):(e.shadowColor=dt,e.shadowBlur=10,e.fillStyle=dt),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(tt,Ze,be,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=X("var(--nice-shadow-md, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(x)&&x.length>0){const pe=Date.now(),xe=m&&typeof m.lifeMs=="number"?m.lifeMs:Zu,qe=(Me,Ne,Be,Ge=5)=>{const Je=Be,Ee=Be*.45;e.beginPath();let Fe=Math.PI/2*3,ge=Me,Re=Ne;const Ae=Math.PI/Ge;e.moveTo(Me,Ne-Je);for(let We=0;We<Ge;We++)ge=Me+Math.cos(Fe)*Je,Re=Ne+Math.sin(Fe)*Je,e.lineTo(ge,Re),Fe+=Ae,ge=Me+Math.cos(Fe)*Ee,Re=Ne+Math.sin(Fe)*Ee,e.lineTo(ge,Re),Fe+=Ae;e.lineTo(Me,Ne-Je),e.closePath()},Ie=Me=>{let Ne=Me>>>0;return()=>(Ne=Ne*1664525+1013904223>>>0,(Ne&2147483647)/2147483647)};x.forEach(Me=>{const Ne=pe-Me.createdAt;if(Ne<0||Ne>xe)return;const Be=Ne/xe,Ge=(Me.noteStart-(s-2))/7*t,Je=he(Me.notePitch),Ee=Ie(Me.seed||Math.floor(Me.createdAt%1e5)),Fe=m&&typeof m.count=="number"?m.count:Qu,ge=m&&typeof m.baseSpeed=="number"?m.baseSpeed:Ju,Re=m&&typeof m.baseSize=="number"?m.baseSize:eh;for(let Ae=0;Ae<Fe;Ae++){const We=Ee(),ze=Ee(),rt=Ae/Fe*Math.PI*2+We*Math.PI*.6+Be*1.5,Ye=6+ge*(1-Be)*(.5+ze*.8),Wt=Ge+Math.cos(rt)*Ye,Xt=Je+Math.sin(rt)*Ye*(.8+We*.6),Mt=Math.max(1,Re*(1-Be)*(.5+ze)),Ss=40+Math.round(20*Ee()),ks=70+Math.round(20*Ee()),qr=Math.max(0,1-Be)*(.9-Ee()*.3),Wc=Math.max(6,Mt*2.6),Vr=nh(Ss,ks,60,Math.round(Wc),(Me.seed||0)+Ae);Vr&&Vr.complete?(e.save(),e.translate(Wt,Xt+4),e.rotate(rt+Be*4+(Ee()-.5)*1.2),e.globalAlpha=qr,e.drawImage(Vr,-Mt/2,-Mt/2,Mt,Mt),e.restore()):(e.save(),e.translate(Wt,Xt+4),e.rotate(rt+Be*4),e.fillStyle=`hsla(${Ss}, ${ks}%, 60%, ${qr})`,e.fillRect(-Mt/2,-Mt/2,Mt,Mt),e.restore()),Ee()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-Be),e.fillStyle=`hsla(${30+Math.round(10*Ee())}, ${60+Math.round(30*Ee())}%, ${70+Math.round(10*Ee())}%, ${qr})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-Be)})`,e.lineWidth=.8,qe(Wt,Xt+4,Mt*(1.4+Ee())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:tt,ballY:Ze,ballIsGold:ft}},Ka=({song:e,currentTime:t,playerRef:r,config:a={},userPitch:s,segmentScores:i,goldBursts:o,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:h="Ziom",score:f=1e4,playerBgColor:p="var(--karaoke-player-bg, #2196f3)",playerCount:y=2,gapDesaturation:m,goldSettings:x,difficultyLevel:v,algorithmLabel:g,algorithmColor:S,latencyMs:b=null,top:k,animationMode:j,karaokeSettings:N=null}=a,R=u.useRef(null),w=u.useRef(null),[M,I]=u.useState({width:600,height:150,top:250,visibleWidth:600}),[A,T]=u.useState(0),O=u.useRef(0),E=u.useRef(null),V=u.useRef(null),ee=u.useRef(null),z=u.useRef(t),q=u.useRef(performance.now()),K=u.useRef(e),re=u.useRef(M),_=u.useRef(s),U=u.useRef(d),$=u.useRef(0),P=u.useRef(!1),F=u.useRef(null),D=u.useRef(null),C=()=>{const L=(e==null?void 0:e.id)??null;if(L!==D.current||!F.current){D.current=L;const B=e.notes.map(ne=>ne.noteLine);F.current=Hn(B,e.bpm??void 0);const G=F.current.reduce((ne,Z)=>ne+Z.length,0),H=F.current.reduce((ne,Z)=>ne+Z.filter(Y=>Y.isGold).length,0),X=F.current.flat().map(ne=>ne.pitch),oe=X.length?Math.min(...X):0,le=X.length?Math.max(...X):0;ca("BARS",`Parsed notes for "${e.title}" — ${F.current.length} verses, ${G} notes (including ${H} golden), pitch range: ${oe}–${le}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:B.length,verseCount:F.current.length,totalNotes:G,goldCount:H,minPitch:oe,maxPitch:le})}return F.current};return u.useEffect(()=>{const L=(G,H,X)=>G+(H-G)*X,B=G=>{V.current===null&&(V.current=G);const H=Math.min(.1,(G-(V.current||G))/1e3);V.current=G;const X=$.current,oe=O.current,le=1-Math.exp(-12*H),ne=Math.abs(oe-X)<.25?oe:L(X,oe,le);Math.abs(ne-X)>1e-4&&(T(ne),$.current=ne,R.current&&(R.current.style.transform=`translateX(${ne}px)`)),E.current=requestAnimationFrame(B)};return E.current=requestAnimationFrame(B),()=>{E.current&&cancelAnimationFrame(E.current),E.current=null,V.current=null}},[]),u.useEffect(()=>{const L=()=>{if(!r.current)return;const B=r.current.getBoundingClientRect(),G=2/Math.max(1,y),H=Math.round(B.width*G),X=Math.round(B.width),oe=H*(150/600);I({width:H,height:oe,top:30,visibleWidth:X})};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[r,y]),u.useEffect(()=>{var X;if(d||!R.current)return;const L=R.current.getContext("2d");if(!L)return;const B=C(),G=t-(e.gap??0)/1e3,H=ha(L,M.width,M.height,B,G,h,f,p,s,e.id,m??void 0,i,v??void 0,d,x??void 0,o,g,S,$.current,M.visibleWidth,l,c,j,N);if(H&&R.current){const oe=M.visibleWidth||(((X=w.current)==null?void 0:X.getBoundingClientRect().width)??M.width),le=M.width;let ne=Math.round(oe/2-H.ballX);const Z=oe-le;ne=Math.max(Z,Math.min(0,ne)),O.current=ne}},[t,e,M,s,d,i,o,j,N]),u.useEffect(()=>{z.current=t,q.current=performance.now()},[t]),u.useEffect(()=>{K.current=e},[e]),u.useEffect(()=>{re.current=M},[M]),u.useEffect(()=>{_.current=s},[s]),u.useEffect(()=>{U.current=d},[d]),u.useEffect(()=>{const L=()=>{var se;const B=R.current,G=K.current,H=re.current;if(!B||!G||!H)return;const X=B.getContext("2d");if(!X)return;const oe=C(),le=Math.min(.5,(performance.now()-q.current)/1e3),Z=(U.current?z.current+le:z.current)-(G.gap??0)/1e3,Y=ha(X,H.width,H.height,oe,Z,h,f,p,_.current,G.id,m??void 0,i,v??void 0,U.current,x??void 0,o,g,S,$.current,H.visibleWidth,l,c,j,N);if(Y){const ae=H.visibleWidth||(((se=w.current)==null?void 0:se.getBoundingClientRect().width)??H.width),ue=H.width;let J=Math.round(ae/2-Y.ballX);const de=ae-ue;J=Math.max(de,Math.min(0,J)),O.current=J}};if(d){P.current||(P.current=!0,ca("BARS",`Drawing bars in RAF loop — canvas: ${re.current.width}×${re.current.height}px, player: ${h}`,{canvasSize:re.current}));const B=()=>{L(),ee.current=requestAnimationFrame(B)};return ee.current=requestAnimationFrame(B),()=>{ee.current&&cancelAnimationFrame(ee.current),ee.current=null}}P.current=!1},[d,h,f,p,m,i,v,x,o,j,N]),n.jsxs("div",{ref:w,style:{position:"absolute",left:"50%",top:`${k??M.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:M.visibleWidth,height:M.height,overflow:"hidden"},children:[n.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} 50% { transform: scale(1.08); box-shadow: 0 8px 18px var(--nice-overlay-30, rgba(0,0,0,0.32));} 100% { transform: scale(1); box-shadow: 0 4px 10px var(--nice-overlay-20, rgba(0, 0, 0, 0.2));} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),n.jsx("div",{style:{position:"absolute",right:8,top:6,zIndex:40,pointerEvents:"none",display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--nice-text-inverse, #fff)"},children:typeof b<"u"&&b!==null?(()=>{const L=b,B=L<=120?"var(--latency-good, #10b981)":L<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",G=`${L}ms`;return n.jsxs("div",{className:L>250?"av-latency-pulse":"",style:{background:B,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdStopwatch,{size:12}),n.jsx("span",{children:G})]})})():n.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px var(--nice-overlay-35, rgba(0, 0, 0, 0.35))",minWidth:44,textAlign:"center"},children:"—"})}),n.jsx("canvas",{ref:R,width:M.width,height:M.height,role:"img","aria-label":`Pitch timeline for ${h??"player"}. Score: ${f??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${A}px)`,willChange:"transform"}})]})},po="/textures/seamless/256x256";function At(e,t,r){return{name:e,icon:r,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${po}/${e}/Photoreal_${e}_${i}-512x512.png`}})}}function Dt(e,t,r){return{name:e,icon:r,entries:Array.from({length:t},(a,s)=>{const i=String(s+1).padStart(2,"0");return{label:`${e} ${i}`,url:`${po}/${e}/${e}_${i}-256x256.png`}})}}const Ya=[At("Fire",8,"fire"),At("Metal",8,"metal"),At("Ice",8,"ice"),At("Stone",8,"stone"),At("Wood",8,"wood"),At("Tile",8,"tile"),At("Concrete",8,"concrete"),At("Trees",8,"trees"),At("Grass",8,"grass"),Dt("Wall",24,"wall"),Dt("Rust",24,"rust"),Dt("Woven",24,"woven"),Dt("Ground",24,"ground"),Dt("Pebbles",24,"pebbles"),Dt("Plant",24,"plant"),Dt("Roof",24,"roof"),Dt("Misc",24,"misc")],fo=Ya.flatMap(e=>e.entries);function ch(e){return fo.find(t=>t.url===e)}const dh={color:"var(--nice-primary, #2196f3)",highlight:"var(--nice-bg, #fff)",glow:0,capStyle:"flat",pattern:null,texture:null},uh={fire:W.NtdFire,metal:W.NtdSettings,ice:W.NtdSnowflake,stone:W.NtdMountain,wood:W.NtdTree,tile:W.NtdGrid,concrete:W.NtdLayers,trees:W.NtdTree,grass:W.NtdLeaf,wall:W.NtdHome,rust:W.NtdCircle,woven:W.NtdGrid,ground:W.NtdMountain,pebbles:W.NtdDroplet,plant:W.NtdLeaf,roof:W.NtdHome,misc:W.NtdPalette},hh=({icon:e})=>{const t=uh[e];return t?n.jsx(t,{size:14}):n.jsx(n.Fragment,{children:e})},mo=({fill:e=dh,onChange:t=()=>{},previewColor:r="var(--nice-primary, #2196f3)",accentColor:a="var(--nice-primary, #0d6efd)",width:s,height:i})=>{const{t:o}=Te(),[l,c]=u.useState(null),d=(g,S)=>{t({...e,[g]:S})},h=u.useMemo(()=>{const g=e.color||r||"var(--nice-primary, #2196f3)";return(S,b,k)=>{const j=Wn.find(R=>R.name===S)||Wn[0],N=b?$r.find(R=>R.name===b)??null:null;return co({width:80,height:22,capStyle:j,color:g,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:N,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:k??null,textureScale:e.textureScale})}},[e,r]),f=`2px solid ${a}`,p=a==="var(--nice-warning-dark, #d4a017)"?"var(--nice-warning-bg, #fff8e1)":"var(--nice-info-bg, #e7f1ff)",y=u.useRef(null),m=u.useRef(null),x=u.useCallback((g,S)=>{g.current&&g.current.scrollBy({left:S*180,behavior:"smooth"})},[]),v={position:"absolute",top:0,width:28,height:"100%",border:"none",cursor:"pointer",zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"var(--nice-text-on-primary, #ccc)",background:"linear-gradient(90deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"};return n.jsxs("div",{style:{padding:"4px 0"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[n.jsx(at.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:o("playerForm.barColor","Color")}),n.jsx(at.Form.Check,{type:"checkbox",id:`bar-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.color,onChange:g=>d("color",g.target.checked?null:r||"var(--nice-primary, #2196f3)"),className:"mb-0"}),e.color&&n.jsx("input",{type:"color",value:e.color,onChange:g=>d("color",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),n.jsx(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:o("playerForm.capShape","Cap shape")}),n.jsxs("div",{style:{position:"relative",marginBottom:10},children:[n.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(y,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:n.jsx(W.NtdChevronLeft,{size:16})}),n.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(y,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:n.jsx(W.NtdChevronRight,{size:16})}),n.jsx("div",{ref:y,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:Wn.map(g=>{const S=e.capStyleName===g.name;return n.jsx("div",{title:g.name,onClick:()=>d("capStyleName",g.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(g.name,null)}},g.name)})})]}),n.jsx(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:o("playerForm.pattern","Pattern")}),n.jsxs("div",{style:{position:"relative",marginBottom:10},children:[n.jsx("button",{type:"button",style:{...v,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>x(m,-1),"aria-label":o("playerForm.scrollLeft","Scroll left"),children:n.jsx(W.NtdChevronLeft,{size:16})}),n.jsx("button",{type:"button",style:{...v,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, var(--nice-overlay-90, rgba(30, 30, 30, 0.9)) 60%, transparent)"},onClick:()=>x(m,1),"aria-label":o("playerForm.scrollRight","Scroll right"),children:n.jsx(W.NtdChevronRight,{size:16})}),n.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[n.jsx("div",{title:"None",onClick:()=>d("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid var(--nice-border-color, #555)":f,borderRadius:6,padding:"3px 8px",background:e.patternName?"var(--nice-text, #222)":p,fontSize:12,lineHeight:"22px",color:"var(--nice-text-inverse, #ccc)"},children:"—"}),$r.map(g=>{const S=e.patternName===g.name;return n.jsx("div",{title:g.name,onClick:()=>d("patternName",g.name),style:{cursor:"pointer",flexShrink:0,border:S?f:"1px solid var(--nice-border-color, #555)",borderRadius:6,padding:3,background:S?p:"var(--nice-bg-secondary, #222)"},dangerouslySetInnerHTML:{__html:h(e.capStyleName,g.name)}},g.name)})]})]}),n.jsx(at.Form.Check,{type:"switch",id:`bar-pattern-only-${a}`,label:o("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:g=>d("patternOnly",g.target.checked),className:"mb-2"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[n.jsx(at.Form.Label,{className:"mb-0",style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:o("playerForm.patternColor","Pattern color")}),n.jsx(at.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${a}`,label:o("playerForm.auto","Auto"),checked:!e.patternColor,onChange:g=>d("patternColor",g.target.checked?null:r||"var(--nice-bg, #fff)"),className:"mb-0"}),e.patternColor&&n.jsx("input",{type:"color",value:e.patternColor,onChange:g=>d("patternColor",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&n.jsxs(n.Fragment,{children:[n.jsxs(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:[o("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),n.jsx(at.Form.Range,{min:0,max:100,value:e.highlight,onChange:g=>d("highlight",parseInt(g.target.value)),className:"mb-2"}),n.jsxs(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:[o("playerForm.glow","Glow"),": ",e.glow,"%"]}),n.jsx(at.Form.Range,{min:0,max:100,value:e.glow,onChange:g=>d("glow",parseInt(g.target.value)),className:"mb-2"})]}),n.jsxs(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:[o("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),n.jsx(at.Form.Range,{min:0,max:100,value:e.glass,onChange:g=>d("glass",parseInt(g.target.value)),className:"mb-2"}),n.jsx(at.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"var(--nice-text-secondary, #ccc)"},children:o("playerForm.texture","Texture")}),n.jsxs("div",{style:{marginBottom:6},children:[n.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[n.jsx("button",{type:"button",className:`btn btn-sm ${e.textureUrl?"btn-outline-secondary":"btn-primary"}`,onClick:()=>{d("textureUrl",null),c(null)},children:o("playerForm.texNone","None")}),Ya.map(g=>n.jsx("button",{type:"button",className:`btn btn-sm ${(l==null?void 0:l.name)===g.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>c(S=>(S==null?void 0:S.name)===g.name?null:g),title:g.name,children:n.jsx(hh,{icon:g.icon})},g.name))]}),l&&n.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid var(--nice-border, #dee2e6)",borderRadius:6,background:"var(--nice-bg-secondary, #f8f9fa)"},children:l.entries.map(g=>{const S=e.textureUrl===g.url;return n.jsx("div",{title:g.label,onClick:()=>d("textureUrl",S?null:g.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:S?`3px solid ${a}`:"1px solid var(--nice-text-muted, #bbb)",backgroundImage:`url(${g.url})`,backgroundSize:"cover",boxShadow:S?`0 0 6px ${a}`:void 0}},g.url)})}),e.textureUrl&&n.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[n.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid var(--nice-border-color, #aaa)"}}),n.jsx("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #666)"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&n.jsxs(n.Fragment,{children:[n.jsxs(at.Form.Label,{style:{fontSize:13,color:"var(--nice-text-secondary, #ccc)"},children:[o("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"×"]}),n.jsx(at.Form.Range,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:g=>d("textureScale",parseInt(g.target.value)/100),className:"mb-2"})]})]})},it=ot.scoped("AudioPitchAnalyzer");function go({onSegments:e,defaultCompareAll:t=!1,externalFile:r=null,postPitch:a,postLibrosaPitchTrack:s}){const{t:i}=Te(),[o,l]=u.useState("pitchy"),[c,d]=u.useState(null),[h,f]=u.useState(t),[p,y]=u.useState({}),[m,x]=u.useState({}),[v,g]=u.useState([]),[S,b]=u.useState([]),[k,j]=u.useState(!1),[N,R]=u.useState(null),[w]=u.useState(null),[M]=u.useState(null),[I,A]=u.useState(null),T=u.useRef(null);function O(_){try{if(_ instanceof Error){let $=`${_.message}
40
+ ${_.stack??""}`;const P=_;if(P!=null&&P.attemptedUrls)try{$+=`
41
+ Attempted URLs: ${Array.isArray(P.attemptedUrls)?P.attemptedUrls.join(", "):String(P.attemptedUrls)}`}catch{$+=`
42
+ Attempted URLs: ${String(P.attemptedUrls)}`}return $}const U=_;return U!=null&&U.attemptedUrls?`Error: ${String(U.message??U)}
43
+ Attempted URLs: ${Array.isArray(U.attemptedUrls)?U.attemptedUrls.join(", "):String(U.attemptedUrls)}`:String(_)}catch{return"Unknown error"}}function E(_){if(!_||_<=0)return null;const U=12*Math.log2(_/440)+69;return Math.round(U-12)}async function V(_){var $;const U=($=_.target.files)==null?void 0:$[0];U&&await ee(U,h)}async function ee(_,U){R(null),b([]),j(!0);try{const $=await _.arrayBuffer(),P=window.AudioContext??window.webkitAudioContext,D=await new P().decodeAudioData($),C=D.getChannelData(0);d(C);const L=D.sampleRate,B=Math.floor(L*.1),G=B,H=()=>{const Y=[],se=ia.PitchDetector.forFloat32Array(B);for(let ae=0;ae<C.length-B;ae+=G){const ue=C.slice(ae,ae+B),[J,de]=se.findPitch(ue,L),me=E(J);me&&J>50&&J<2e3&&de>.7&&Y.push({start:ae/L,duration:B/L,pitch:me,freq:J})}return Y},X=()=>{const Y=[];for(let se=0;se<C.length-B;se+=G){const ae=C.slice(se,se+B),ue=q(ae,L),J=E(ue);J&&ue>50&&ue<2e3&&Y.push({start:se/L,duration:B/L,pitch:J,freq:ue})}return Y};if(U){j(!0),R(null);const Y={};try{const se={};try{Y.pitchy=H(),se.pitchy=null}catch(ae){Y.pitchy=[],se.pitchy=O(ae),it.warn("pitchy failed",ae)}try{Y["ultrastar-wp"]=X(),se["ultrastar-wp"]=null}catch(ae){Y["ultrastar-wp"]=[],se["ultrastar-wp"]=O(ae),it.warn("ultrastar-wp failed",ae)}Y.aubio=[],se.aubio="disabled";try{if(!a)throw new Error("CREPE backend not configured");const ue=(await a(_)).track??[];Y.crepe=ue.map((J,de)=>{var me;return{start:J.t,duration:(me=ue[de+1])!=null&&me.t?ue[de+1].t-J.t:.1,pitch:E(J.hz)??0,freq:J.hz}}),se.crepe=null}catch(ae){Y.crepe=[],se.crepe=O(ae),it.warn("crepe failed",ae)}try{if(!s)throw new Error("Librosa backend not configured");const ue=(await s(new File([_],_.name,{type:_.type}))).track??[];Y.librosa=ue.map((J,de)=>{var me;return{start:J.t,duration:(me=ue[de+1])!=null&&me.t?ue[de+1].t-J.t:.1,pitch:E(J.hz)??0,freq:J.hz}}),se.librosa=null}catch(ae){Y.librosa=[],se.librosa=O(ae),it.warn("librosa failed",ae)}x(se),y(Y),b(Y[o]??[])}catch(se){it.error("compareAll overall failed",se);const ae=se instanceof Error?se.message:String(se);R(i("audioPitch.errorComparing","Error comparing algorithms: ")+ae)}finally{j(!1)}return}const oe=[],le=[];let ne=0;if(o==="pitchy"){const Y=ia.PitchDetector.forFloat32Array(B);for(let se=0;se<C.length-B;se+=G){const ae=C.slice(se,se+B);let ue=0;for(let ve=0;ve<ae.length;ve++)ue+=ae[ve]*ae[ve];ue=Math.sqrt(ue/ae.length),le.push(ue);const[J,de]=Y.findPitch(ae,L),me=E(J);me&&J>50&&J<2e3&&de>.7&&(oe.push({start:se/L,duration:B/L,pitch:me,freq:J}),ne++)}}else if(o==="crepe")try{if(!a)throw new Error("CREPE backend not configured");const Y=await a(_);if(!Y.track||Y.track.length===0)R(i("audioPitch.crepeNoNotes","CREPE detected no notes")),it.warn("Crepe: No notes detected in audio file.");else{const se=Y.track.map((ae,ue)=>{const J=E(ae.hz);return J&&ae.hz>50&&ae.hz<2e3?{start:ae.t,duration:ue<Y.track.length-1?Y.track[ue+1].t-ae.t:.1,pitch:J,freq:ae.hz}:null}).filter(ae=>ae!==null);if(b(se),e)try{e(se)}catch(ae){it.error("Error in onSegments:",ae)}g([]),d(null);return}}catch(Y){R(i("audioPitch.crepeBackendError","CREPE backend error")),A(O(Y)),it.error("Crepe: Error calling backend:",Y)}else if(o==="librosa")try{await z(_),g([]),d(null);return}catch(Y){R(i("audioPitch.librosaBackendError","Librosa backend error")),A(O(Y)),it.error("Librosa: Error calling backend:",Y)}else if(o==="ultrastar-wp")for(let Y=0;Y<C.length-B;Y+=G){const se=C.slice(Y,Y+B);let ae=0;for(let de=0;de<se.length;de++)ae+=se[de]*se[de];ae=Math.sqrt(ae/se.length),le.push(ae);const ue=q(se,L),J=E(ue);J&&ue>50&&ue<2e3&&(oe.push({start:Y/L,duration:B/L,pitch:J,freq:ue}),ne++)}g(le);const Z=K(oe);if(b(Z),e)try{e(Z)}catch(Y){it.error("Error in onSegments:",Y)}Z.length===0&&o!=="crepe"&&(R(i("audioPitch.noNotesDetected","No notes detected")),it.warn("No notes detected in audio file."))}catch($){R(i("audioPitch.errorAnalyzing","Error analyzing the file: ")+($ instanceof Error?$.message:String($))),A(O($)),it.error("Error analyzing audio file:",$)}finally{j(!1)}}u.useEffect(()=>{r&&ee(r,!0)},[r]);async function z(_){try{if(!s)throw new Error("Librosa backend not configured");const U=new File([_],"capture.wav",{type:"audio/wav"}),P=((await s(U)).track??[]).map(F=>({t:F.t,hz:F.hz}));if(e){const F=P.map((D,C)=>{var G;const L=((G=P[C+1])==null?void 0:G.t)??D.t+.1,B=E(D.hz)??0;return{start:D.t,duration:Math.max(.05,L-D.t),pitch:B,freq:D.hz}});e(F),b(F)}}catch(U){it.warn("Librosa analysis failed, falling back to local detectors",U);const P=(typeof U=="object"&&U!==null?U:{}).attemptedUrls;P&&it.error("Librosa attempted URLs:",P);const F=P?Array.isArray(P)?P.join(", "):String(P):null,D=U instanceof Error?U.message:String(U);R(i("audioPitch.librosaBackendError","Librosa backend error")+": "+D+(F?" (attempted: "+F+")":"")),A(O(U))}}function q(_,U){const F=Math.floor(U/50),D=Math.max(2,Math.floor(U/2e3));let C=0;for(let H=0;H<_.length;H++)C+=_[H]*_[H];if(C<=1e-8)return 0;let L=-1,B=0;const G=1e-10;for(let H=D;H<=Math.min(F,_.length-2);H++){let X=0;const oe=_.length-H;for(let ne=0;ne<oe;ne++)X+=_[ne]*_[ne+H];const le=X/(oe+G)/(C/_.length+G);le>B&&(B=le,L=H)}return L>0&&B>.01?U/L:0}function K(_){if(_.length===0)return[];const U=[];let $=_[0];for(let P=1;P<_.length;P++){const F=_[P];F.pitch===$.pitch&&Math.abs(F.freq-$.freq)<1?$.duration+=F.duration:(U.push($),$=F)}return U.push($),U}function re(){try{const _=Object.keys(p).length>0?Object.keys(p):["pitchy","ultrastar-wp","aubio","crepe","librosa"],U=(()=>{let ne=0;for(const Z of _){const Y=p[Z]??[];for(const se of Y)ne=Math.max(ne,se.start+(se.duration||0))}return ne||0})(),$=(ne,Z)=>!ne||!Z?1/0:1200*Math.log2(ne/Z),P=(ne,Z)=>{if(!ne||!Z)return!1;const Y=Math.round(Math.log2(Z/ne)),se=ne*Math.pow(2,Y),ae=Math.abs($(se,Z));return Math.abs(Y)>=1&&ae<50},F=ne=>{const Z={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!ne||ne.length===0)return Z;Z.count=ne.length,Z.totalDur=ne.reduce((ue,J)=>ue+(J.duration||0),0);const Y=ne.map(ue=>ue.freq).filter(Boolean);if(Y.length===0)return Z;const se=Y.reduce((ue,J)=>ue+J,0)/Y.length,ae=Y.reduce((ue,J)=>ue+(J-se)*(J-se),0)/Y.length;return Z.meanFreq=se,Z.stdFreq=Math.sqrt(ae||0),Z.meanDur=Z.totalDur/Z.count,Z.voicedFraction=U>0?Z.totalDur/U:null,Z},D=(ne,Z)=>{let Y=0,se=0;const ae=[];for(const J of ne){const de=J.start,me=J.start+(J.duration||.05);let ve=null,ce=0;for(const ye of Z){const ke=ye.start,ie=ye.start+(ye.duration||.05),he=Math.max(0,Math.min(me,ie)-Math.max(de,ke));he>ce&&(ce=he,ve=ye)}if(ve&&ce>0){const ye=Math.abs($(J.freq,ve.freq));ae.push(ye),ye<50&&Y++,P(J.freq,ve.freq)&&se++}}const ue=ae.length?ae.reduce((J,de)=>J+de,0)/ae.length:null;return{matches:Y,compared:ne.length,meanCents:ue,octaveErrors:se}},C=[];C.push("# AudioPitchAnalyzer — Comparative Report"),C.push(`Generated: ${new Date().toISOString()}`),C.push(""),C.push("## Summary"),C.push(`- Selected algorithm in UI: **${o}**`),C.push(`- Total analyzed duration (approx): **${U.toFixed(3)} s**`),C.push(""),C.push("## Per-algorithm statistics"),C.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),C.push("|---|---:|---:|---:|---:|---:|---:|");const L={};for(const ne of _){const Z=p[ne]??[],Y=F(Z);L[ne]=Y,C.push(`| ${ne} | ${Y.count||0} | ${(Y.totalDur||0).toFixed(3)} | ${Y.voicedFraction!==null?(Y.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${Y.meanFreq?Y.meanFreq.toFixed(1):"N/A"} | ${Y.stdFreq?Y.stdFreq.toFixed(1):"N/A"} | ${Y.meanDur?Y.meanDur.toFixed(3):"N/A"} |`)}C.push(""),C.push("## Pairwise agreement (reference -> test)");const B=_.includes("crepe")?"crepe":_.includes("librosa")?"librosa":_.includes("pitchy")?"pitchy":_[0];C.push(`Reference algorithm: **${B}**`),C.push(""),C.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),C.push("|---|---:|---:|---:|---:|---:|");for(const ne of _){if(ne===B)continue;const Z=D(p[B]??[],p[ne]??[]),Y=Z.compared?(Z.matches/Z.compared*100).toFixed(1)+"%":"N/A";C.push(`| ${B} -> ${ne} | ${Z.matches} | ${Z.compared} | ${Y} | ${Z.meanCents!==null?Z.meanCents.toFixed(1):"N/A"} | ${Z.octaveErrors} |`)}C.push(""),C.push("## Observations and analysis"),C.push("- The table above gives an overview of voiced coverage and per-algorithm mean frequencies. High voiced fraction indicates the algorithm detected many tonal regions; low fraction indicates conservative voicing or failures in noisy/quiet sections."),C.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),C.push("- Mean cents difference (reference vs test) indicates systematic tuning offsets or frequency bias; values <50 cents are generally acceptable for musical content, but for scoring you may want <20 cents."),C.push("");for(const ne of _){C.push(`### ${ne}`);const Z=L[ne];C.push(`- Segments: ${Z.count||0}`),C.push(`- Total voiced (s): ${(Z.totalDur||0).toFixed(3)}`),C.push(`- Voiced fraction: ${Z.voicedFraction!==null?(Z.voicedFraction*100).toFixed(1)+"%":"N/A"}`),C.push(`- Mean frequency: ${Z.meanFreq?Z.meanFreq.toFixed(2)+" Hz":"N/A"}`),C.push(`- Std frequency: ${Z.stdFreq?Z.stdFreq.toFixed(2)+" Hz":"N/A"}`),C.push("")}C.push("## Conclusions & recommendation");const G=[];for(const ne of _){if(ne===B){G.push({alg:ne,score:100});continue}const Z=D(p[B]??[],p[ne]??[]),Y=Z.compared?Z.matches/Z.compared:0,se=Z.compared?Z.octaveErrors/Z.compared:0,ae=Y-se*.5;G.push({alg:ne,score:ae})}G.sort((ne,Z)=>Z.score-ne.score),C.push(`- Based on this recording, recommended authoritative detector: **${G[0].alg}** (best agreement with reference).`),C.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),C.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),C.push(""),C.push("## Raw data (per-algorithm segments)");for(const ne of _){const Z=p[ne]??[];C.push(`### ${ne} — ${Z.length} segments`);for(const se of Z)C.push(`- ${se.start.toFixed(3)} .. ${(se.start+(se.duration||0)).toFixed(3)} : ${se.freq.toFixed(2)} Hz (pitch ${se.pitch})`);const Y=m[ne];Y&&C.push(`- Error: ${Y}`),C.push("")}const H=C.join(`
44
+ `),X=new Blob([H],{type:"text/markdown;charset=utf-8"}),oe=URL.createObjectURL(X),le=document.createElement("a");le.href=oe,le.download="audiopitch_scientific_report_"+(r?r.name:"capture")+".md",document.body.appendChild(le),le.click(),le.remove(),URL.revokeObjectURL(oe)}catch(_){it.error("generateScientificReport error",_),it.warn(i("audioPitch.reportError","Could not generate the report: ")+String(_))}}return n.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid var(--nice-border, #ccc)",borderRadius:8},children:[n.jsx("h3",{children:i("audioPitch.title","Pitch analysis")}),n.jsxs("div",{style:{marginBottom:12},children:[n.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:i("audioPitch.algorithm","Algorithm")}),n.jsxs("select",{id:"pitch-algorithm-select",value:o,onChange:_=>l(_.target.value),style:{marginRight:16},children:[n.jsx("option",{value:"ultrastar-wp",children:i("audioPitch.algorithmUltrastarWp","Ultrastar WP (autocorrelation)")}),n.jsx("option",{value:"crepe",children:"crepe (AI)"}),n.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),n.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),n.jsxs("label",{style:{marginRight:8},children:[n.jsx("input",{type:"checkbox",checked:h,onChange:_=>f(_.target.checked)})," ",i("audioPitch.compareAll","Compare all algorithms")]}),n.jsx("input",{type:"file",accept:"audio/*",ref:T,onChange:V,disabled:k})]}),k&&n.jsx("div",{children:i("audioPitch.analyzing","Analyzing...")}),n.jsxs("div",{style:{marginTop:8},children:[n.jsx("b",{children:i("audioPitch.method","Method:")})," ",o]}),N&&n.jsxs("div",{style:{color:"red",marginTop:8},children:[n.jsxs("b",{children:[o,": "]}),n.jsx("div",{children:N}),I&&n.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:I})]}),w&&n.jsxs("div",{style:{marginTop:12},children:[n.jsx("b",{children:"Aubio diagnostics"}),n.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:w}),M&&n.jsxs("div",{style:{marginTop:8},children:[n.jsx("b",{children:"Probe:"})," ",M]})]}),(Object.keys(p).length>0||Object.keys(m).length>0)&&n.jsxs("div",{style:{marginTop:12},children:[n.jsx("button",{onClick:()=>re(),children:i("audioPitch.downloadReport","Download report")}),Object.entries(m).length>0&&n.jsxs("div",{style:{marginTop:8},children:[n.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(m).filter(([_,U])=>U).map(([_,U])=>n.jsxs("div",{style:{marginTop:6},children:[n.jsxs("b",{children:[_,":"]}),n.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-danger-light, #f88)",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:U})]},_))]})]}),S.length>0&&n.jsxs("div",{style:{marginTop:16},children:[n.jsx("b",{children:i("audioPitch.resultUltrastar","Result (UltraStar format):")}),n.jsxs("pre",{style:{background:"var(--nice-text, #222)",color:"var(--nice-bg, #fff)",padding:8,borderRadius:4},children:[S.map(_=>`: ${Math.round(_.start*10)} ${Math.round(_.duration*10)} ${_.pitch} [${_.freq.toFixed(1)} Hz]`).join(`
45
45
  `),`
46
- -`]})]}),c&&c.length>0&&r.jsxs("div",{style:{marginTop:24},children:[r.jsx("b",{children:i("audioPitch.waveformRms")}),r.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-text, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:D=>{if(!D)return;const W=D.getContext("2d");if(W){W.clearRect(0,0,600,100),W.strokeStyle="var(--nice-info, #0ff)",W.beginPath();for(let j=0;j<c.length;j+=Math.ceil(c.length/600)){const F=j/c.length*600,I=50-c[j]*48;j===0?W.moveTo(F,I):W.lineTo(F,I)}if(W.stroke(),x.length>0){W.strokeStyle="var(--nice-warning, #ff0)",W.beginPath();for(let j=0;j<x.length;j++){const F=j/x.length*600,I=100-x[j]*90;j===0?W.moveTo(F,I):W.lineTo(F,I)}W.stroke()}}}}),r.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[r.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:"Waveform"}),"  | "," ",r.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!S&&k.length===0&&!R&&r.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:r.jsx("i",{children:i("audioPitch.noNotesDetected")})}),h&&Object.keys(f).length>0&&r.jsxs("div",{style:{marginTop:16},children:[r.jsx("h4",{children:i("audioPitch.algorithmComparison")}),Object.entries(f).map(([D,W])=>r.jsxs("div",{style:{marginBottom:12},children:[r.jsx("b",{children:D}),": ",i("audioPitch.detectedSegments")," ",W.length,r.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-border, #ddd)",padding:8,borderRadius:4,marginTop:8},children:W.map(j=>`: ${Math.round(j.start*10)} ${Math.round(j.duration*10)} ${j.pitch} [${j.freq.toFixed(1)} Hz]`).join(`
47
- `)})]},D))]})]})}const Dt=1e4,Os=5e3;function Hr(e,t=.35){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!n)return e;const a=Math.min(255,Math.round(parseInt(n[1],16)+(255-parseInt(n[1],16))*t)),s=Math.min(255,Math.round(parseInt(n[2],16)+(255-parseInt(n[2],16))*t)),i=Math.min(255,Math.round(parseInt(n[3],16)+(255-parseInt(n[3],16))*t));return`rgb(${a},${s},${i})`}const lh=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],ch=({entry:e,rank:t,animDelay:n})=>{const[a,s]=d.useState(0),[i,o]=d.useState(0),[l,c]=d.useState(0),[u,h]=d.useState(0),p=Math.min(e.classicScore,Dt),f=Math.min(e.bonusScore,Dt),y=p/Dt*Os,m=f>0?f/Dt*Os:0;return d.useEffect(()=>{let v,x=null;const g=Math.max(y,400),k=Math.max(m,m>0?300:0),b=S=>{x===null&&(x=S);const M=S-x-n;if(M<0){v=requestAnimationFrame(b);return}if(M<=g){const R=Math.min(1,M/g),N=1-Math.pow(1-R,3);s(Math.min(N*(p/Dt)*100,100)),c(Math.round(N*e.classicScore)),v=requestAnimationFrame(b);return}if(s(Math.min(p/Dt*100,100)),c(e.classicScore),k>0){const R=M-g;if(R<=k){const N=Math.min(1,R/k),C=1-Math.pow(1-N,3);o(Math.min(C*(f/Dt)*100,100)),h(Math.round(C*e.bonusScore)),v=requestAnimationFrame(b);return}o(Math.min(f/Dt*100,100)),h(e.bonusScore)}};return v=requestAnimationFrame(b),()=>cancelAnimationFrame(v)},[e.classicScore,e.bonusScore,y,m,n]),r.jsxs("div",{className:"karaoke-summary-bar",children:[r.jsx("span",{className:"karaoke-summary-bar-rank",children:t<=3?r.jsx(se.NtdMedal,{size:18,primaryColor:lh[t-1]}):`#${t}`}),r.jsx("span",{className:"karaoke-summary-bar-name",style:{color:e.color},children:e.name}),r.jsxs("div",{className:"karaoke-summary-bar-track",children:[e.bonusScore>0&&r.jsx("div",{className:"karaoke-summary-bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Hr(e.color,.45)}}),r.jsx("div",{className:"karaoke-summary-bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Hr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),r.jsxs("div",{className:"karaoke-summary-bar-text",children:[l.toLocaleString(),u>0&&r.jsxs("span",{className:"karaoke-summary-bar-text-bonus",style:{color:Hr(e.color,.5)},children:["+",u.toLocaleString()]})]})]}),r.jsx("span",{className:"karaoke-summary-bar-total",children:(l+u).toLocaleString()})]})},Bs=({title:e,entries:t,highlightNames:n,playerColorMap:a})=>r.jsxs("div",{className:"karaoke-summary-rank",children:[r.jsx("h4",{className:"karaoke-summary-rank-title",children:e}),r.jsx("table",{className:"karaoke-summary-rank-table",children:r.jsx("tbody",{children:t.map((s,i)=>{const o=n.has(s.name),l=a.get(s.name);return r.jsxs("tr",{className:o?"karaoke-summary-rank-row karaoke-summary-rank-row--hl":"karaoke-summary-rank-row",children:[r.jsx("td",{className:`karaoke-summary-rank-pos${i<3?" karaoke-summary-rank-pos--top":""}`,children:s.rank}),r.jsxs("td",{className:"karaoke-summary-rank-name",style:l?{color:l}:void 0,children:[o&&"● ",s.name]}),r.jsx("td",{className:"karaoke-summary-rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Ka=({uploadedSong:e,playerScores:t,topSingings:n,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:u,accessMode:h,"data-testid":p})=>{const[f,y]=d.useState(!1),m=d.useMemo(()=>[...t].sort((S,M)=>M.totalScore-S.totalScore),[t]),v=d.useMemo(()=>{const S=new Map;for(const M of t)S.set(M.name,M.color);return S},[t]),x=d.useMemo(()=>new Set(t.map(S=>S.name)),[t]),g=d.useMemo(()=>m.map((S,M)=>({rank:M+1,name:S.name,score:S.totalScore,color:S.color})),[m]),k=d.useMemo(()=>{const S=n.map(R=>({name:R.playerName,score:R.score})),M=new Set;for(const R of m)M.has(R.id)||(M.add(R.id),S.push({name:R.name,score:R.totalScore}));return S.sort((R,N)=>N.score-R.score),S.slice(0,10).map((R,N)=>({rank:N+1,name:R.name,score:R.score}))},[n,m]),b=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:r.jsxs("div",{className:`karaoke-summary-overlay${l?` ${l}`:""}`,style:c,id:u,"data-testid":p,children:[r.jsxs("div",{className:"karaoke-summary-card",children:[r.jsx("h1",{className:"karaoke-summary-title",children:b}),r.jsx("div",{className:"karaoke-summary-bars",children:m.length===0?r.jsx("div",{className:"karaoke-summary-empty",children:i("karaokeSummary.noScores","No scores")}):m.map((S,M)=>r.jsx(ch,{entry:S,rank:M+1,animDelay:M*300},S.id))}),(m.length>1||n.length>0)&&r.jsxs("div",{className:"karaoke-summary-ranks",children:[m.length>1&&r.jsx(Bs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:g,highlightNames:x,playerColorMap:v}),n.length>0&&r.jsx(Bs,{title:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:k,highlightNames:x,playerColorMap:v})]}),r.jsxs("div",{className:"karaoke-summary-actions",children:[o&&r.jsxs("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--report",onClick:()=>y(!0),children:[r.jsx(se.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),r.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),f&&(o==null?void 0:o(()=>y(!1)))]})},dh=it.scoped("GenericPlayer"),uh=e=>/youtu(\.be|be\.com)/i.test(e),go=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),hh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),ph=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),n=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&uh(o.url)))??null;if(n)return n;const a=t("hls")||e.sources.find(o=>o.url&&go(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&hh(o.url))||null;return s||(e.sources[0]??null)},Pr=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},fh=[.25,.5,.75,1,1.25,1.5,1.75,2],Ya=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:u="full",compactNextCount:h=3,progressBarPosition:p="inline",loop:f=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:v=!1,repeatMode:x="none",playbackSpeed:g=1,abLoop:k=null,onRepeatModeChange:b,onShuffleChange:S,onSpeedChange:M,sleepTimer:R=0,onSleepTimerExpired:N})=>{const{t:C}=Te(),[w,O]=d.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),$=e[w],E=d.useMemo(()=>ph($),[$]),[_,L]=d.useState(!1),[U,Z]=d.useState(0),[A,q]=d.useState(0),[H,re]=d.useState(.9),[D,W]=d.useState(null),[j,F]=d.useState(null),I=d.useRef(null),[P,T]=d.useState(v),[z,B]=d.useState(x),[G,Y]=d.useState(g),[X,ie]=d.useState(k),[le,te]=d.useState([]),[V,K]=d.useState(R>0?R*60:null),oe=d.useRef(null),[ne,he]=d.useState(()=>Ni()),J=d.useRef(null),de=d.useRef(null),me=d.useRef(null),xe=d.useRef(null);d.useEffect(()=>{if(P&&e.length>0){const fe=e.map((be,_e)=>_e);for(let be=fe.length-1;be>0;be--){const _e=Math.floor(Math.random()*(be+1));[fe[be],fe[_e]]=[fe[_e],fe[be]]}te(fe)}},[P,e.length]),d.useEffect(()=>(oe.current&&(window.clearInterval(oe.current),oe.current=null),R>0&&_&&(K(R*60),oe.current=window.setInterval(()=>{K(fe=>!fe||fe<=1?(oe.current&&window.clearInterval(oe.current),oe.current=null,N==null||N(),null):fe-1)},1e3)),()=>{oe.current&&window.clearInterval(oe.current)}),[R,_]);const ce=d.useCallback(fe=>{const be=Math.min(Math.max(0,fe),Math.max(0,e.length-1));O(be),i==null||i(be)},[e.length,i]),ye=d.useCallback(()=>{if(P&&le.length>0){const be=le.indexOf(w)+1;return be<le.length?le[be]:z==="all"?le[0]:-1}return w<e.length-1?w+1:z==="all"?0:-1},[w,e.length,P,le,z]),Se=d.useCallback(()=>{if(P&&le.length>0){const fe=le.indexOf(w);return fe>0?le[fe-1]:z==="all"?le[le.length-1]:-1}return w>0?w-1:z==="all"?e.length-1:-1},[w,e.length,P,le,z]),ae=d.useCallback(()=>{const fe=ye();fe>=0&&ce(fe)},[ye,ce]),ue=d.useCallback(async()=>{var fe,be;await Bt(),he(!0),(E==null?void 0:E.kind)==="youtube"?(fe=J.current)==null||fe.playVideo():(be=de.current)==null||be.play(),L(!0),o==null||o(!0)},[E,o]),Ie=d.useCallback(()=>{var fe,be;(E==null?void 0:E.kind)==="youtube"?(fe=J.current)==null||fe.pauseVideo():(be=de.current)==null||be.pause(),L(!1),o==null||o(!1)},[E,o]),ze=d.useCallback(()=>_?Ie():ue(),[_,ue,Ie]),$e=d.useCallback(fe=>{var pe;const be=($==null?void 0:$.startOffset)??0,_e=fe+be;(E==null?void 0:E.kind)==="youtube"?(pe=J.current)==null||pe.seekTo(_e,!0):de.current&&(de.current.currentTime=_e);const vt=Math.max(0,fe);q(vt),l==null||l(vt)},[E,l]),Ye=d.useCallback(()=>{if(A>3){$e(0);return}const fe=Se();fe>=0&&ce(fe)},[Se,ce,A,$e]),je=d.useCallback(fe=>{var be,_e;re(fe),W(null),(E==null?void 0:E.kind)==="youtube"?(_e=(be=J.current)==null?void 0:be.setVolume)==null||_e.call(be,Math.round(fe*100)):de.current&&(de.current.volume=fe)},[E]),Ve=d.useCallback(()=>{D!==null?je(D):(W(H),je(0))},[H,D,je]),ht=d.useCallback(fe=>{var be,_e;Y(fe),de.current&&(de.current.playbackRate=fe),(E==null?void 0:E.kind)==="youtube"&&((_e=(be=J.current)==null?void 0:be.setPlaybackRate)==null||_e.call(be,fe)),M==null||M(fe)},[E,M]),et=d.useCallback(()=>{const fe=["none","all","one"],be=fe[(fe.indexOf(z)+1)%fe.length];B(be),b==null||b(be)},[z,b]),Ze=d.useCallback(()=>{const fe=!P;T(fe),S==null||S(fe)},[P,S]),At=d.useCallback(fe=>{ie(fe)},[]);d.useImperativeHandle(c,()=>({play:ue,pause:Ie,toggle:ze,seekTo:$e,setVolume:je,setSpeed:ht,setRepeatMode:fe=>{B(fe),b==null||b(fe)},toggleShuffle:Ze,setABLoop:At,getUnderlyingPlayer:()=>(E==null?void 0:E.kind)==="youtube"?J.current:(E==null?void 0:E.kind)==="hls"||(E==null?void 0:E.kind)==="audio"?de.current:null}),[ue,Ie,ze,$e,je,ht,Ze,At,E==null?void 0:E.kind]),d.useEffect(()=>{const fe=window.setInterval(()=>{let be=0,_e=0;(E==null?void 0:E.kind)==="youtube"&&J.current?(be=J.current.getCurrentTime()||0,_e=J.current.getDuration()||0):de.current&&(be=de.current.currentTime||0,_e=de.current.duration||0);const vt=($==null?void 0:$.startOffset)??0,pe=Math.max(0,be-vt);q(pe),Z(_e),l==null||l(pe),X&&pe>=X.b&&$e(X.a)},250);return()=>window.clearInterval(fe)},[E==null?void 0:E.kind,l,X]),d.useEffect(()=>()=>{I.current&&(window.clearInterval(I.current),I.current=null)},[]),d.useEffect(()=>{if(me.current){try{me.current.destroy()}catch{}me.current=null}if(de.current&&(de.current.volume=H,de.current.crossOrigin=E!=null&&E.withCredentials?"use-credentials":"anonymous"),(E==null?void 0:E.kind)==="hls"&&go(E.url)){const fe=de.current;if(!fe)return;const be=()=>{fe.src=E.url,fe.load();const _e=($==null?void 0:$.startOffset)??0;try{_e&&!isNaN(_e)&&(fe.currentTime=_e)}catch{}n&&fe.play().catch(()=>{})};fe.canPlayType("application/vnd.apple.mpegurl")?be():(async()=>{var _e;try{const pe=(await import("hls.js")).default;if((_e=pe==null?void 0:pe.isSupported)!=null&&_e.call(pe)){const ve=new pe({xhrSetup:Ue=>{if(E!=null&&E.withCredentials&&(Ue.withCredentials=!0),E!=null&&E.headers)for(const[Ee,Ce]of Object.entries(E.headers))try{Ue.setRequestHeader(Ee,Ce)}catch{}}});me.current=ve,ve.loadSource(E.url),ve.attachMedia(fe),ve.on(pe.Events.MANIFEST_PARSED,()=>{n&&fe.play().catch(()=>{})})}else be()}catch(vt){dh.debug("HLS.js setup failed, falling back to native playback",vt),be()}})()}else if((E==null?void 0:E.kind)==="audio"&&E.url&&de.current){const fe=de.current;fe.src=E.url,fe.load();const be=($==null?void 0:$.startOffset)??0;try{be&&!isNaN(be)&&(fe.currentTime=be)}catch{}n&&fe.play().catch(()=>{})}I.current&&(window.clearInterval(I.current),I.current=null),F(null),q(0),Z(0),n&&(E==null?void 0:E.kind)==="youtube"&&a>0?(F(a),I.current=window.setInterval(()=>{F(fe=>{var be;if(!fe)return null;if(fe<=1){I.current&&(window.clearInterval(I.current),I.current=null);try{(be=J.current)==null||be.playVideo()}catch{}return L(!0),o==null||o(!0),null}return fe-1})},1e3)):L(!!n)},[E==null?void 0:E.url,E==null?void 0:E.kind,E==null?void 0:E.withCredentials,JSON.stringify(E==null?void 0:E.headers),n,H]);const pt=d.useCallback(()=>{if(z==="one"){$e(0),ue();return}const fe=ye();fe>=0?ce(fe):(L(!1),o==null||o(!1),$e(0),y==null||y())},[z,ye,ce,o,$e,y,ue]);d.useEffect(()=>{if(!m)return;const fe=be=>{const _e=be.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable))switch(be.key){case" ":be.preventDefault(),ze();break;case"ArrowRight":be.preventDefault(),$e(Math.min(A+5,U));break;case"ArrowLeft":be.preventDefault(),$e(Math.max(0,A-5));break;case"ArrowUp":be.preventDefault(),je(Math.min(1,H+.05));break;case"ArrowDown":be.preventDefault(),je(Math.max(0,H-.05));break;case"m":case"M":Ve();break;case"n":case"N":ae();break;case"p":case"P":Ye();break;case"r":case"R":et();break;case"s":case"S":Ze();break}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[m,ze,$e,A,U,je,H,Ve,ae,Ye,et,Ze]);const Et=(E==null?void 0:E.kind)==="youtube"||u==="full"||u==="nobuttons",ct=h>0?e.slice(w+1,w+1+h):[];return r.jsxs("div",{ref:xe,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[n&&!ne&&r.jsx("div",{className:"gp-audio-activation",onClick:()=>{he(!0),ue()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:r.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),Et&&r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(E==null?void 0:E.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(E==null?void 0:E.kind)==="youtube"&&r.jsx(Ma,{videoId:E.videoId??vh(E.url),onReady:fe=>{J.current=fe.target,je(H);const be=($==null?void 0:$.startOffset)??0;try{be&&fe.target.seekTo(be,!0)}catch{}if(u==="nobuttons"){try{fe.target.playVideo()}catch{}L(!0)}},onEnd:pt,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||u==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:f?1:0}},style:{width:"100%",height:"100%"}}),j!==null&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:r.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:j})}),u==="nobuttons"&&r.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((E==null?void 0:E.kind)==="audio"||(E==null?void 0:E.kind)==="hls")&&r.jsxs(r.Fragment,{children:[u==="full"&&r.jsx("div",{style:{textAlign:"center",color:"var(--text-primary, #0f172a)"},children:$!=null&&$.coverUrl?r.jsx("img",{alt:"cover",src:$.coverUrl,style:{height:s-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[$==null?void 0:$.artist," — ",$==null?void 0:$.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-secondary, #64748b)"},children:(E==null?void 0:E.label)??`${(E==null?void 0:E.codec)??""} ${(E==null?void 0:E.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:de,onEnded:pt,onLoadedMetadata:()=>{const fe=de.current;fe&&Z(fe.duration||0)},crossOrigin:E!=null&&E.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(u==="minimal"||u==="compact")&&r.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:r.jsxs("div",{children:[r.jsx("div",{style:{fontWeight:600},children:($==null?void 0:$.title)??""}),r.jsx("div",{style:{color:"var(--text-secondary, #64748b)",fontSize:13},children:($==null?void 0:$.artist)??""})]})}),u==="full"&&r.jsxs(r.Fragment,{children:[r.jsx(yo,{currentTime:A,duration:U}),r.jsx(mh,{isPlaying:_,index:w,count:e.length,currentTime:A,duration:U,volume:H,onPrev:Ye,onNext:ae,onToggle:ze,onSeek:$e,onVolume:je}),r.jsx(xh,{shuffleOn:P,repeatMode:z,speed:G,abLoop:X,currentTime:A,sleepRemaining:V,onToggleShuffle:Ze,onCycleRepeat:et,onSpeedChange:ht,onSetABLoop:At,onMuteToggle:Ve,isMuted:D!==null})]}),u==="progressOnly"&&r.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:r.jsx(gh,{currentTime:A,duration:U,onSeek:$e})}),(u==="minimal"||u==="compact")&&r.jsx(yh,{isPlaying:_,canPrev:w>0,canNext:w<e.length-1,onPrev:Ye,onNext:ae,onToggle:ze}),u==="compact"&&ct.length>0&&r.jsx(bh,{items:ct,onSelect:fe=>ce(w+1+fe)}),u==="nobuttons"&&r.jsx(r.Fragment,{}),u==="full"&&e.length>0&&r.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((fe,be)=>r.jsxs("button",{onClick:()=>ce(be),style:{textAlign:"left",border:"1px solid var(--border-color)",borderRadius:8,padding:"8px 10px",background:be===w?"color-mix(in srgb, var(--color-primary) 14%, transparent)":"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},title:fe.sources.map(_e=>_e.kind).join(", "),children:[r.jsx("div",{style:{fontWeight:600},children:fe.title}),r.jsx("div",{style:{color:"var(--text-secondary)",fontSize:12},children:fe.artist})]},fe.id))})]})},bt={border:"1px solid var(--border-color)",borderRadius:8,padding:"6px 10px",background:"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},yo=({currentTime:e,duration:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary, #64748b)"},children:[Pr(e)," / ",Pr(t)]})]}),mh=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=Te();return r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("player.previousTrack"),"aria-label":p("player.previousTrack"),style:bt,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:p(e?"player.pause":"player.play"),"aria-label":p(e?"player.pause":"player.play"),style:bt,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("player.nextTrack"),"aria-label":p("player.nextTrack"),style:bt,children:r.jsx(se.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:f=>u(parseFloat(f.target.value)),"aria-label":"Seek position"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:f=>h(parseFloat(f.target.value)),"aria-label":"Volume"})]})]})},gh=({currentTime:e,duration:t,onSeek:n})=>r.jsxs(r.Fragment,{children:[r.jsx(yo,{currentTime:e,duration:t}),r.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:a=>n(parseFloat(a.target.value)),"aria-label":"Seek position"})]}),yh=({isPlaying:e,canPrev:t,canNext:n,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=Te();return r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[r.jsx("button",{onClick:a,disabled:!t,title:o("player.previousTrack"),"aria-label":o("player.previousTrack"),style:bt,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:i,title:o(e?"player.pause":"player.play"),"aria-label":o(e?"player.pause":"player.play"),style:bt,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:s,disabled:!n,title:o("player.nextTrack"),"aria-label":o("player.nextTrack"),style:bt,children:r.jsx(se.NtdSkipForward,{size:16})})]})},bh=({items:e,onSelect:t})=>{const{t:n}=Te();return r.jsxs("div",{style:{border:"1px solid var(--border-color)",borderRadius:8,padding:10,background:"var(--bg-secondary)",color:"var(--text-primary)"},children:[r.jsx("div",{style:{fontWeight:600,marginBottom:6},children:n("player.upNext")}),r.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((a,s)=>r.jsx("li",{style:{marginBottom:4},children:r.jsxs("button",{type:"button",onClick:()=>t(s),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--text-primary, #0f172a)"},title:a.sources.map(i=>i.kind).join(", "),children:[r.jsx("span",{style:{fontWeight:600},children:a.artist})," — ",a.title]})},a.id))})]})},xh=({shuffleOn:e,repeatMode:t,speed:n,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:u,onMuteToggle:h,isMuted:p})=>{const{t:f}=Te(),y={none:"Off",all:"All",one:"One"},m=t==="one"?r.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[r.jsx(se.NtdRepeat,{size:16}),r.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?r.jsx(se.NtdRepeat,{size:16}):r.jsx(se.NtdArrowRight,{size:16});return r.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[r.jsx("button",{onClick:o,title:f("player.shuffle","Shuffle"),"aria-label":f("player.shuffle","Shuffle"),style:{...bt,opacity:e?1:.4,fontWeight:e?700:400},children:r.jsx(se.NtdShuffle,{size:16})}),r.jsx("button",{onClick:l,title:`${f("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${f("player.repeat","Repeat")}: ${y[t]}`,style:{...bt,opacity:t==="none"?.4:1},children:m}),r.jsx("select",{value:n,onChange:v=>c(parseFloat(v.target.value)),title:f("player.speed","Speed"),"aria-label":f("player.speed","Speed"),style:{...bt,minWidth:56,fontSize:12},children:fh.map(v=>r.jsxs("option",{value:v,children:[v,"x"]},v))}),r.jsx("button",{onClick:h,title:f("player.mute","Mute"),"aria-label":f("player.mute","Mute"),style:{...bt,opacity:p?1:.6},children:p?r.jsx(se.NtdVolumeMute,{size:16}):r.jsx(se.NtdVolume,{size:16})}),a?r.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[r.jsxs("span",{style:{fontSize:11,color:"var(--text-secondary, #64748b)"},children:["A: ",Pr(a.a)," — B: ",Pr(a.b)]}),r.jsx("button",{onClick:()=>u(null),title:f("player.clearLoop","Clear loop"),style:{...bt,fontSize:11,padding:"2px 6px"},children:r.jsx(se.NtdClose,{size:12})})]}):r.jsx("button",{onClick:()=>u({a:s,b:s+10}),title:f("player.abLoop","A-B Loop"),"aria-label":f("player.abLoop","Set A-B Loop"),style:{...bt,opacity:.4},children:"A-B"}),i!==null&&i>0&&r.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function vh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const n=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(n)return n[1]}function bo(e){const t={};if(!e)return t;const n=e.split(",");for(const a of n){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Sh(e,t="/api/karaoke/cover"){var a,s;const n=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&n?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function kh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function xo(e,t,n=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<n)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Za(e,t){const n=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{n.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),n}function vo(e,t,n){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(u=>{a.push({start:u.visualStart-n,end:u.visualEnd-n,pitch:l.pitch,frac:u.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function So(e,t=120){let n=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);n=s}return n.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function ko(e,t,n){const s=Date.parse(e)-n;return Math.max(0,Math.round(t-s))}const wo={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function wh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function jh(e){return wo[e]??"var(--nice-text-secondary, #555555)"}function Ch(e){const t=wo[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function jo(e,t){const n=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(n){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=bo(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function Mh(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Xa=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Xa||{});function Co(e,t="song.txt"){const n=e.split(/\r?\n/),a={},s=[];for(const o of n){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Xa.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Rh=e=>window.btoa(unescape(encodeURIComponent(e))),Mo=({onSongUpload:e,parseSong:t,onError:n,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=Te(),l=i??o,c=h=>{const p=new FileReader;p.onload=async f=>{var m;if(!((m=f.target)!=null&&m.result))return;const y=f.target.result;try{const v=t?await t({fileName:h.name,data:Rh(y)}):Co(y,h.name);e(v)}catch(v){n==null||n(v)}},p.readAsText(h,"UTF-8")},u=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return r.jsx("div",{className:"nice-karaoke-uploader",children:r.jsx(we.NiceUpload,{accept:a,maxFileSize:s,validateFile:u,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const p=h[0];p&&c(p)}})})};function Nh(e,t,n,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,u=Math.PI/5*l-Math.PI/2,h=t+Math.cos(u)*c,p=n+Math.sin(u)*c;l===0?e.moveTo(h,p):e.lineTo(h,p)}e.closePath(),e.fillStyle=s,e.fill()}const Wt=60,Gs=4,Ws=["A","B","X","Y","LB","RB","LT","RT"],Ro=({lanes:e,events:t,currentTime:n,activeLanes:a,difficulty:s,feedbackQueue:i,isPlaying:o,height:l=300})=>{const c=e.length,u=d.useRef(null),h=d.useRef([]);return d.useEffect(()=>{h.current=i},[i]),d.useEffect(()=>{var b,S,M,R;const p=u.current;if(!p)return;const f=p.getContext("2d");if(!f)return;const y=window.devicePixelRatio||1,m=p.clientWidth,v=p.clientHeight;if(p.width=m*y,p.height=v*y,f.scale(y,y),f.clearRect(0,0,m,v),c===0)return;const x=m/c;for(let N=0;N<c;N++){const C=N*x;f.fillStyle=N%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",f.fillRect(C,0,x,v),N>0&&(f.strokeStyle="rgba(255,255,255,0.1)",f.lineWidth=1,f.beginPath(),f.moveTo(C,0),f.lineTo(C,v),f.stroke())}const g=v-Wt-10;f.strokeStyle="rgba(255,255,255,0.4)",f.lineWidth=2,f.setLineDash([8,4]),f.beginPath(),f.moveTo(0,g),f.lineTo(m,g),f.stroke(),f.setLineDash([]);const k=(v-Wt-20)/Gs;for(const N of t){const C=N.note.startTime,w=C+N.note.duration,O=C-n;if(O>Gs||w<n-.5)continue;const $=N.lane,E=$*x+4,_=x-8,L=g-O*k,U=N.note.duration*k,Z=n>=C-.15&&n<=w+.15,A=n>w+.15,q=((b=e[$])==null?void 0:b.color)??"#888";A?f.fillStyle="rgba(100,100,100,0.3)":Z?(f.fillStyle=q,f.shadowColor=q,f.shadowBlur=12):f.fillStyle=q+"99";const H=Math.max(U,8),re=6;f.beginPath(),f.moveTo(E+re,L),f.lineTo(E+_-re,L),f.quadraticCurveTo(E+_,L,E+_,L+re),f.lineTo(E+_,L+H-re),f.quadraticCurveTo(E+_,L+H,E+_-re,L+H),f.lineTo(E+re,L+H),f.quadraticCurveTo(E,L+H,E,L+H-re),f.lineTo(E,L+re),f.quadraticCurveTo(E,L,E+re,L),f.fill(),f.shadowBlur=0,N.note.isGold&&Nh(f,E+_/2,L+H/2,Math.min(7,_/4),"#fbbf24")}for(let N=0;N<c;N++){const C=N*x,w=v-Wt,O=a[N],$=((S=e[N])==null?void 0:S.color)??"#888";f.fillStyle=O?$:"rgba(30,30,30,0.9)",f.fillRect(C+2,w+2,x-4,Wt-4),f.strokeStyle=O?"#fff":$,f.lineWidth=O?3:1,f.strokeRect(C+2,w+2,x-4,Wt-4),f.fillStyle=O?"#000":"#fff",f.font=`bold ${Math.min(24,x*.3)}px monospace`,f.textAlign="center",f.textBaseline="middle",f.fillText(((M=e[N])==null?void 0:M.label)??"",C+x/2,w+Wt/2);const E=((R=e[N])==null?void 0:R.gamepadButton)??-1;E>=0&&E<Ws.length&&(f.fillStyle=O?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",f.font="10px sans-serif",f.fillText(Ws[E],C+x/2,w+Wt-8))}for(const N of h.current){const C=n-N.time;if(C<0||C>.8)continue;const w=Math.max(0,1-C/.8),O=N.lane*x;f.save(),f.globalAlpha=w,f.font="bold 20px sans-serif",f.textAlign="center",f.textBaseline="bottom",f.fillStyle=N.type==="perfect"?"#10b981":N.type==="good"?"#f59e0b":"#ef4444";const $=N.type==="perfect"?"PERFECT":N.type==="good"?"GOOD":"MISS";f.fillText($,O+x/2,g-10-C*40),f.restore()}},[n,e,t,a,c,o]),!o||c===0?null:r.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:l,zIndex:35,pointerEvents:"none"},children:[r.jsx("canvas",{ref:u,role:"img","aria-label":"Pad karaoke note highway — hit notes in time with the music",style:{width:"100%",height:"100%",display:"block"}}),r.jsxs("div",{style:{position:"absolute",top:8,right:12,background:"var(--nice-overlay-60, rgba(0,0,0,0.6))",color:"#fff",padding:"4px 12px",borderRadius:8,fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdGamepad,{size:14})," PAD — ",s]})]})},An=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],No={easy:{keys:["f","j"],buttons:[0,1],labels:["F","J"]},normal:{keys:["d","f","j","k"],buttons:[3,2,0,1],labels:["D","F","J","K"]},hard:{keys:["s","d","f","j","k","l"],buttons:[4,3,2,0,1,5],labels:["S","D","F","J","K","L"]}};function ha(e){return 440*Math.pow(2,(e-69)/12)}function To(e,t){const n=No[t],a=n.keys.length,s=[];for(const u of e)for(const h of u)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((u,h)=>u-h),s.length===0)return n.keys.map((u,h)=>({index:h,key:u,gamepadButton:n.buttons[h],label:n.labels[h],minPitch:-999,maxPitch:999,color:An[h%An.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let u=0;u<a;u++){const h=i+Math.floor(l*u/a),p=i+Math.floor(l*(u+1)/a)-1;c.push({index:u,key:n.keys[u],gamepadButton:n.buttons[u],label:n.labels[u],minPitch:u===0?-999:h,maxPitch:u===a-1?999:p,color:An[u%An.length]})}return c}function $o(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let n=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,n=s.index)}return n}function Po(e,t,n){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=n,a.push({note:o,lane:$o(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Ao{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,u,h,p,f,y,m,v;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(u=(c=this.config).onLaneActive)==null||u.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(p=(h=this.config).onCurrentNote)==null||p.call(h,o)),i.some(Boolean)&&o){const x=o.lane,g=i.indexOf(!0);if(i[x]){const k=ha(o.note.pitch);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(f=this.config).onHitFeedback)==null||y.call(f,{type:"perfect",lane:x,time:s}))}else if(g>=0){const b=Math.abs(g-x)*3,S=ha(o.note.pitch+b);this.config.onPitch(S),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(v=(m=this.config).onHitFeedback)==null||v.call(m,{type:"miss",lane:g,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=qn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=To(n,t.difficulty),this.events=Po(n,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const n=(a=t.target)==null?void 0:a.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const n=t[0];if(n){this.gamepadButtonsDown.clear();for(let s=0;s<n.buttons.length;s++)(a=n.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const n of this.lanes)(this.keysDown.has(n.key)||this.gamepadButtonsDown.has(n.gamepadButton))&&(t[n.index]=!0);return t}findActiveNote(t){for(const n of this.events){const a=n.note.startTime-this.preWindow,s=n.note.startTime+n.note.duration+this.postWindow;if(t>=a&&t<=s)return n}return null}}const mt=it.scoped("BaseStreamClient");function Us(e,t,n){if(t===n)return e.slice();const a=Math.round(e.length*n/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),u=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[u]*h}return s}function Th(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n++){const a=Math.max(-1,Math.min(1,e[n]));t[n]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const xn=16e3,$h="/scripts/pitch-worklet.js";class Eo{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,n;try{(n=(t=this.opts).onMaxReconnect)==null||n.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return $h}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(mt.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,n,a,s,i,o;try{(n=(t=this.opts).onOpen)==null||n.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,mt.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const l=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(u){(o=(i=this.opts).onError)==null||o.call(i,u);break}}finally{this.sendQueue=[]}mt.info(`[${this.ts()}] flushed ${l} queued chunks`)}},this.ws.onclose=t=>{var n,a;try{(a=(n=this.opts).onClose)==null||a.call(n,t)}catch{}if(mt.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);mt.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else mt.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var n,a;mt.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(n=this.opts).onError)==null||a.call(n,t)}catch{}},this.ws.onmessage=t=>{var n,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(n=this.opts).onError)==null||a.call(n,s)}})}handleAudioFrame(t){var f,y,m,v,x,g,k,b;const n=new Float32Array(this.buffer.length+t.length);n.set(this.buffer,0),n.set(t,this.buffer.length),this.buffer=n;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*xn/1e3),i=Math.floor(this.buffer.length*xn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/xn),u=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Us(u,a,xn);let p=0;for(;p+s<=h.length;){const S=h.subarray(p,p+s),R=Th(S).buffer,N=this.ws;if(N&&N.readyState===WebSocket.OPEN)try{N.send(R),this.chunksSent++,(y=(f=this.opts).onSend)==null||y.call(f,R.byteLength)}catch(w){(v=(m=this.opts).onError)==null||v.call(m,w)}else N&&N.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(R),(g=(x=this.opts).onSend)==null||g.call(x,0)):(this.chunksDropped++,(b=(k=this.opts).onSend)==null||b.call(k,0));const C=Date.now();C-this.lastStatusLog>5e3&&(this.lastStatusLog=C,mt.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(N==null?void 0:N.readyState)??"none"} worklet=${this.usingWorklet}`)),p+=s}if(p<h.length){const S=h.subarray(p),M=Us(S,xn,a),R=new Float32Array(M.length+this.buffer.length);R.set(M,0),R.set(this.buffer,M.length),this.buffer=R}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,mt.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){mt.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const n=4096;this.proc=this.audioCtx.createScriptProcessor(n,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,mt.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const n=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(n)}stop(){var t,n;if(mt.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(n=this.ws)==null||n.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Ph=it.scoped("CrepeStreaming");class Ah extends Eo{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,n)}onMaxReconnect(){var t,n;Ph.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(n=(t=this.crepeOpts).onFallback)==null||n.call(t)}catch{}}}class Eh extends Eo{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const n=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,n)}get useWorklet(){return!1}}const Pt={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Ih(e){const t=new Float32Array(e);for(let n=0;n<e;n++)t[n]=.5*(1-Math.cos(2*Math.PI*n/(e-1)));return t}function Lh(e,t){const n=new Float32Array(e.length);for(let a=0;a<e.length;a++)n[a]=e[a]*t[a];return n}function Io({isPlaying:e,gameMode:t,players:n,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:u={},micSmoothingWindows:h={},micHysteresisFrames:p={},micUseHanning:f={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:v,isPadMode:x,clockOffsetMsRef:g,currentPartyIdRef:k,rtc:b}){const[S,M]=d.useState({}),R=d.useRef({}),N=d.useRef({}),[C,w]=d.useState({}),O=d.useRef({}),$=d.useRef([]),E=d.useRef(null),_=d.useRef(null),[,L]=d.useState({}),[,U]=d.useState({}),[,Z]=d.useState({}),[A,q]=d.useState({}),[H,re]=d.useState(!0),[D,W]=d.useState(!1),j=d.useRef(n);j.current=n;const F=d.useRef(0),I=d.useRef(performance.now());return d.useEffect(()=>{$.current.forEach(G=>G()),$.current=[];const P={current:!1};function T(G,Y,X=0){v.current!==F.current&&(F.current=v.current,I.current=performance.now());const ie=Math.min(.25,(performance.now()-I.current)/1e3),le=v.current+ie-X/1e3;M(V=>{const K=V[G]||[];return{...V,[G]:[...K,{t:le,hz:Y}]}}),R.current[G]=(R.current[G]||[]).concat({t:le,hz:Y});const te=R.current[G];te.length>500&&(R.current[G]=te.slice(-500))}function z(G,Y,X,ie=.02,le=0,te=.6,V=0,K=0,oe=0,ne=!1){let he=null,J=null,de=null;return(async()=>{try{he=new AudioContext;let ce=he.createMediaStreamSource(Y);if(V>0){const $e=he.createGain();$e.gain.value=V,ce.connect($e),ce=$e}const ye=he.createAnalyser();ye.fftSize=2048,ce.connect(ye);const Se=new Float32Array(ye.fftSize),ae=ne?Ih(ye.fftSize):null,ue=[];let Ie=0;if(X==="pitchy")try{const{PitchDetector:$e}=await import("pitchy");de=$e.forFloat32Array(ye.fftSize)}catch($e){Pt.warn("pitchy import failed, falling back to autocorrelation",$e)}const ze=()=>{try{ye.getFloatTimeDomainData(Se)}catch{}const $e=ae?Lh(Se,ae):Se;let Ye=0;for(let Ve=0;Ve<$e.length;Ve++)Ye+=$e[Ve]*$e[Ve];Ye=Math.sqrt(Ye/$e.length);let je=0;if(Ye>=ie)if(de)try{const[Ve,ht]=de.findPitch($e,he.sampleRate);Ve>50&&Ve<3e3&&ht>te&&(je=Ve)}catch{}else je=xo($e,he.sampleRate,ie),(je<50||je>3e3)&&(je=0);if(je>0&&K>1&&(ue.push(je),ue.length>K&&ue.shift(),je=ue.reduce((Ve,ht)=>Ve+ht,0)/ue.length),je>0)Ie=0,T(G,je,le);else if(Ie++,oe>0&&Ie<=oe&&ue.length>0){const Ve=ue[ue.length-1];Ve>0&&T(G,Ve,le)}J=requestAnimationFrame(ze),O.current[G]=J};ze()}catch(xe){Pt.warn("startLocalPitch error",xe)}})(),()=>{J&&cancelAnimationFrame(J),he&&he.close().catch(()=>{})}}function B(G,Y,X,ie=0){X==="crepe"&&_.current?(_.current.stop(),_.current=null):X==="librosa"&&E.current&&(E.current.stop(),E.current=null);const le=window.location,te=le.protocol==="https:"?"wss:":"ws:",V=X==="librosa"?`${te}//${le.host}/api/librosa/ws/pyin`:`${te}//${le.host}/api/ai/audio/pitch/ws/pitch_server`,K=X==="librosa"?L:U;K(de=>({...de,[G]:"connecting"}));const oe=[],ne=de=>{if(de>0){for(oe.push(v.current);oe.length>200;)oe.shift();X==="crepe"&&Z(me=>({...me,[G]:(me[G]||0)+1}))}},he=()=>{K(de=>({...de,[G]:"closed"})),oe.length=0},J=de=>{if(typeof de.hz=="number"&&de.hz>0){const me=de.hz,ce=(oe.length>0?oe.shift():v.current)-ie/1e3;M(ye=>{const Se=ye[G]||[];return{...ye,[G]:[...Se,{t:ce,hz:me}]}})}else oe.length>0&&oe.shift()};if(X==="librosa"){const de=new Eh({wsUrl:V,onOpen:()=>K(me=>({...me,[G]:"connected"})),onClose:he,onError:me=>{K(xe=>({...xe,[G]:"error"})),Pt.warn("Librosa WS error",me)},onMessage:J,onSend:ne});return E.current=de,de.startWithMediaStream(Y).catch(me=>{Pt.warn("Librosa client start failed",me),K(xe=>({...xe,[G]:"failed"}))}),()=>{de.stop(),E.current=null,K(me=>({...me,[G]:""}))}}else{const de=new Ah({wsUrl:V,onOpen:()=>K(me=>({...me,[G]:"connected"})),onClose:he,onError:me=>{K(xe=>({...xe,[G]:"error"})),Pt.warn("Crepe WS error",me)},onMessage:J,onSend:ne,onFallback:()=>{K(xe=>({...xe,[G]:"fallback-pitchy"})),_.current=null;const me=z(G,Y,"pitchy",.02,ie);$.current.push(me)}});return _.current=de,de.startWithMediaStream(Y).catch(me=>{Pt.warn("Crepe client start failed",me),K(xe=>({...xe,[G]:"failed"}))}),()=>{de.stop(),_.current=null,K(me=>({...me,[G]:""}))}}}if(e){if(M({}),t!=="pad"){const G={};j.current.forEach(Y=>{if(!Y.micId)return;const X=s[Y.id]||i,ie=Y.micId&&o[Y.micId]||.02,le=Y.micId&&l[Y.micId]||0,te=Y.micId&&c[Y.micId]||0,V=Y.micId&&u[Y.micId]||.6,K=Y.micId&&h[Y.micId]||0,oe=Y.micId&&p[Y.micId]||0,ne=Y.micId&&f[Y.micId]||!1,he=Y.micId&&y[Y.micId]||!1,J=(Y.micId?m[Y.micId]:void 0)??100,de=new Ea;de.startRecording({deviceId:Y.micId,onLevel:()=>{},gain:te,monitorEnabled:he,monitorVolume:J}).then(()=>{if(P.current){de.stopRecording().catch(()=>{});return}G[Y.id]=de;const me=de.getStream();if(!me){Pt.warn(`No stream from recorder for player ${Y.id}`);return}if(X==="librosa"||X==="crepe"){const xe=B(Y.id,me,X,le);$.current.push(xe)}else{const xe=z(Y.id,me,X,ie,le,V,te,K,oe,ne);$.current.push(xe)}}).catch(me=>Pt.warn(`recorder start failed for player ${Y.id}`,me))}),N.current=G}}else{const G=N.current,Y=Object.keys(G).map(Number);Promise.allSettled(Y.map(async X=>{const ie=await G[X].stopRecording();return{pid:X,blob:ie}})).then(X=>{const ie={};for(const le of X)le.status==="fulfilled"&&le.value.blob&&(ie[le.value.pid]=le.value.blob);Object.keys(ie).length>0&&w(le=>({...le,...ie}))}),N.current={},Object.values(O.current).forEach(X=>X&&cancelAnimationFrame(X)),O.current={}}return()=>{P.current=!0,$.current.forEach(G=>G()),$.current=[],Object.values(N.current).forEach(G=>G.stopRecording().catch(()=>{})),N.current={},Object.values(O.current).forEach(G=>G&&cancelAnimationFrame(G)),O.current={}}},[e,t,a,s,i,o,l,c,u,h,p,f,y,m]),d.useEffect(()=>{if(!b)return;const P=300,T=async()=>{try{const B={...R.current};for(const G of Object.keys(B)){const Y=Number(G),X=B[Y]||[];if(!X||X.length===0)continue;R.current[Y]=[];const ie=So(X,120),le={playerId:Y,points:ie,clientNowUtc:new Date().toISOString(),quantized:!0};k!=null&&k.current&&(le.EventId=k.current);try{b.isConnected()&&await b.publishTimelineUpdate(le)}catch(te){Pt.warn("failed to publish timeline update, will retry",te),R.current[Y]=(R.current[Y]||[]).concat(X).slice(-1e3)}}}catch{}},z=window.setInterval(T,P);return()=>{z&&window.clearInterval(z)}},[b,k]),d.useEffect(()=>{if(!b)return;const P=T=>{try{const z=T;if(!z||typeof z.playerId>"u"||!Array.isArray(z.points))return;const B=Number(z.playerId),G=z.points.map(Y=>({t:Y.t,hz:Y.hz}));if(!G.length)return;if(z.serverTimeUtc){const Y=ko(z.serverTimeUtc,Date.now(),(g==null?void 0:g.current)||0);q(X=>({...X,[B]:Y}))}M(Y=>{const X=Y[B]||[];return{...Y,[B]:[...X,...G]}})}catch{}};return b.onTimelineUpdate(P),()=>b.offTimelineUpdate(P)},[b,g]),{livePitch:S,setLivePitch:M,recordings:C,recordersRef:N,unsentPitchRef:R,pitchCleanupsRef:$,remoteLatencyMs:A,showRemoteTimelines:H,setShowRemoteTimelines:re,compactTimelines:D,setCompactTimelines:W}}function Lo(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function Do(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function _o(e,t,n){const{semitoneTolerance:a,preWindow:s,postExtra:i}=n,o=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,u=typeof n.difficultyMult=="number"?n.difficultyMult:1,h=!!n.disableGoldNotes;let p=0,f=0,y=0;const m=[];let v=0,x=0,g=0;const k=new Map;e.forEach((w,O)=>{const $=w.startTime,E=w.startTime+w.duration,_=$-s,L=E+i,U=t.filter(j=>j.t>=_&&j.t<=L&&j.hz>0);if(!U||U.length===0)return;const Z=Math.max(1,Math.ceil((w.duration||.25)/o)),A=Math.max(10,Math.round(100*(w.duration||1))),q=Math.max(1,Math.round(A/Z));let H=0;const re=[];for(let j=0;j<Z;j++){const F=$+j*(w.duration/Z),I=$+(j+1)*(w.duration/Z),P=Math.min(.06,w.duration/Z*.2),T=F-P,z=I+P,B=t.filter(te=>te.t>=T&&te.t<=z&&te.hz>0);if(!B||B.length===0)continue;let G=0;B.forEach(te=>{let K=((12*Math.log2(te.hz/440)+69)%12+12)%12;for(;K-w.pitch>6;)K-=12;for(;K-w.pitch<-6;)K+=12;const oe=Math.abs(K-w.pitch);G+=oe});const Y=G/B.length;let X=0;if(a<=0)X=Y===0?1:0;else{const te=a*2;X=Math.max(0,1-Math.min(Y/te,1))}if(X<=0)continue;const ie=!h&&w.isGold?2:1,le=Math.round(q*ie*X);le>0&&(p+=le,H+=le,re.push({segIndex:j,frac:X,add:le,segStart:T,segEnd:z,visualStart:F,visualEnd:I}))}const D=w.line??0;k.has(D)||k.set(D,{total:0,hit:0,comboBonus:0});const W=k.get(D);if(W.total++,H>0){v++,v>x&&(x=v),W.hit++;const j=Do(v),F=j>1?Math.round(H*(j-1)):0;g+=F,W.comboBonus+=F;const I=Math.max(1,Math.ceil((w.duration||.25)/o)),T=re.length>=I,z=T?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*l*(!h&&w.isGold?1.5:1)*u):0,B=T&&!h&&w.isGold?Math.round(Math.max(10,Math.round(100*(w.duration||1)))*c*u):0;f+=z,y+=B,m.push({noteKey:`${w.line??0}-${w.idx??0}`,segments:re,totalAdded:H,completed:T,completionBonus:z,goldFullBonus:B})}else v=0});const b=[];for(const[w,O]of k.entries()){const $=O.total>0?O.hit/O.total:0;b.push({verseIndex:w,hitFraction:$,label:Lo($),comboBonus:O.comboBonus})}const S={maxCombo:x,currentCombo:0,totalComboBonus:g},M=g+f+y,R=m.length,N=m.filter(w=>w.completed).length,C={hits:R,misses:e.length-R,good:R-N,perfect:N,maxCombo:x};return{classicScore:p,bonusScore:M,totalScore:p+M,total:p,perNote:m,combo:S,verseRatings:b,noteStats:C}}function Fo(e,t){let n=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;n+=s*i}return n}function zo(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function Oo(e,t,n){const a=Fo(t,n);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const s=zo(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i,total:s}}const vn={maxCombo:0,currentCombo:0,totalComboBonus:0},qs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function Bo({livePitch:e,uploadedSong:t,isPlaying:n,difficulty:a,players:s,isPadMode:i}){const[o,l]=d.useState(0),[c,u]=d.useState(0),[h,p]=d.useState(0),[f,y]=d.useState([]),[m,v]=d.useState(vn),[x,g]=d.useState([]),[k,b]=d.useState([]),[S,M]=d.useState({}),[R,N]=d.useState({}),[C,w]=d.useState({}),[O,$]=d.useState({}),[E,_]=d.useState({});return d.useEffect(()=>{if(!t||!n)return;const L=qn(t.notes.map(B=>B.noteLine),t.bpm??void 0),U=(t.gap??0)/1e3,Z=Za(L,U),A=Ir(a),q=[];let H=null,re=null,D=null,W=[];const j={},F={},I={},P={},T={},z=i?s[0]:s.find(B=>!!B.micId)||s[0];for(let B=0;B<s.length;B++){const G=s[B],Y=(G==null?void 0:G.id)!=null?e[G.id]||[]:[];if(Y.length===0){q.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||Je[B%Je.length],classicScore:0,bonusScore:0,totalScore:0}),j[G.id]=[],F[G.id]={...vn},I[G.id]=[],P[G.id]=0,T[G.id]={...qs};continue}const X=Ua(G.id),ie=!!(X!=null&&X.disableGoldNotes),le=_o(Z,Y,{semitoneTolerance:A.semitoneTolerance,preWindow:A.preWindow,postExtra:A.postExtra,difficultyMult:A.difficultyMult,disableGoldNotes:ie}),te=Oo(le,Z,ie);q.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||Je[B%Je.length],classicScore:te.classicScore,bonusScore:te.bonusScore,totalScore:te.totalScore}),j[G.id]=vo(le.perNote,L,U),F[G.id]=le.combo??{...vn},I[G.id]=le.verseRatings??[],P[G.id]=te.totalScore,T[G.id]=le.noteStats??{...qs},G.id===(z==null?void 0:z.id)&&(H=te,re=le.combo??null,D=le.verseRatings??null,W=j[G.id])}b(q),M(j),N(F),w(I),$(P),_(T),H?(l(H.classicScore),u(H.bonusScore),p(H.totalScore),y(W),v(re??vn),g(D??[])):(l(0),u(0),p(0),y([]),v(vn),g([]))},[e,t,n,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:f,liveCombo:m,liveVerseRatings:x,perPlayerScores:k,perPlayerSegmentScores:S,perPlayerCombo:R,perPlayerVerseRatings:C,perPlayerTotalScores:O,perPlayerNoteStats:E}}const Dh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),_h=({players:e,song:t,initialSong:n=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:u=!0,initiallyActivated:h=!1,showUploader:p=!1,parseSong:f,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:v,micOffsets:x,micGains:g,micPitchThresholds:k,micSmoothingWindows:b,micHysteresisFrames:S,micUseHanning:M,micMonitorEnabled:R,micMonitorVolumes:N,searchYouTubeByArtistTitle:C,fetchTopSingings:w,onSaveResults:O,rtc:$,onSongChange:E,onPlayingChange:_,onTimeUpdate:L,onEnded:U,onContinue:Z,renderReport:A,t:q,className:H,style:re,id:D,accessMode:W,"data-testid":j})=>{var Fe;const{t:F}=Te(),I=q??F,[P,T]=d.useState(t??n??null),[z,B]=d.useState(!1),[G,Y]=d.useState(0),[X,ie]=d.useState(h),[le,te]=d.useState(!1),[V,K]=d.useState([]),[oe,ne]=d.useState(""),[he,J]=d.useState(null),[de,me]=d.useState(0),xe=s==="pad",[ce,ye]=d.useState([]),[Se,ae]=d.useState([]),[ue,Ie]=d.useState([]),[ze,$e]=d.useState([]),Ye=d.useRef(null),je=d.useRef(null),Ve=d.useRef(null),ht=d.useRef(!1),et=d.useRef(0);d.useEffect(()=>{et.current=G},[G]);const Ze=d.useRef(t);d.useEffect(()=>{t!==void 0&&t!==Ze.current&&(Ze.current=t,T(t),te(!1),Y(0),me(ge=>ge+1))},[t]);const At=d.useMemo(()=>JSON.stringify(e.map(ge=>({id:ge.id,micId:ge.micId}))),[e]),{livePitch:pt,setLivePitch:Et,recordings:ct,remoteLatencyMs:fe}=Io({isPlaying:z,gameMode:s,players:e,playersMicKey:At,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:v,micOffsets:x,micGains:g,micPitchThresholds:k,micSmoothingWindows:b,micHysteresisFrames:S,micUseHanning:M,micMonitorEnabled:R,micMonitorVolumes:N,currentTimeRef:et,isPadMode:xe,rtc:$}),be=Bo({livePitch:pt,uploadedSong:P,isPlaying:z,difficulty:a,players:e,isPadMode:xe}),_e=d.useRef(be);_e.current=be;const vt=d.useMemo(()=>P?jo(P,s):null,[P,s]),pe=((Fe=e[0])==null?void 0:Fe.id)??1;d.useEffect(()=>{var Me;if(!xe||!z||!P){(Me=Ye.current)==null||Me.stop(),Ye.current=null,ye([]),ae([]),Ie([]),$e([]);return}const ge=new Ao({difficulty:a,noteLines:P.notes.map(Pe=>Pe.noteLine),bpm:P.bpm??void 0,gap:P.gap??0,onPitch:Pe=>{const Ge=et.current;Et(De=>{const nt=De[pe]||[];return{...De,[pe]:[...nt,{t:Ge,hz:Pe}]}})},onHitFeedback:Pe=>$e(Ge=>[...Ge.slice(-20),Pe]),onLaneActive:Pe=>Ie(Pe)});return ye(ge.getLanes()),ae(ge.getEvents()),Ie(new Array(ge.getLanes().length).fill(!1)),ge.start(()=>et.current),Ye.current=ge,()=>{ge.stop(),Ye.current=null}},[xe,z,P,a,pe,Et]);const ve=d.useCallback(ge=>{B(ge),_==null||_(ge)},[_]),Ue=d.useCallback(ge=>{Y(ge),L==null||L(ge)},[L]),Ee=d.useCallback(()=>{var Me;try{Bt()}catch{}const ge=()=>{ie(!0),ht.current=!0};!xe&&u&&((Me=navigator.mediaDevices)!=null&&Me.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Pe=>Pe.getTracks().forEach(Ge=>Ge.stop())).catch(()=>{}).finally(ge):ge()},[xe,u]);d.useEffect(()=>{if(!X||!ht.current)return;ht.current=!1;const ge=window.setInterval(()=>{je.current&&(window.clearInterval(ge),je.current.play())},100),Me=window.setTimeout(()=>window.clearInterval(ge),3e3);return()=>{window.clearInterval(ge),window.clearTimeout(Me)}},[X]);const Ce=d.useCallback(()=>{te(!0),U==null||U();const ge=(P==null?void 0:P.id)??0,Me=_e.current,Pe=[];for(const De of e){const nt=Me.perPlayerTotalScores[De.id]??0;if(nt<=0)continue;const Ke=Me.perPlayerNoteStats[De.id];Pe.push({playerId:De.id,songId:ge,score:nt,hits:(Ke==null?void 0:Ke.hits)??0,misses:(Ke==null?void 0:Ke.misses)??0,good:(Ke==null?void 0:Ke.good)??0,perfect:(Ke==null?void 0:Ke.perfect)??0,combo:(Ke==null?void 0:Ke.maxCombo)??0})}const Ge=()=>{w&&ge>0&&Promise.resolve(w(ge)).then(K).catch(()=>{})};O&&Pe.length>0?Promise.resolve(O(Pe)).then(Ge).catch(Ge):Ge()},[e,P,O,w,U]);d.useEffect(()=>{var ge;s==="demo"&&z&&G>=12&&((ge=je.current)==null||ge.pause(),Ce())},[s,z,G,Ce]),d.useEffect(()=>{if(!P||de===0||!C||Dh(P.videoPath))return;if(P.youtubeId){const Me=`https://www.youtube.com/watch?v=${P.youtubeId}`;T(Pe=>Pe&&{...Pe,videoPath:Me});return}if(!P.artist||!P.title)return;let ge=!1;return ne(I("karaokeManager.ytSearching","Searching YouTube…")),J("searching"),Promise.resolve(C(P.artist,P.title)).then(Me=>{if(!ge)if(Me){const Pe=`https://www.youtube.com/watch?v=${Me}`;T(Ge=>Ge&&{...Ge,videoPath:Pe}),ne(""),J(null)}else ne(I("karaokeManager.ytNotFound","Not found on YouTube")),J("error"),window.setTimeout(()=>{ge||(ne(""),J(null))},4e3)}).catch(()=>{ge||(ne(I("karaokeManager.ytSearchError","Search error")),J("error"))}),()=>{ge=!0}},[de,P,C,I]);const Re=d.useCallback(()=>{var ge,Me;te(!1),Et({}),(ge=je.current)==null||ge.seekTo(0),(Me=je.current)==null||Me.play()},[Et]),Oe=d.useCallback(()=>{te(!1),Z==null||Z()},[Z]),Be=d.useCallback(ge=>{T(ge),te(!1),Y(0),me(Me=>Me+1),E==null||E(ge)},[E]),Qe=d.useMemo(()=>{if(!c)return e;const ge=e.find(Me=>!!Me.micId)||e[0];return ge?[ge]:[]},[e,c]),Ae=((P==null?void 0:P.gap)??0)/1e3;return W==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-manager${H?` ${H}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...re},id:D,"data-testid":j,children:[oe&&r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-bg, #fff)"},children:[he==="error"?r.jsx(se.NtdClose,{size:16}):r.jsx(se.NtdSearch,{size:16}),oe]}),!P&&p&&r.jsx(Mo,{onSongUpload:Be,parseSong:f,t:I}),P&&!X&&r.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:Ee,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[r.jsx("div",{style:{fontSize:56,lineHeight:0},children:xe?r.jsx(se.NtdGamepad,{size:56}):r.jsx(se.NtdMicrophone,{size:56})}),r.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff"},children:I("karaokeManager.activateAudio","Tap to start")}),r.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:xe?I("karaokeManager.padHint","Hit the notes with your keys or pad!"):I("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),P&&r.jsxs("div",{ref:Ve,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[r.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:r.jsx(Ya,{tracks:vt?[vt]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:je,onPlayingChange:ve,onTimeUpdate:Ue,onEnded:Ce})}),o&&X&&r.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Qe.map((ge,Me)=>{const Pe=pt[ge.id]||[],Ge=Ae?Pe.map(De=>({t:De.t-Ae,hz:De.hz})):Pe;return r.jsx(Va,{song:P,currentTime:G,playerRef:Ve,userPitch:Ge,segmentScores:be.perPlayerSegmentScores[ge.id],combo:be.perPlayerCombo[ge.id],verseRatings:be.perPlayerVerseRatings[ge.id],config:{playerName:ge.name,score:be.perPlayerTotalScores[ge.id]??0,playerBgColor:ge.color||Je[Me%Je.length],difficultyLevel:a,isPlaying:z,playerCount:Qe.length,latencyMs:fe[ge.id]??null,top:30+Me*160}},ge.id)})}),xe&&ce.length>0&&r.jsx(Ro,{lanes:ce,events:Se,currentTime:G,activeLanes:ue,difficulty:a,feedbackQueue:ze,isPlaying:z}),l&&X&&r.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:r.jsx(Da,{song:P,currentTime:G})})]}),le&&Object.keys(ct).length>0&&r.jsx(Fh,{recordings:ct,players:e,t:I}),le&&r.jsx(Ka,{uploadedSong:P,playerScores:be.perPlayerScores,topSingings:V,onRestart:Re,onContinue:Oe,t:I,renderReport:A})]})},Fh=({recordings:e,players:t,t:n})=>{const a=d.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return d.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),r.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[r.jsxs("h4",{style:{marginTop:0,color:"var(--nice-bg, #fff)"},children:[r.jsx(se.NtdMicrophone,{size:16})," ",n("karaokeManager.playerRecordings","Player recordings")]}),r.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,color:"var(--nice-bg, #fff)"},children:t.map(s=>r.jsxs("li",{style:{marginBottom:12,display:"flex",alignItems:"center",gap:10},children:[r.jsx("b",{children:s.name||`Player ${s.id}`}),a[s.id]?r.jsxs(r.Fragment,{children:[r.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),r.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[r.jsx(se.NtdDownload,{size:13})," ",n("karaokeManager.download","Download")]})]}):r.jsx("span",{style:{opacity:.6},children:n("karaokeManager.noRecording","No recording")})]},s.id))})]})},Go=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function nn(e){return 12*Math.log2(e/440)+69}function Qn(e){const t=Go[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function Kr(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),a=Math.floor(n),s=Math.ceil(n);return a===s?e[a]:e[a]+(e[s]-e[a])*(n-a)}function Wo(e){const{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:u,combo:h,classicScore:p,bonusScore:f,totalScore:y,micSettings:m}=e,v=l.filter(ae=>ae.hz>0),x=v.map(ae=>nn(ae.hz)),g=[],k=[],b=[],S=[...c].sort((ae,ue)=>ae.startTime-ue.startTime);function M(ae){let ue=0,Ie=S.length-1;for(;ue<=Ie;){const ze=ue+Ie>>>1,$e=S[ze];if(ae<$e.startTime)Ie=ze-1;else if(ae>$e.startTime+$e.duration)ue=ze+1;else return $e.pitch}return 0}for(const ae of l){const ue=ae.hz>0?nn(ae.hz):0,Ie=M(ae.t);if(k.push({t:ae.t,sung:ue,expected:Ie}),ue>0&&Ie>0){const ze=(ue-Ie)*100;g.push(ze)}}let R=0;for(const ae of S){const ue=ae.startTime-.3,Ie=ae.startTime+ae.duration;for(;R<v.length&&v[R].t<ue;)R++;R<v.length&&v[R].t<=Ie&&b.push((v[R].t-ae.startTime)*1e3)}const N=g.map(Math.abs),C=[...N].sort((ae,ue)=>ae-ue),w=N.length>0?N.reduce((ae,ue)=>ae+ue,0)/N.length:0,O=Kr(C,50),$=N.length>1?Math.sqrt(N.reduce((ae,ue)=>ae+(ue-w)**2,0)/(N.length-1)):0,E=N.filter(ae=>ae<=50).length,_=N.filter(ae=>ae<=15).length,L=N.length>0?E/N.length*100:0,U=N.length>0?_/N.length*100:0,Z=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],A=new Array(10).fill(0);for(const ae of g){const ue=ae<-100?0:ae<-50?1:ae<-25?2:ae<-15?3:ae<0?4:ae<15?5:ae<25?6:ae<50?7:ae<100?8:9;A[ue]++}const q=Z.map((ae,ue)=>({centRange:ae,count:A[ue],pct:g.length>0?A[ue]/g.length*100:0})),H=v.map(ae=>ae.hz).sort((ae,ue)=>ae-ue),re=H.length>0?H[0]:0,D=H.length>0?H[H.length-1]:0,W=re>0?nn(re):0,j=D>0?nn(D):0,F=j-W,I=[...x].sort((ae,ue)=>ae-ue),P=Kr(I,10),T=Kr(I,90),z=new Array(12).fill(0);for(const ae of x){const ue=Math.round(ae)%12;ue>=0&&ue<12&&z[ue]++}const B=z.reduce((ae,ue)=>ae+ue,0),G=Go.map((ae,ue)=>({note:ae,count:z[ue],pct:B>0?z[ue]/B*100:0})),Y=zh(v),X=b.length>0?b.reduce((ae,ue)=>ae+ue,0)/b.length:0,ie=b.length>1?Math.sqrt(b.reduce((ae,ue)=>ae+(ue-X)**2,0)/(b.length-1)):0,le=ie>0?Math.max(0,Math.min(100,100-ie/2)):100;let te=0,V=0;for(let ae=1;ae<x.length;ae++){const ue=Math.abs(x[ae]-x[ae-1]);te+=ue,V++}const K=V>0?te/V*100/12:0,oe=l.filter(ae=>ae.hz<=0).length,ne=l.length>0?(1-oe/l.length)*100:0,he=new Map;for(const ae of c){const ue=ae.line??0;he.has(ue)||he.set(ue,[]),he.get(ue).push(ae)}const J=new Map;for(const ae of v){const ue=M(ae.t);if(ue<=0)continue;let Ie=0,ze=S.length-1,$e=-1;for(;Ie<=ze;){const je=Ie+ze>>>1,Ve=S[je];if(ae.t<Ve.startTime)ze=je-1;else if(ae.t>Ve.startTime+Ve.duration)Ie=je+1;else{$e=Ve.line??0;break}}if($e<0)continue;const Ye=Math.abs((nn(ae.hz)-ue)*100);J.has($e)||J.set($e,[]),J.get($e).push(Ye)}const de=u.map(ae=>{const ue=he.get(ae.verseIndex)??[],Ie=J.get(ae.verseIndex)??[],ze=Ie.length>0?Ie.reduce(($e,Ye)=>$e+Ye,0)/Ie.length:0;return{verseIndex:ae.verseIndex,label:ae.label,hitFraction:ae.hitFraction,avgCentDeviation:Math.round(ze*10)/10,noteCount:ue.length,notesHit:Math.round(ae.hitFraction*ue.length),comboBonus:ae.comboBonus}}),me=2,xe=.5,ce=l.length>0?l[l.length-1].t:0,ye=[],Se=k.filter(ae=>ae.sung>0&&ae.expected>0);if(Se.length>0){let ae=0,ue=0,Ie=0;for(let ze=0;ze<=ce;ze+=xe){const $e=ze-me/2,Ye=ze+me/2;for(;ue<Se.length&&Se[ue].t<Ye;)Math.abs(Se[ue].sung-Se[ue].expected)<=.5&&Ie++,ue++;for(;ae<ue&&Se[ae].t<$e;)Math.abs(Se[ae].sung-Se[ae].expected)<=.5&&Ie--,ae++;const je=ue-ae;ye.push({t:ze,accuracy:je>0?Ie/je*100:0})}}else for(let ae=0;ae<=ce;ae+=xe)ye.push({t:ae,accuracy:0});return{playerName:t,playerColor:n,songTitle:a,songArtist:s,songBpm:i,difficulty:o,timestamp:new Date().toISOString(),classicScore:p,bonusScore:f,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(w*10)/10,medianCentDeviation:Math.round(O*10)/10,stdDevCents:Math.round($*10)/10,intonationAccuracyPct:Math.round(L*10)/10,perfectHitPct:Math.round(U*10)/10,pitchDeviationHistogram:q,lowestHz:Math.round(re*10)/10,highestHz:Math.round(D*10)/10,lowestNote:W>0?Qn(W):"—",highestNote:j>0?Qn(j):"—",rangeInSemitones:Math.round(F*10)/10,tessituraLow:P>0?Qn(P):"—",tessituraHigh:T>0?Qn(T):"—",pitchClassDistribution:G,vibrato:Y,avgOnsetDeviationMs:Math.round(X*10)/10,rhythmStabilityPct:Math.round(le*10)/10,jitterPct:Math.round(K*100)/100,shimmerProxy:Math.round(ne*10)/10,verseMetrics:de,micSettings:m,pitchOverTime:k,accuracyOverTime:ye}}function zh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>nn(y.hz)),n=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&n[y]-n[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let v=0,x=t[o]-m,g=Math.abs(x);for(let S=o+1;S<=y;S++){const M=t[S]-m;M*x<0&&v++,x=M;const R=Math.abs(M);R>g&&(g=R)}const k=n[y]-n[o];if(k<=0)continue;const b=v/2/k;b>=3&&b<=12&&(s.push(b),i.push(g*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const u=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,p=Math.sqrt(s.reduce((y,m)=>y+(m-u)**2,0)/s.length),f=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(u*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(f)}}const Q={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function gt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Vs(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}const Oh=({reports:e,noteCount:t,uploadedSong:n=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:u,t:h,className:p,style:f,id:y,accessMode:m,"data-testid":v})=>{const{t:x}=Te(),g=h??x,k=d.useRef(null),b=d.useMemo(()=>{if(e||!n)return[];const D=qn(n.notes.map(j=>j.noteLine),n.bpm??void 0),W=(n.gap??0)/1e3;return Za(D,W)},[e,n]),S=d.useMemo(()=>e||(!n||!a||!o?[]:a.map(D=>{const W=(s==null?void 0:s[D.id])||[];return Wo({playerName:D.name,playerColor:D.color,songTitle:n.title,songArtist:n.artist,songBpm:n.bpm??0,difficulty:l,pitchPoints:W,notes:b,verseRatings:i??[],combo:o,classicScore:D.classicScore,bonusScore:D.bonusScore,totalScore:D.totalScore,micSettings:(c==null?void 0:c[D.id])??null})})),[e,n,a,s,i,o,l,b,c]),M=d.useCallback(()=>{var I,P;if(!k.current)return;const D=`<!DOCTYPE html>
46
+ -`]})]}),c&&c.length>0&&n.jsxs("div",{style:{marginTop:24},children:[n.jsx("b",{children:i("audioPitch.waveformRms","Waveform and RMS:")}),n.jsx("canvas",{width:600,height:100,style:{background:"var(--nice-bg-secondary, #222)",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:_=>{if(!_)return;const U=_.getContext("2d");if(U){U.clearRect(0,0,600,100),U.strokeStyle=Se.resolveCssColor("var(--nice-info, #0ff)",U.canvas),U.beginPath();for(let $=0;$<c.length;$+=Math.ceil(c.length/600)){const P=$/c.length*600,F=50-c[$]*48;$===0?U.moveTo(P,F):U.lineTo(P,F)}if(U.stroke(),v.length>0){U.strokeStyle=Se.resolveCssColor("var(--nice-warning, #ff0)",U.canvas),U.beginPath();for(let $=0;$<v.length;$++){const P=$/v.length*600,F=100-v[$]*90;$===0?U.moveTo(P,F):U.lineTo(P,F)}U.stroke()}}}}),n.jsxs("div",{style:{color:"var(--nice-text-muted, #aaa)",fontSize:12,marginTop:4},children:[n.jsx("span",{style:{color:"var(--nice-info, #0ff)"},children:"Waveform"}),"  | "," ",n.jsx("span",{style:{color:"var(--nice-warning, #ff0)"},children:"RMS"})]})]}),!k&&S.length===0&&!N&&n.jsx("div",{style:{marginTop:16,color:"var(--nice-text-muted, #aaa)"},children:n.jsx("i",{children:i("audioPitch.noNotesDetected","No notes detected")})}),h&&Object.keys(p).length>0&&n.jsxs("div",{style:{marginTop:16},children:[n.jsx("h4",{children:i("audioPitch.algorithmComparison","Algorithm comparison")}),Object.entries(p).map(([_,U])=>n.jsxs("div",{style:{marginBottom:12},children:[n.jsx("b",{children:_}),": ",i("audioPitch.detectedSegments","detected segments:")," ",U.length,n.jsx("pre",{style:{background:"var(--nice-text, #111)",color:"var(--nice-text-inverse, #ddd)",padding:8,borderRadius:4,marginTop:8},children:U.map($=>`: ${Math.round($.start*10)} ${Math.round($.duration*10)} ${$.pitch} [${$.freq.toFixed(1)} Hz]`).join(`
47
+ `)})]},_))]})]})}const zt=1e4,Gs=5e3;function Xr(e,t=.35){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!r)return e;const a=Math.min(255,Math.round(parseInt(r[1],16)+(255-parseInt(r[1],16))*t)),s=Math.min(255,Math.round(parseInt(r[2],16)+(255-parseInt(r[2],16))*t)),i=Math.min(255,Math.round(parseInt(r[3],16)+(255-parseInt(r[3],16))*t));return`rgb(${a},${s},${i})`}const ph=["var(--nice-warning, #facc15)","var(--nice-text-secondary, #cbd5e1)","var(--nice-warning, #d97706)"],fh=({entry:e,rank:t,animDelay:r})=>{const[a,s]=u.useState(0),[i,o]=u.useState(0),[l,c]=u.useState(0),[d,h]=u.useState(0),f=Math.min(e.classicScore,zt),p=Math.min(e.bonusScore,zt),y=f/zt*Gs,m=p>0?p/zt*Gs:0;return u.useEffect(()=>{let x,v=null;const g=Math.max(y,400),S=Math.max(m,m>0?300:0),b=k=>{v===null&&(v=k);const j=k-v-r;if(j<0){x=requestAnimationFrame(b);return}if(j<=g){const N=Math.min(1,j/g),R=1-Math.pow(1-N,3);s(Math.min(R*(f/zt)*100,100)),c(Math.round(R*e.classicScore)),x=requestAnimationFrame(b);return}if(s(Math.min(f/zt*100,100)),c(e.classicScore),S>0){const N=j-g;if(N<=S){const R=Math.min(1,N/S),w=1-Math.pow(1-R,3);o(Math.min(w*(p/zt)*100,100)),h(Math.round(w*e.bonusScore)),x=requestAnimationFrame(b);return}o(Math.min(p/zt*100,100)),h(e.bonusScore)}};return x=requestAnimationFrame(b),()=>cancelAnimationFrame(x)},[e.classicScore,e.bonusScore,y,m,r]),n.jsxs("div",{className:"karaoke-summary-bar",children:[n.jsx("span",{className:"karaoke-summary-bar-rank",children:t<=3?n.jsx(W.NtdMedal,{size:18,primaryColor:ph[t-1]}):`#${t}`}),n.jsx("span",{className:"karaoke-summary-bar-name",style:{color:e.color},children:e.name}),n.jsxs("div",{className:"karaoke-summary-bar-track",children:[e.bonusScore>0&&n.jsx("div",{className:"karaoke-summary-bar-fill-bonus",style:{width:`${Math.min(a+i,100)}%`,background:Xr(e.color,.45)}}),n.jsx("div",{className:"karaoke-summary-bar-fill-classic",style:{width:`${a}%`,background:`linear-gradient(90deg, ${e.color}, ${Xr(e.color,.15)})`,boxShadow:`0 0 8px ${e.color}55`}}),n.jsxs("div",{className:"karaoke-summary-bar-text",children:[l.toLocaleString(),d>0&&n.jsxs("span",{className:"karaoke-summary-bar-text-bonus",style:{color:Xr(e.color,.5)},children:["+",d.toLocaleString()]})]})]}),n.jsx("span",{className:"karaoke-summary-bar-total",children:(l+d).toLocaleString()})]})},Ws=({title:e,entries:t,highlightNames:r,playerColorMap:a})=>n.jsxs("div",{className:"karaoke-summary-rank",children:[n.jsx("h4",{className:"karaoke-summary-rank-title",children:e}),n.jsx("table",{className:"karaoke-summary-rank-table",children:n.jsx("tbody",{children:t.map((s,i)=>{const o=r.has(s.name),l=a.get(s.name);return n.jsxs("tr",{className:o?"karaoke-summary-rank-row karaoke-summary-rank-row--hl":"karaoke-summary-rank-row",children:[n.jsx("td",{className:`karaoke-summary-rank-pos${i<3?" karaoke-summary-rank-pos--top":""}`,children:s.rank}),n.jsxs("td",{className:"karaoke-summary-rank-name",style:l?{color:l}:void 0,children:[o&&n.jsxs(n.Fragment,{children:[n.jsx(W.NtdCircle,{size:8})," "]}),s.name]}),n.jsx("td",{className:"karaoke-summary-rank-score",children:s.score.toLocaleString()})]},`${s.name}-${i}`)})})})]}),Xa=({uploadedSong:e,playerScores:t,topSingings:r,onRestart:a,onContinue:s,t:i,renderReport:o,className:l,style:c,id:d,accessMode:h,"data-testid":f})=>{const[p,y]=u.useState(!1),m=u.useMemo(()=>[...t].sort((k,j)=>j.totalScore-k.totalScore),[t]),x=u.useMemo(()=>{const k=new Map;for(const j of t)k.set(j.name,j.color);return k},[t]),v=u.useMemo(()=>new Set(t.map(k=>k.name)),[t]),g=u.useMemo(()=>m.map((k,j)=>({rank:j+1,name:k.name,score:k.totalScore,color:k.color})),[m]),S=u.useMemo(()=>{const k=r.map(N=>({name:N.playerName,score:N.score})),j=new Set;for(const N of m)j.has(N.id)||(j.add(N.id),k.push({name:N.name,score:N.totalScore}));return k.sort((N,R)=>R.score-N.score),k.slice(0,10).map((N,R)=>({rank:R+1,name:N.name,score:N.score}))},[r,m]),b=e?e.artist?`${e.artist} — ${e.title}`:e.title:i("karaokeSummary.unknownSong","Unknown song");return h==="hidden"?null:n.jsxs("div",{className:`karaoke-summary-overlay${l?` ${l}`:""}`,style:c,id:d,"data-testid":f,children:[n.jsxs("div",{className:"karaoke-summary-card",children:[n.jsx("h1",{className:"karaoke-summary-title",children:b}),n.jsx("div",{className:"karaoke-summary-bars",children:m.length===0?n.jsx("div",{className:"karaoke-summary-empty",children:i("karaokeSummary.noScores","No scores")}):m.map((k,j)=>n.jsx(fh,{entry:k,rank:j+1,animDelay:j*300},k.id))}),(m.length>1||r.length>0)&&n.jsxs("div",{className:"karaoke-summary-ranks",children:[m.length>1&&n.jsx(Ws,{title:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdHome,{size:14})," ",i("karaokeSummary.localRanking","Session ranking")]}),entries:g,highlightNames:v,playerColorMap:x}),r.length>0&&n.jsx(Ws,{title:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdTrophy,{size:14})," ",i("karaokeSummary.globalRanking","Top 10")]}),entries:S,highlightNames:v,playerColorMap:x})]}),n.jsxs("div",{className:"karaoke-summary-actions",children:[o&&n.jsxs("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--report",onClick:()=>y(!0),children:[n.jsx(W.NtdBarChart,{size:15})," ",i("karaokeSummary.report","Report")]}),n.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--restart",onClick:a,children:i("karaokeSummary.restart","Restart")}),n.jsx("button",{type:"button",className:"karaoke-summary-btn karaoke-summary-btn--continue",onClick:s,children:i("karaokeSummary.continue","Continue")})]})]}),p&&(o==null?void 0:o(()=>y(!1)))]})},mh=ot.scoped("GenericPlayer"),gh=e=>/youtu(\.be|be\.com)/i.test(e),yo=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),yh=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),bh=e=>{var i;if(!((i=e==null?void 0:e.sources)!=null&&i.length))return null;const t=o=>e.sources.find(l=>l.kind===o),r=e.sources.find(o=>o.kind==="youtube"&&(o.videoId||o.url&&gh(o.url)))??null;if(r)return r;const a=t("hls")||e.sources.find(o=>o.url&&yo(o.url))||null;if(a)return a;const s=t("audio")||e.sources.find(o=>o.url&&yh(o.url))||null;return s||(e.sources[0]??null)},Er=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`},vh=[.25,.5,.75,1,1.25,1.5,1.75,2],Za=({tracks:e=[],initialIndex:t=0,autoPlay:r=!0,countdownSeconds:a=0,height:s=360,onIndexChange:i,onPlayingChange:o,onTimeUpdate:l,externalRef:c,uiMode:d="full",compactNextCount:h=3,progressBarPosition:f="inline",loop:p=!1,onEnded:y,enableKeyboardShortcuts:m=!0,shuffle:x=!1,repeatMode:v="none",playbackSpeed:g=1,abLoop:S=null,onRepeatModeChange:b,onShuffleChange:k,onSpeedChange:j,sleepTimer:N=0,onSleepTimerExpired:R})=>{const{t:w}=Te(),[M,I]=u.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),A=e[M],T=u.useMemo(()=>bh(A),[A]),[O,E]=u.useState(!1),[V,ee]=u.useState(0),[z,q]=u.useState(0),[K,re]=u.useState(.9),[_,U]=u.useState(null),[$,P]=u.useState(null),F=u.useRef(null),[D,C]=u.useState(x),[L,B]=u.useState(v),[G,H]=u.useState(g),[X,oe]=u.useState(S),[le,ne]=u.useState([]),[Z,Y]=u.useState(N>0?N*60:null),se=u.useRef(null),[ae,ue]=u.useState(()=>Ni()),J=u.useRef(null),de=u.useRef(null),me=u.useRef(null),ve=u.useRef(null);u.useEffect(()=>{if(D&&e.length>0){const fe=e.map((be,_e)=>_e);for(let be=fe.length-1;be>0;be--){const _e=Math.floor(Math.random()*(be+1));[fe[be],fe[_e]]=[fe[_e],fe[be]]}ne(fe)}},[D,e.length]),u.useEffect(()=>(se.current&&(window.clearInterval(se.current),se.current=null),N>0&&O&&(Y(N*60),se.current=window.setInterval(()=>{Y(fe=>!fe||fe<=1?(se.current&&window.clearInterval(se.current),se.current=null,R==null||R(),null):fe-1)},1e3)),()=>{se.current&&window.clearInterval(se.current)}),[N,O]);const ce=u.useCallback(fe=>{const be=Math.min(Math.max(0,fe),Math.max(0,e.length-1));I(be),i==null||i(be)},[e.length,i]),ye=u.useCallback(()=>{if(D&&le.length>0){const be=le.indexOf(M)+1;return be<le.length?le[be]:L==="all"?le[0]:-1}return M<e.length-1?M+1:L==="all"?0:-1},[M,e.length,D,le,L]),ke=u.useCallback(()=>{if(D&&le.length>0){const fe=le.indexOf(M);return fe>0?le[fe-1]:L==="all"?le[le.length-1]:-1}return M>0?M-1:L==="all"?e.length-1:-1},[M,e.length,D,le,L]),ie=u.useCallback(()=>{const fe=ye();fe>=0&&ce(fe)},[ye,ce]),he=u.useCallback(async()=>{var fe,be;await Gt(),ue(!0),(T==null?void 0:T.kind)==="youtube"?(fe=J.current)==null||fe.playVideo():(be=de.current)==null||be.play(),E(!0),o==null||o(!0)},[T,o]),Le=u.useCallback(()=>{var fe,be;(T==null?void 0:T.kind)==="youtube"?(fe=J.current)==null||fe.pauseVideo():(be=de.current)==null||be.pause(),E(!1),o==null||o(!1)},[T,o]),Oe=u.useCallback(()=>O?Le():he(),[O,he,Le]),Pe=u.useCallback(fe=>{var pe;const be=(A==null?void 0:A.startOffset)??0,_e=fe+be;(T==null?void 0:T.kind)==="youtube"?(pe=J.current)==null||pe.seekTo(_e,!0):de.current&&(de.current.currentTime=_e);const St=Math.max(0,fe);q(St),l==null||l(St)},[T,l]),Xe=u.useCallback(()=>{if(z>3){Pe(0);return}const fe=ke();fe>=0&&ce(fe)},[ke,ce,z,Pe]),je=u.useCallback(fe=>{var be,_e;re(fe),U(null),(T==null?void 0:T.kind)==="youtube"?(_e=(be=J.current)==null?void 0:be.setVolume)==null||_e.call(be,Math.round(fe*100)):de.current&&(de.current.volume=fe)},[T]),He=u.useCallback(()=>{_!==null?je(_):(U(K),je(0))},[K,_,je]),pt=u.useCallback(fe=>{var be,_e;H(fe),de.current&&(de.current.playbackRate=fe),(T==null?void 0:T.kind)==="youtube"&&((_e=(be=J.current)==null?void 0:be.setPlaybackRate)==null||_e.call(be,fe)),j==null||j(fe)},[T,j]),tt=u.useCallback(()=>{const fe=["none","all","one"],be=fe[(fe.indexOf(L)+1)%fe.length];B(be),b==null||b(be)},[L,b]),Ze=u.useCallback(()=>{const fe=!D;C(fe),k==null||k(fe)},[D,k]),It=u.useCallback(fe=>{oe(fe)},[]);u.useImperativeHandle(c,()=>({play:he,pause:Le,toggle:Oe,seekTo:Pe,setVolume:je,setSpeed:pt,setRepeatMode:fe=>{B(fe),b==null||b(fe)},toggleShuffle:Ze,setABLoop:It,getUnderlyingPlayer:()=>(T==null?void 0:T.kind)==="youtube"?J.current:(T==null?void 0:T.kind)==="hls"||(T==null?void 0:T.kind)==="audio"?de.current:null}),[he,Le,Oe,Pe,je,pt,Ze,It,T==null?void 0:T.kind]),u.useEffect(()=>{const fe=window.setInterval(()=>{let be=0,_e=0;(T==null?void 0:T.kind)==="youtube"&&J.current?(be=J.current.getCurrentTime()||0,_e=J.current.getDuration()||0):de.current&&(be=de.current.currentTime||0,_e=de.current.duration||0);const St=(A==null?void 0:A.startOffset)??0,pe=Math.max(0,be-St);q(pe),ee(_e),l==null||l(pe),X&&pe>=X.b&&Pe(X.a)},250);return()=>window.clearInterval(fe)},[T==null?void 0:T.kind,l,X]),u.useEffect(()=>()=>{F.current&&(window.clearInterval(F.current),F.current=null)},[]),u.useEffect(()=>{if(me.current){try{me.current.destroy()}catch{}me.current=null}if(de.current&&(de.current.volume=K,de.current.crossOrigin=T!=null&&T.withCredentials?"use-credentials":"anonymous"),(T==null?void 0:T.kind)==="hls"&&yo(T.url)){const fe=de.current;if(!fe)return;const be=()=>{fe.src=T.url,fe.load();const _e=(A==null?void 0:A.startOffset)??0;try{_e&&!isNaN(_e)&&(fe.currentTime=_e)}catch{}r&&fe.play().catch(()=>{})};fe.canPlayType("application/vnd.apple.mpegurl")?be():(async()=>{var _e;try{const pe=(await import("hls.js")).default;if((_e=pe==null?void 0:pe.isSupported)!=null&&_e.call(pe)){const xe=new pe({xhrSetup:qe=>{if(T!=null&&T.withCredentials&&(qe.withCredentials=!0),T!=null&&T.headers)for(const[Ie,Me]of Object.entries(T.headers))try{qe.setRequestHeader(Ie,Me)}catch{}}});me.current=xe,xe.loadSource(T.url),xe.attachMedia(fe),xe.on(pe.Events.MANIFEST_PARSED,()=>{r&&fe.play().catch(()=>{})})}else be()}catch(St){mh.debug("HLS.js setup failed, falling back to native playback",St),be()}})()}else if((T==null?void 0:T.kind)==="audio"&&T.url&&de.current){const fe=de.current;fe.src=T.url,fe.load();const be=(A==null?void 0:A.startOffset)??0;try{be&&!isNaN(be)&&(fe.currentTime=be)}catch{}r&&fe.play().catch(()=>{})}F.current&&(window.clearInterval(F.current),F.current=null),P(null),q(0),ee(0),r&&(T==null?void 0:T.kind)==="youtube"&&a>0?(P(a),F.current=window.setInterval(()=>{P(fe=>{var be;if(!fe)return null;if(fe<=1){F.current&&(window.clearInterval(F.current),F.current=null);try{(be=J.current)==null||be.playVideo()}catch{}return E(!0),o==null||o(!0),null}return fe-1})},1e3)):E(!!r)},[T==null?void 0:T.url,T==null?void 0:T.kind,T==null?void 0:T.withCredentials,JSON.stringify(T==null?void 0:T.headers),r,K]);const ft=u.useCallback(()=>{if(L==="one"){Pe(0),he();return}const fe=ye();fe>=0?ce(fe):(E(!1),o==null||o(!1),Pe(0),y==null||y())},[L,ye,ce,o,Pe,y,he]);u.useEffect(()=>{if(!m)return;const fe=be=>{const _e=be.target;if(!(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable))switch(be.key){case" ":be.preventDefault(),Oe();break;case"ArrowRight":be.preventDefault(),Pe(Math.min(z+5,V));break;case"ArrowLeft":be.preventDefault(),Pe(Math.max(0,z-5));break;case"ArrowUp":be.preventDefault(),je(Math.min(1,K+.05));break;case"ArrowDown":be.preventDefault(),je(Math.max(0,K-.05));break;case"m":case"M":He();break;case"n":case"N":ie();break;case"p":case"P":Xe();break;case"r":case"R":tt();break;case"s":case"S":Ze();break}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[m,Oe,Pe,z,V,je,K,He,ie,Xe,tt,Ze]);const Lt=(T==null?void 0:T.kind)==="youtube"||d==="full"||d==="nobuttons",dt=h>0?e.slice(M+1,M+1+h):[];return n.jsxs("div",{ref:ve,className:"gp-player",style:{display:"grid",gap:12},tabIndex:-1,children:[r&&!ae&&n.jsx("div",{className:"gp-audio-activation",onClick:()=>{ue(!0),he()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",cursor:"pointer"},children:n.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),Lt&&n.jsxs("div",{className:"gp-stage",style:{width:"100%",height:s,background:(T==null?void 0:T.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(T==null?void 0:T.kind)==="youtube"&&n.jsx(Na,{videoId:T.videoId??jh(T.url),onReady:fe=>{J.current=fe.target,je(K);const be=(A==null?void 0:A.startOffset)??0;try{be&&fe.target.seekTo(be,!0)}catch{}if(d==="nobuttons"){try{fe.target.playVideo()}catch{}E(!0)}},onEnd:ft,opts:{width:"100%",height:"100%",playerVars:{autoplay:r||d==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:p?1:0}},style:{width:"100%",height:"100%"}}),$!==null&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-70, rgba(0, 0, 0, 0.7))"},children:n.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:$})}),d==="nobuttons"&&n.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((T==null?void 0:T.kind)==="audio"||(T==null?void 0:T.kind)==="hls")&&n.jsxs(n.Fragment,{children:[d==="full"&&n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, rgba(255, 255, 255, 0.9))"},children:A!=null&&A.coverUrl?n.jsx("img",{alt:"cover",src:A.coverUrl,style:{height:s-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[A==null?void 0:A.artist," — ",A==null?void 0:A.title]}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:(T==null?void 0:T.label)??`${(T==null?void 0:T.codec)??""} ${(T==null?void 0:T.quality)??""}`.trim()})]})}),n.jsx("audio",{ref:de,onEnded:ft,onLoadedMetadata:()=>{const fe=de.current;fe&&ee(fe.duration||0)},crossOrigin:T!=null&&T.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&n.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:(A==null?void 0:A.title)??""}),n.jsx("div",{style:{color:"var(--nice-text-secondary, #64748b)",fontSize:13},children:(A==null?void 0:A.artist)??""})]})}),d==="full"&&n.jsxs(n.Fragment,{children:[n.jsx(bo,{currentTime:z,duration:V}),n.jsx(xh,{isPlaying:O,index:M,count:e.length,currentTime:z,duration:V,volume:K,onPrev:Xe,onNext:ie,onToggle:Oe,onSeek:Pe,onVolume:je}),n.jsx(Ch,{shuffleOn:D,repeatMode:L,speed:G,abLoop:X,currentTime:z,sleepRemaining:Z,onToggleShuffle:Ze,onCycleRepeat:tt,onSpeedChange:pt,onSetABLoop:It,onMuteToggle:He,isMuted:_!==null})]}),d==="progressOnly"&&n.jsx("div",{style:f==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"var(--nice-overlay-90, rgba(15, 23, 42, 0.9))",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:n.jsx(Sh,{currentTime:z,duration:V,onSeek:Pe})}),(d==="minimal"||d==="compact")&&n.jsx(kh,{isPlaying:O,canPrev:M>0,canNext:M<e.length-1,onPrev:Xe,onNext:ie,onToggle:Oe}),d==="compact"&&dt.length>0&&n.jsx(wh,{items:dt,onSelect:fe=>ce(M+1+fe)}),d==="nobuttons"&&n.jsx(n.Fragment,{}),d==="full"&&e.length>0&&n.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((fe,be)=>n.jsxs("button",{onClick:()=>ce(be),style:{textAlign:"left",border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"8px 10px",background:be===M?"color-mix(in srgb, var(--nice-color-primary) 14%, transparent)":"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},title:fe.sources.map(_e=>_e.kind).join(", "),children:[n.jsx("div",{style:{fontWeight:600},children:fe.title}),n.jsx("div",{style:{color:"var(--nice-text-secondary)",fontSize:12},children:fe.artist})]},fe.id))})]})},vt={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},bo=({currentTime:e,duration:t})=>n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[n.jsx("div",{}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary, #64748b)"},children:[Er(e)," / ",Er(t)]})]}),xh=({isPlaying:e,index:t,count:r,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Te();return n.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:o,disabled:t<=0,title:f("player.previousTrack","Previous track"),"aria-label":f("player.previousTrack","Previous track"),style:vt,children:n.jsx(W.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:c,title:e?f("player.pause","Pause"):f("player.play","Play"),"aria-label":e?f("player.pause","Pause"):f("player.play","Play"),style:vt,children:e?n.jsx(W.NtdPause,{size:16}):n.jsx(W.NtdPlay,{size:16})}),n.jsx("button",{onClick:l,disabled:t>=r-1,title:f("player.nextTrack","Next track"),"aria-label":f("player.nextTrack","Next track"),style:vt,children:n.jsx(W.NtdSkipForward,{size:16})})]}),n.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,onChange:p=>d(parseFloat(p.target.value)),"aria-label":"Seek position"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdVolume,{size:16}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,onChange:p=>h(parseFloat(p.target.value)),"aria-label":"Volume"})]})]})},Sh=({currentTime:e,duration:t,onSeek:r})=>n.jsxs(n.Fragment,{children:[n.jsx(bo,{currentTime:e,duration:t}),n.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:a=>r(parseFloat(a.target.value)),"aria-label":"Seek position"})]}),kh=({isPlaying:e,canPrev:t,canNext:r,onPrev:a,onNext:s,onToggle:i})=>{const{t:o}=Te();return n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[n.jsx("button",{onClick:a,disabled:!t,title:o("player.previousTrack","Previous track"),"aria-label":o("player.previousTrack","Previous track"),style:vt,children:n.jsx(W.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:i,title:e?o("player.pause","Pause"):o("player.play","Play"),"aria-label":e?o("player.pause","Pause"):o("player.play","Play"),style:vt,children:e?n.jsx(W.NtdPause,{size:16}):n.jsx(W.NtdPlay,{size:16})}),n.jsx("button",{onClick:s,disabled:!r,title:o("player.nextTrack","Next track"),"aria-label":o("player.nextTrack","Next track"),style:vt,children:n.jsx(W.NtdSkipForward,{size:16})})]})},wh=({items:e,onSelect:t})=>{const{t:r}=Te();return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color)",borderRadius:8,padding:10,background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)"},children:[n.jsx("div",{style:{fontWeight:600,marginBottom:6},children:r("player.upNext","Up next")}),n.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((a,s)=>n.jsx("li",{style:{marginBottom:4},children:n.jsxs("button",{type:"button",onClick:()=>t(s),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--nice-text-primary, #0f172a)"},title:a.sources.map(i=>i.kind).join(", "),children:[n.jsx("span",{style:{fontWeight:600},children:a.artist})," — ",a.title]})},a.id))})]})},Ch=({shuffleOn:e,repeatMode:t,speed:r,abLoop:a,currentTime:s,sleepRemaining:i,onToggleShuffle:o,onCycleRepeat:l,onSpeedChange:c,onSetABLoop:d,onMuteToggle:h,isMuted:f})=>{const{t:p}=Te(),y={none:"Off",all:"All",one:"One"},m=t==="one"?n.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[n.jsx(W.NtdRepeat,{size:16}),n.jsx("span",{style:{position:"absolute",right:-3,bottom:-3,fontSize:8,fontWeight:700},children:"1"})]}):t==="all"?n.jsx(W.NtdRepeat,{size:16}):n.jsx(W.NtdArrowRight,{size:16});return n.jsxs("div",{className:"gp-pro-controls",style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap",fontSize:13},children:[n.jsx("button",{onClick:o,title:p("player.shuffle","Shuffle"),"aria-label":p("player.shuffle","Shuffle"),style:{...vt,opacity:e?1:.4,fontWeight:e?700:400},children:n.jsx(W.NtdShuffle,{size:16})}),n.jsx("button",{onClick:l,title:`${p("player.repeat","Repeat")}: ${y[t]}`,"aria-label":`${p("player.repeat","Repeat")}: ${y[t]}`,style:{...vt,opacity:t==="none"?.4:1},children:m}),n.jsx("select",{value:r,onChange:x=>c(parseFloat(x.target.value)),title:p("player.speed","Speed"),"aria-label":p("player.speed","Speed"),style:{...vt,minWidth:56,fontSize:12},children:vh.map(x=>n.jsxs("option",{value:x,children:[x,"x"]},x))}),n.jsx("button",{onClick:h,title:p("player.mute","Mute"),"aria-label":p("player.mute","Mute"),style:{...vt,opacity:f?1:.6},children:f?n.jsx(W.NtdVolumeMute,{size:16}):n.jsx(W.NtdVolume,{size:16})}),a?n.jsxs("span",{style:{display:"flex",gap:4,alignItems:"center"},children:[n.jsxs("span",{style:{fontSize:11,color:"var(--nice-text-secondary, #64748b)"},children:["A: ",Er(a.a)," — B: ",Er(a.b)]}),n.jsx("button",{onClick:()=>d(null),title:p("player.clearLoop","Clear loop"),style:{...vt,fontSize:11,padding:"2px 6px"},children:n.jsx(W.NtdClose,{size:12})})]}):n.jsx("button",{onClick:()=>d({a:s,b:s+10}),title:p("player.abLoop","A-B Loop"),"aria-label":p("player.abLoop","Set A-B Loop"),style:{...vt,opacity:.4},children:"A-B"}),i!==null&&i>0&&n.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--nice-text-secondary, #64748b)",display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdMoon,{size:12})," ",Math.floor(i/60),":",(i%60).toString().padStart(2,"0")]})]})};function jh(e){if(!e)return;const t=e.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/);if(t)return t[1];const r=e.match(/[?&]v=([A-Za-z0-9_-]{6,})/);if(r)return r[1]}function vo(e){const t={};if(!e)return t;const r=e.split(",");for(const a of r){const s=a.trim();s.startsWith("v=")?t.youtubeId=s.substring(2):s.startsWith("co=")?t.coverImage=s.substring(3):s.startsWith("bg=")&&(t.backgroundImage=s.substring(3))}return t}function Mh(e,t="/api/karaoke/cover"){var a,s;const r=((a=e.coverImage)==null?void 0:a.startsWith("http://"))||((s=e.coverImage)==null?void 0:s.startsWith("https://"));return e.coverImage&&r?e.coverImage:e.youtubeId?`https://img.youtube.com/vi/${e.youtubeId}/hqdefault.jpg`:e.coverImage?`${t}?filePath=${encodeURIComponent(e.coverImage)}`:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='320' height='180'%3E%3Crect width='320' height='180' fill='%23333'/%3E%3Ctext x='160' y='95' text-anchor='middle' fill='%23999' font-size='16'%3ENo Cover%3C/text%3E%3C/svg%3E"}function Rh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function xo(e,t,r=.01){let a=0;for(let o=0;o<e.length;o++)a+=e[o]*e[o];if(a=Math.sqrt(a/e.length),a<r)return 0;let s=-1,i=0;for(let o=20;o<e.length/2;o++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+o];l/=e.length/2,l>i&&(i=l,s=o)}return s>0?t/s:0}function Qa(e,t){const r=[];return e.forEach((a,s)=>{a.forEach((i,o)=>{r.push({startTime:i.startTime+t,duration:i.duration,pitch:i.pitch,isGold:i.isGold,line:s,idx:o})})}),r}function So(e,t,r){const a=[];return e.forEach(s=>{var c;const[i,o]=s.noteKey.split("-").map(Number),l=(c=t[i])==null?void 0:c[o];l&&s.segments.forEach(d=>{a.push({start:d.visualStart-r,end:d.visualEnd-r,pitch:l.pitch,frac:d.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),a}function ko(e,t=120){let r=e;if(e.length>t){const a=e.length/t,s=[];for(let i=0;i<t;i++)s.push(e[Math.floor(i*a)]);r=s}return r.map(a=>({t:Math.round(a.t*1e3)/1e3,hz:Math.round(a.hz)}))}function wo(e,t,r){const s=Date.parse(e)-r;return Math.max(0,Math.round(t-s))}const Co={crepe:"var(--nice-accent, #a78bfa)",librosa:"var(--nice-success-light, #34d399)",pitchy:"var(--nice-primary-light, #60a5fa)",autocorr:"var(--nice-text-secondary, #555555)"};function Nh(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function Th(e){return Co[e]??"var(--nice-text-secondary, #555555)"}function $h(e){const t=Co[e]??"var(--nice-text-secondary, #555555)";return`var(--algo-${e}, ${t})`}function jo(e,t){const r=!(t!=null&&t.includes("no-music")),a=t==null?void 0:t.includes("instrumental"),s=[];if(r){if(e.videoPath){let i=e.videoPath;if(i.startsWith("v=")){const o=vo(i);o.youtubeId&&(i=`https://www.youtube.com/watch?v=${o.youtubeId}`)}/youtu(\.be|be\.com)/i.test(i)?s.push({kind:"youtube",url:i}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&s.push({kind:"audio",url:e.videoPath})}if(s.length===0){const i=a?e.instrumentalPath:e.audioPath;i&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(i)&&s.push({kind:"audio",url:i})}s.length===0&&e.youtubeId&&s.push({kind:"youtube",url:`https://www.youtube.com/watch?v=${e.youtubeId}`})}return{id:String(e.id??e.title??"song"),title:e.title??"—",artist:e.artist??"—",coverUrl:e.coverPath??void 0,sources:s}}function Ph(e){const t=e.videoPath??e.video??void 0;return{id:e.id,title:e.title??"",artist:e.artist??"",year:e.year,genre:e.genre,language:e.language,filePath:e.filePath,coverPath:e.coverPath,audioPath:e.audioPath??e.audio??void 0,videoPath:t,format:0,notes:e.notes??[],gap:e.gap,bpm:e.bpm,videoGap:e.videoGap,start:e.start,end:e.end,youtubeId:e.youtubeId,instrumentalPath:e.instrumentalPath,isVerified:e.isVerified,coverImage:e.coverImage,backgroundImage:e.backgroundImage}}var Ja=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Ja||{});function Mo(e,t="song.txt"){const r=e.split(/\r?\n/),a={},s=[];for(const o of r){const l=o.replace(/\uFEFF/g,"");if(l.trim()){if(l.startsWith("#")){const c=l.indexOf(":");c>0&&(a[l.slice(1,c).trim().toUpperCase()]=l.slice(c+1).trim())}else if(/^[:*\-FG]/.test(l))s.push({noteLine:l});else if(l.trim()==="E")break}}const i=o=>{if(!o)return;const l=parseFloat(o.replace(",","."));return Number.isFinite(l)?l:void 0};return{title:a.TITLE||t.replace(/\.txt$/i,""),artist:a.ARTIST||"",format:Ja.Ultrastar,bpm:i(a.BPM),gap:i(a.GAP),genre:a.GENRE||void 0,language:a.LANGUAGE||void 0,year:a.YEAR||void 0,audioPath:a.MP3||void 0,videoPath:a.VIDEO||a.MP3||void 0,notes:s}}const Ah=e=>window.btoa(unescape(encodeURIComponent(e))),Ro=({onSongUpload:e,parseSong:t,onError:r,accept:a=".txt",maxFileSize:s=5*1024*1024,t:i})=>{const{t:o}=Te(),l=i??o,c=h=>{const f=new FileReader;f.onload=async p=>{var m;if(!((m=p.target)!=null&&m.result))return;const y=p.target.result;try{const x=t?await t({fileName:h.name,data:Ah(y)}):Mo(y,h.name);e(x)}catch(x){r==null||r(x)}},f.readAsText(h,"UTF-8")},d=h=>/\.txt$/i.test(h.name)?h.size===0?l("karaokeUploader.empty","The file is empty."):null:l("karaokeUploader.notTxt","Please choose an UltraStar .txt file.");return n.jsx("div",{className:"nice-karaoke-uploader",children:n.jsx(Ce.NiceUpload,{accept:a,maxFileSize:s,validateFile:d,multiple:!1,text:l("karaokeUploader.dropPrompt","Click or drag & drop an UltraStar file (.txt)"),onFilesSelected:h=>{const f=h[0];f&&c(f)}})})};function Eh(e,t,r,a,s){const o=a*.45;e.beginPath();for(let l=0;l<10;l++){const c=l%2===0?a:o,d=Math.PI/5*l-Math.PI/2,h=t+Math.cos(d)*c,f=r+Math.sin(d)*c;l===0?e.moveTo(h,f):e.lineTo(h,f)}e.closePath(),e.fillStyle=s,e.fill()}const Ut=60,Us=4,qs=["A","B","X","Y","LB","RB","LT","RT"],No=({lanes:e,events:t,currentTime:r,activeLanes:a,difficulty:s,feedbackQueue:i,isPlaying:o,height:l=300})=>{const c=e.length,d=u.useRef(null),h=u.useRef([]);return u.useEffect(()=>{h.current=i},[i]),u.useEffect(()=>{var b,k,j,N;const f=d.current;if(!f)return;const p=f.getContext("2d");if(!p)return;const y=window.devicePixelRatio||1,m=f.clientWidth,x=f.clientHeight;if(f.width=m*y,f.height=x*y,p.scale(y,y),p.clearRect(0,0,m,x),c===0)return;const v=m/c;for(let R=0;R<c;R++){const w=R*v;p.fillStyle=R%2===0?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",p.fillRect(w,0,v,x),R>0&&(p.strokeStyle="rgba(255,255,255,0.1)",p.lineWidth=1,p.beginPath(),p.moveTo(w,0),p.lineTo(w,x),p.stroke())}const g=x-Ut-10;p.strokeStyle="rgba(255,255,255,0.4)",p.lineWidth=2,p.setLineDash([8,4]),p.beginPath(),p.moveTo(0,g),p.lineTo(m,g),p.stroke(),p.setLineDash([]);const S=(x-Ut-20)/Us;for(const R of t){const w=R.note.startTime,M=w+R.note.duration,I=w-r;if(I>Us||M<r-.5)continue;const A=R.lane,T=A*v+4,O=v-8,E=g-I*S,V=R.note.duration*S,ee=r>=w-.15&&r<=M+.15,z=r>M+.15,q=((b=e[A])==null?void 0:b.color)??"#888";z?p.fillStyle="rgba(100,100,100,0.3)":ee?(p.fillStyle=q,p.shadowColor=q,p.shadowBlur=12):p.fillStyle=q+"99";const K=Math.max(V,8),re=6;p.beginPath(),p.moveTo(T+re,E),p.lineTo(T+O-re,E),p.quadraticCurveTo(T+O,E,T+O,E+re),p.lineTo(T+O,E+K-re),p.quadraticCurveTo(T+O,E+K,T+O-re,E+K),p.lineTo(T+re,E+K),p.quadraticCurveTo(T,E+K,T,E+K-re),p.lineTo(T,E+re),p.quadraticCurveTo(T,E,T+re,E),p.fill(),p.shadowBlur=0,R.note.isGold&&Eh(p,T+O/2,E+K/2,Math.min(7,O/4),"#fbbf24")}for(let R=0;R<c;R++){const w=R*v,M=x-Ut,I=a[R],A=((k=e[R])==null?void 0:k.color)??"#888";p.fillStyle=I?A:"rgba(30,30,30,0.9)",p.fillRect(w+2,M+2,v-4,Ut-4),p.strokeStyle=I?"#fff":A,p.lineWidth=I?3:1,p.strokeRect(w+2,M+2,v-4,Ut-4),p.fillStyle=I?"#000":"#fff",p.font=`bold ${Math.min(24,v*.3)}px monospace`,p.textAlign="center",p.textBaseline="middle",p.fillText(((j=e[R])==null?void 0:j.label)??"",w+v/2,M+Ut/2);const T=((N=e[R])==null?void 0:N.gamepadButton)??-1;T>=0&&T<qs.length&&(p.fillStyle=I?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.4)",p.font="10px sans-serif",p.fillText(qs[T],w+v/2,M+Ut-8))}for(const R of h.current){const w=r-R.time;if(w<0||w>.8)continue;const M=Math.max(0,1-w/.8),I=R.lane*v;p.save(),p.globalAlpha=M,p.font="bold 20px sans-serif",p.textAlign="center",p.textBaseline="bottom",p.fillStyle=R.type==="perfect"?"#10b981":R.type==="good"?"#f59e0b":"#ef4444";const A=R.type==="perfect"?"PERFECT":R.type==="good"?"GOOD":"MISS";p.fillText(A,I+v/2,g-10-w*40),p.restore()}},[r,e,t,a,c,o]),!o||c===0?null:n.jsxs("div",{className:"nice-pad-karaoke-overlay",style:{position:"absolute",top:0,left:0,right:0,height:l,zIndex:35,pointerEvents:"none"},children:[n.jsx("canvas",{ref:d,role:"img","aria-label":"Pad karaoke note highway — hit notes in time with the music",style:{width:"100%",height:"100%",display:"block"}}),n.jsxs("div",{style:{position:"absolute",top:8,right:12,background:"var(--nice-overlay-60, rgba(0,0,0,0.6))",color:"#fff",padding:"4px 12px",borderRadius:8,fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:1,display:"flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdGamepad,{size:14})," PAD — ",s]})]})},In=["var(--player-color-1, #ef4444)","var(--player-color-2, #f59e0b)","var(--player-color-3, #10b981)","var(--player-color-4, #3b82f6)","var(--player-color-5, #8b5cf6)","var(--player-color-6, #ec4899)"],To={easy:{keys:["f","j"],buttons:[0,1],labels:["F","J"]},normal:{keys:["d","f","j","k"],buttons:[3,2,0,1],labels:["D","F","J","K"]},hard:{keys:["s","d","f","j","k","l"],buttons:[4,3,2,0,1,5],labels:["S","D","F","J","K","L"]}};function pa(e){return 440*Math.pow(2,(e-69)/12)}function $o(e,t){const r=To[t],a=r.keys.length,s=[];for(const d of e)for(const h of d)s.includes(h.pitch)||s.push(h.pitch);if(s.sort((d,h)=>d-h),s.length===0)return r.keys.map((d,h)=>({index:h,key:d,gamepadButton:r.buttons[h],label:r.labels[h],minPitch:-999,maxPitch:999,color:In[h%In.length]}));const i=s[0],l=s[s.length-1]-i+1,c=[];for(let d=0;d<a;d++){const h=i+Math.floor(l*d/a),f=i+Math.floor(l*(d+1)/a)-1;c.push({index:d,key:r.keys[d],gamepadButton:r.buttons[d],label:r.labels[d],minPitch:d===0?-999:h,maxPitch:d===a-1?999:f,color:In[d%In.length]})}return c}function Po(e,t){for(const s of t)if(e>=s.minPitch&&e<=s.maxPitch)return s.index;let r=0,a=1/0;for(const s of t){const i=(s.minPitch+s.maxPitch)/2,o=Math.abs(e-i);o<a&&(a=o,r=s.index)}return r}function Ao(e,t,r){const a=[];for(let s=0;s<e.length;s++)for(let i=0;i<e[s].length;i++){const o={...e[s][i]};o.startTime+=r,a.push({note:o,lane:Po(o.pitch,t),lineIndex:s,noteIndex:i})}return a.sort((s,i)=>s.note.startTime-i.note.startTime),a}class Eo{constructor(t){this.lanes=[],this.events=[],this.raf=null,this.keysDown=new Set,this.gamepadButtonsDown=new Set,this.running=!1,this.getCurrentTime=()=>0,this.lastFeedbackTime=0,this.lastActiveNote=null,this.preWindow=.15,this.postWindow=.15,this.loop=()=>{var c,d,h,f,p,y,m,x;if(!this.running)return;const s=this.getCurrentTime();this.pollGamepad();const i=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,i);const o=this.findActiveNote(s);if(o!==this.lastActiveNote&&(this.lastActiveNote=o,(f=(h=this.config).onCurrentNote)==null||f.call(h,o)),i.some(Boolean)&&o){const v=o.lane,g=i.indexOf(!0);if(i[v]){const S=pa(o.note.pitch);this.config.onPitch(S),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(y=(p=this.config).onHitFeedback)==null||y.call(p,{type:"perfect",lane:v,time:s}))}else if(g>=0){const b=Math.abs(g-v)*3,k=pa(o.note.pitch+b);this.config.onPitch(k),s-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=s,(x=(m=this.config).onHitFeedback)==null||x.call(m,{type:"miss",lane:g,time:s}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const r=Hn(t.noteLines,t.bpm),a=(t.gap??0)/1e3;switch(this.lanes=$o(r,t.difficulty),this.events=Ao(r,this.lanes,a),t.difficulty){case"easy":this.preWindow=.25,this.postWindow=.25;break;case"normal":this.preWindow=.15,this.postWindow=.15;break;case"hard":this.preWindow=.08,this.postWindow=.08;break}}getLanes(){return this.lanes}getEvents(){return this.events}start(t){this.running||(this.running=!0,this.getCurrentTime=t,this.handleKeyDown=this.handleKeyDown.bind(this),this.handleKeyUp=this.handleKeyUp.bind(this),window.addEventListener("keydown",this.handleKeyDown),window.addEventListener("keyup",this.handleKeyUp),this.loop())}stop(){this.running=!1,this.raf&&(cancelAnimationFrame(this.raf),this.raf=null),window.removeEventListener("keydown",this.handleKeyDown),window.removeEventListener("keyup",this.handleKeyUp),this.keysDown.clear(),this.gamepadButtonsDown.clear()}handleKeyDown(t){var a;const r=(a=t.target)==null?void 0:a.tagName;r&&["INPUT","TEXTAREA","SELECT"].includes(r)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var a;const t=navigator.getGamepads?Array.from(navigator.getGamepads()).filter(Boolean):[];if(!t.length)return;const r=t[0];if(r){this.gamepadButtonsDown.clear();for(let s=0;s<r.buttons.length;s++)(a=r.buttons[s])!=null&&a.pressed&&this.gamepadButtonsDown.add(s)}}getActiveLanes(){const t=new Array(this.lanes.length).fill(!1);for(const r of this.lanes)(this.keysDown.has(r.key)||this.gamepadButtonsDown.has(r.gamepadButton))&&(t[r.index]=!0);return t}findActiveNote(t){for(const r of this.events){const a=r.note.startTime-this.preWindow,s=r.note.startTime+r.note.duration+this.postWindow;if(t>=a&&t<=s)return r}return null}}const gt=ot.scoped("BaseStreamClient");function Vs(e,t,r){if(t===r)return e.slice();const a=Math.round(e.length*r/t),s=new Float32Array(a),i=e.length/a;for(let o=0;o<a;o++){const l=o*i,c=Math.floor(l),d=Math.min(e.length-1,c+1),h=l-c;s[o]=e[c]*(1-h)+e[d]*h}return s}function Ih(e){const t=new Int16Array(e.length);for(let r=0;r<e.length;r++){const a=Math.max(-1,Math.min(1,e[r]));t[r]=a<0?Math.round(a*32768):Math.round(a*32767)}return t}const Sn=16e3,Lh="/scripts/pitch-worklet.js";class Io{constructor(t){this.sendQueue=[],this.maxQueue=20,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.buffer=new Float32Array(0),this.externalStream=!1,this.usingWorklet=!1,this.closed=!1,this.started=!1,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,this.lastStatusLog=0,this.opts=t}onMaxReconnect(){var t,r;try{(r=(t=this.opts).onMaxReconnect)==null||r.call(t)}catch{}this.stopAudioNodes()}get useWorklet(){return!0}get workletPath(){return Lh}ts(){return new Date().toISOString().slice(11,23)}connectWs(){this.ws&&this.ws.readyState!==WebSocket.CLOSING&&this.ws.readyState!==WebSocket.CLOSED||(gt.info(`[${this.ts()}] connecting to ${this.opts.wsUrl}`),this.ws=new WebSocket(this.opts.wsUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var t,r,a,s,i,o;try{(r=(t=this.opts).onOpen)==null||r.call(t)}catch{}if(this.reconnectAttempts=0,this.chunksSent=0,this.chunksDropped=0,this.responsesReceived=0,gt.info(`[${this.ts()}] ws OPEN | worklet=${this.usingWorklet}`),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.sendQueue.length){const l=this.sendQueue.length;try{for(const c of this.sendQueue)try{this.ws.send(c),this.chunksSent++,(s=(a=this.opts).onSend)==null||s.call(a,c.byteLength)}catch(d){(o=(i=this.opts).onError)==null||o.call(i,d);break}}finally{this.sendQueue=[]}gt.info(`[${this.ts()}] flushed ${l} queued chunks`)}},this.ws.onclose=t=>{var r,a;try{(a=(r=this.opts).onClose)==null||a.call(r,t)}catch{}if(gt.info(`[${this.ts()}] ws CLOSE code=${t.code} clean=${t.wasClean} | sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived}`),this.sendQueue=[],this.ws=void 0,!this.closed&&this.started)if(this.reconnectAttempts++,this.reconnectAttempts<=this.maxReconnectAttempts){const s=Math.min(300*Math.pow(1.5,this.reconnectAttempts-1),5e3);gt.info(`[${this.ts()}] auto-reconnect #${this.reconnectAttempts} in ${s.toFixed(0)}ms`),this.reconnectTimer=setTimeout(()=>{this.closed||this.connectWs()},s)}else gt.warn(`[${this.ts()}] max reconnect attempts reached`),this.onMaxReconnect();else this.stopAudioNodes()},this.ws.onerror=t=>{var r,a;gt.warn(`[${this.ts()}] ws ERROR`,t);try{(a=(r=this.opts).onError)==null||a.call(r,t)}catch{}},this.ws.onmessage=t=>{var r,a;this.responsesReceived++;try{const s=typeof t.data=="string"?t.data:new TextDecoder().decode(t.data);this.handleWsMessage(s)}catch(s){(a=(r=this.opts).onError)==null||a.call(r,s)}})}handleAudioFrame(t){var p,y,m,x,v,g,S,b;const r=new Float32Array(this.buffer.length+t.length);r.set(this.buffer,0),r.set(t,this.buffer.length),this.buffer=r;const a=this.audioCtx.sampleRate,s=Math.round((this.opts.chunkMs??200)*Sn/1e3),i=Math.floor(this.buffer.length*Sn/a),o=Math.floor(i/s);if(o<=0)return;const l=o*s,c=Math.floor(l*a/Sn),d=this.buffer.slice(0,c);this.buffer=this.buffer.slice(c);const h=Vs(d,a,Sn);let f=0;for(;f+s<=h.length;){const k=h.subarray(f,f+s),N=Ih(k).buffer,R=this.ws;if(R&&R.readyState===WebSocket.OPEN)try{R.send(N),this.chunksSent++,(y=(p=this.opts).onSend)==null||y.call(p,N.byteLength)}catch(M){(x=(m=this.opts).onError)==null||x.call(m,M)}else R&&R.readyState===WebSocket.CONNECTING?this.sendQueue.length<this.maxQueue&&(this.sendQueue.push(N),(g=(v=this.opts).onSend)==null||g.call(v,0)):(this.chunksDropped++,(b=(S=this.opts).onSend)==null||b.call(S,0));const w=Date.now();w-this.lastStatusLog>5e3&&(this.lastStatusLog=w,gt.info(`[${this.ts()}] STATUS: sent=${this.chunksSent} dropped=${this.chunksDropped} responses=${this.responsesReceived} ws=${(R==null?void 0:R.readyState)??"none"} worklet=${this.usingWorklet}`)),f+=s}if(f<h.length){const k=h.subarray(f),j=Vs(k,Sn,a),N=new Float32Array(j.length+this.buffer.length);N.set(j,0),N.set(this.buffer,j.length),this.buffer=N}}async setupAudioNodes(t){if(this.useWorklet)try{await this.audioCtx.audioWorklet.addModule(this.workletPath);const a=new AudioWorkletNode(this.audioCtx,"pitch-processor");a.port.onmessage=s=>{this.handleAudioFrame(s.data)},t.connect(a),a.connect(this.audioCtx.destination),this.workletNode=a,this.usingWorklet=!0,gt.info(`[${this.ts()}] using AudioWorklet (pitch-processor)`);return}catch(a){gt.warn(`[${this.ts()}] AudioWorklet unavailable, falling back to ScriptProcessorNode`,a)}const r=4096;this.proc=this.audioCtx.createScriptProcessor(r,1,1),t.connect(this.proc),this.proc.connect(this.audioCtx.destination),this.proc.onaudioprocess=a=>{this.handleAudioFrame(a.inputBuffer.getChannelData(0))},this.usingWorklet=!1,gt.info(`[${this.ts()}] using ScriptProcessorNode fallback`)}stopAudioNodes(){try{this.workletNode&&(this.workletNode.port.close(),this.workletNode.disconnect(),this.workletNode=void 0)}catch{}try{this.proc&&(this.proc.onaudioprocess=null,this.proc.disconnect(),this.proc=void 0)}catch{}}async start(){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream||(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:!0})),this.audioCtx=new AudioContext;const t=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(t)}async startWithMediaStream(t){if(this.closed)throw new Error("client closed");if(this.started)return;this.started=!0,this.externalStream=!0,(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&this.connectWs(),this.mediaStream=t,this.audioCtx=new AudioContext;const r=this.audioCtx.createMediaStreamSource(this.mediaStream);await this.setupAudioNodes(r)}stop(){var t,r;if(gt.info(`[${this.ts()}] stop() called | closed=${this.closed} started=${this.started} sent=${this.chunksSent} responses=${this.responsesReceived}`),this.closed=!0,this.started=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.stopAudioNodes(),this.audioCtx&&this.audioCtx.state!=="closed"&&this.audioCtx.close().catch(()=>{}),!this.externalStream)try{(t=this.mediaStream)==null||t.getTracks().forEach(a=>a.stop())}catch{}try{(r=this.ws)==null||r.close()}catch{}this.ws=void 0,this.sendQueue=[]}}const Dh=ot.scoped("CrepeStreaming");class zh extends Io{constructor(t){super({...t,chunkMs:t.chunkMs??200}),this.crepeOpts=t}get tag(){return"CrepeStreamClient"}handleWsMessage(t){var a,s;const r=JSON.parse(t);(s=(a=this.crepeOpts).onMessage)==null||s.call(a,r)}onMaxReconnect(){var t,r;Dh.warn(`[${this.tag}] [${this.ts()}] triggering fallback`),this.stopAudioNodes();try{(r=(t=this.crepeOpts).onFallback)==null||r.call(t)}catch{}}}class _h extends Io{constructor(t){super({...t,chunkMs:t.chunkMs??100}),this.librosaOpts=t}get tag(){return"LibrosaStreamClient"}handleWsMessage(t){var a,s;const r=JSON.parse(t);(s=(a=this.librosaOpts).onMessage)==null||s.call(a,r)}get useWorklet(){return!1}}const Et={debug:(...e)=>{},warn:(...e)=>{typeof console<"u"&&console.warn("[KaraokePitch]",...e)}};function Fh(e){const t=new Float32Array(e);for(let r=0;r<e;r++)t[r]=.5*(1-Math.cos(2*Math.PI*r/(e-1)));return t}function Oh(e,t){const r=new Float32Array(e.length);for(let a=0;a<e.length;a++)r[a]=e[a]*t[a];return r}function Lo({isPlaying:e,gameMode:t,players:r,playersMicKey:a,micAlgorithms:s={},defaultPitchAlgorithm:i="pitchy",micRmsThresholds:o={},micOffsets:l={},micGains:c={},micPitchThresholds:d={},micSmoothingWindows:h={},micHysteresisFrames:f={},micUseHanning:p={},micMonitorEnabled:y={},micMonitorVolumes:m={},currentTimeRef:x,isPadMode:v,clockOffsetMsRef:g,currentPartyIdRef:S,rtc:b}){const[k,j]=u.useState({}),N=u.useRef({}),R=u.useRef({}),[w,M]=u.useState({}),I=u.useRef({}),A=u.useRef([]),T=u.useRef(null),O=u.useRef(null),[,E]=u.useState({}),[,V]=u.useState({}),[,ee]=u.useState({}),[z,q]=u.useState({}),[K,re]=u.useState(!0),[_,U]=u.useState(!1),$=u.useRef(r);$.current=r;const P=u.useRef(0),F=u.useRef(performance.now());return u.useEffect(()=>{A.current.forEach(G=>G()),A.current=[];const D={current:!1};function C(G,H,X=0){x.current!==P.current&&(P.current=x.current,F.current=performance.now());const oe=Math.min(.25,(performance.now()-F.current)/1e3),le=x.current+oe-X/1e3;j(Z=>{const Y=Z[G]||[];return{...Z,[G]:[...Y,{t:le,hz:H}]}}),N.current[G]=(N.current[G]||[]).concat({t:le,hz:H});const ne=N.current[G];ne.length>500&&(N.current[G]=ne.slice(-500))}function L(G,H,X,oe=.02,le=0,ne=.6,Z=0,Y=0,se=0,ae=!1){let ue=null,J=null,de=null;return(async()=>{try{ue=new AudioContext;let ce=ue.createMediaStreamSource(H);if(Z>0){const Pe=ue.createGain();Pe.gain.value=Z,ce.connect(Pe),ce=Pe}const ye=ue.createAnalyser();ye.fftSize=2048,ce.connect(ye);const ke=new Float32Array(ye.fftSize),ie=ae?Fh(ye.fftSize):null,he=[];let Le=0;if(X==="pitchy")try{const{PitchDetector:Pe}=await import("pitchy");de=Pe.forFloat32Array(ye.fftSize)}catch(Pe){Et.warn("pitchy import failed, falling back to autocorrelation",Pe)}const Oe=()=>{try{ye.getFloatTimeDomainData(ke)}catch{}const Pe=ie?Oh(ke,ie):ke;let Xe=0;for(let He=0;He<Pe.length;He++)Xe+=Pe[He]*Pe[He];Xe=Math.sqrt(Xe/Pe.length);let je=0;if(Xe>=oe)if(de)try{const[He,pt]=de.findPitch(Pe,ue.sampleRate);He>50&&He<3e3&&pt>ne&&(je=He)}catch{}else je=xo(Pe,ue.sampleRate,oe),(je<50||je>3e3)&&(je=0);if(je>0&&Y>1&&(he.push(je),he.length>Y&&he.shift(),je=he.reduce((He,pt)=>He+pt,0)/he.length),je>0)Le=0,C(G,je,le);else if(Le++,se>0&&Le<=se&&he.length>0){const He=he[he.length-1];He>0&&C(G,He,le)}J=requestAnimationFrame(Oe),I.current[G]=J};Oe()}catch(ve){Et.warn("startLocalPitch error",ve)}})(),()=>{J&&cancelAnimationFrame(J),ue&&ue.close().catch(()=>{})}}function B(G,H,X,oe=0){X==="crepe"&&O.current?(O.current.stop(),O.current=null):X==="librosa"&&T.current&&(T.current.stop(),T.current=null);const le=window.location,ne=le.protocol==="https:"?"wss:":"ws:",Z=X==="librosa"?`${ne}//${le.host}/api/librosa/ws/pyin`:`${ne}//${le.host}/api/ai/audio/pitch/ws/pitch_server`,Y=X==="librosa"?E:V;Y(de=>({...de,[G]:"connecting"}));const se=[],ae=de=>{if(de>0){for(se.push(x.current);se.length>200;)se.shift();X==="crepe"&&ee(me=>({...me,[G]:(me[G]||0)+1}))}},ue=()=>{Y(de=>({...de,[G]:"closed"})),se.length=0},J=de=>{if(typeof de.hz=="number"&&de.hz>0){const me=de.hz,ce=(se.length>0?se.shift():x.current)-oe/1e3;j(ye=>{const ke=ye[G]||[];return{...ye,[G]:[...ke,{t:ce,hz:me}]}})}else se.length>0&&se.shift()};if(X==="librosa"){const de=new _h({wsUrl:Z,onOpen:()=>Y(me=>({...me,[G]:"connected"})),onClose:ue,onError:me=>{Y(ve=>({...ve,[G]:"error"})),Et.warn("Librosa WS error",me)},onMessage:J,onSend:ae});return T.current=de,de.startWithMediaStream(H).catch(me=>{Et.warn("Librosa client start failed",me),Y(ve=>({...ve,[G]:"failed"}))}),()=>{de.stop(),T.current=null,Y(me=>({...me,[G]:""}))}}else{const de=new zh({wsUrl:Z,onOpen:()=>Y(me=>({...me,[G]:"connected"})),onClose:ue,onError:me=>{Y(ve=>({...ve,[G]:"error"})),Et.warn("Crepe WS error",me)},onMessage:J,onSend:ae,onFallback:()=>{Y(ve=>({...ve,[G]:"fallback-pitchy"})),O.current=null;const me=L(G,H,"pitchy",.02,oe);A.current.push(me)}});return O.current=de,de.startWithMediaStream(H).catch(me=>{Et.warn("Crepe client start failed",me),Y(ve=>({...ve,[G]:"failed"}))}),()=>{de.stop(),O.current=null,Y(me=>({...me,[G]:""}))}}}if(e){if(j({}),t!=="pad"){const G={};$.current.forEach(H=>{if(!H.micId)return;const X=s[H.id]||i,oe=H.micId&&o[H.micId]||.02,le=H.micId&&l[H.micId]||0,ne=H.micId&&c[H.micId]||0,Z=H.micId&&d[H.micId]||.6,Y=H.micId&&h[H.micId]||0,se=H.micId&&f[H.micId]||0,ae=H.micId&&p[H.micId]||!1,ue=H.micId&&y[H.micId]||!1,J=(H.micId?m[H.micId]:void 0)??100,de=new La;de.startRecording({deviceId:H.micId,onLevel:()=>{},gain:ne,monitorEnabled:ue,monitorVolume:J}).then(()=>{if(D.current){de.stopRecording().catch(()=>{});return}G[H.id]=de;const me=de.getStream();if(!me){Et.warn(`No stream from recorder for player ${H.id}`);return}if(X==="librosa"||X==="crepe"){const ve=B(H.id,me,X,le);A.current.push(ve)}else{const ve=L(H.id,me,X,oe,le,Z,ne,Y,se,ae);A.current.push(ve)}}).catch(me=>Et.warn(`recorder start failed for player ${H.id}`,me))}),R.current=G}}else{const G=R.current,H=Object.keys(G).map(Number);Promise.allSettled(H.map(async X=>{const oe=await G[X].stopRecording();return{pid:X,blob:oe}})).then(X=>{const oe={};for(const le of X)le.status==="fulfilled"&&le.value.blob&&(oe[le.value.pid]=le.value.blob);Object.keys(oe).length>0&&M(le=>({...le,...oe}))}),R.current={},Object.values(I.current).forEach(X=>X&&cancelAnimationFrame(X)),I.current={}}return()=>{D.current=!0,A.current.forEach(G=>G()),A.current=[],Object.values(R.current).forEach(G=>G.stopRecording().catch(()=>{})),R.current={},Object.values(I.current).forEach(G=>G&&cancelAnimationFrame(G)),I.current={}}},[e,t,a,s,i,o,l,c,d,h,f,p,y,m]),u.useEffect(()=>{if(!b)return;const D=300,C=async()=>{try{const B={...N.current};for(const G of Object.keys(B)){const H=Number(G),X=B[H]||[];if(!X||X.length===0)continue;N.current[H]=[];const oe=ko(X,120),le={playerId:H,points:oe,clientNowUtc:new Date().toISOString(),quantized:!0};S!=null&&S.current&&(le.EventId=S.current);try{b.isConnected()&&await b.publishTimelineUpdate(le)}catch(ne){Et.warn("failed to publish timeline update, will retry",ne),N.current[H]=(N.current[H]||[]).concat(X).slice(-1e3)}}}catch{}},L=window.setInterval(C,D);return()=>{L&&window.clearInterval(L)}},[b,S]),u.useEffect(()=>{if(!b)return;const D=C=>{try{const L=C;if(!L||typeof L.playerId>"u"||!Array.isArray(L.points))return;const B=Number(L.playerId),G=L.points.map(H=>({t:H.t,hz:H.hz}));if(!G.length)return;if(L.serverTimeUtc){const H=wo(L.serverTimeUtc,Date.now(),(g==null?void 0:g.current)||0);q(X=>({...X,[B]:H}))}j(H=>{const X=H[B]||[];return{...H,[B]:[...X,...G]}})}catch{}};return b.onTimelineUpdate(D),()=>b.offTimelineUpdate(D)},[b,g]),{livePitch:k,setLivePitch:j,recordings:w,recordersRef:R,unsentPitchRef:N,pitchCleanupsRef:A,remoteLatencyMs:z,showRemoteTimelines:K,setShowRemoteTimelines:re,compactTimelines:_,setCompactTimelines:U}}function Do(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function zo(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function _o(e,t,r){const{semitoneTolerance:a,preWindow:s,postExtra:i}=r,o=r.segMs??.25,l=typeof r.completionBonusFactor=="number"?r.completionBonusFactor:.15,c=typeof r.goldFullBonusFactor=="number"?r.goldFullBonusFactor:.3,d=typeof r.difficultyMult=="number"?r.difficultyMult:1,h=!!r.disableGoldNotes;let f=0,p=0,y=0;const m=[];let x=0,v=0,g=0;const S=new Map;e.forEach((M,I)=>{const A=M.startTime,T=M.startTime+M.duration,O=A-s,E=T+i,V=t.filter($=>$.t>=O&&$.t<=E&&$.hz>0);if(!V||V.length===0)return;const ee=Math.max(1,Math.ceil((M.duration||.25)/o)),z=Math.max(10,Math.round(100*(M.duration||1))),q=Math.max(1,Math.round(z/ee));let K=0;const re=[];for(let $=0;$<ee;$++){const P=A+$*(M.duration/ee),F=A+($+1)*(M.duration/ee),D=Math.min(.06,M.duration/ee*.2),C=P-D,L=F+D,B=t.filter(ne=>ne.t>=C&&ne.t<=L&&ne.hz>0);if(!B||B.length===0)continue;let G=0;B.forEach(ne=>{let Y=((12*Math.log2(ne.hz/440)+69)%12+12)%12;for(;Y-M.pitch>6;)Y-=12;for(;Y-M.pitch<-6;)Y+=12;const se=Math.abs(Y-M.pitch);G+=se});const H=G/B.length;let X=0;if(a<=0)X=H===0?1:0;else{const ne=a*2;X=Math.max(0,1-Math.min(H/ne,1))}if(X<=0)continue;const oe=!h&&M.isGold?2:1,le=Math.round(q*oe*X);le>0&&(f+=le,K+=le,re.push({segIndex:$,frac:X,add:le,segStart:C,segEnd:L,visualStart:P,visualEnd:F}))}const _=M.line??0;S.has(_)||S.set(_,{total:0,hit:0,comboBonus:0});const U=S.get(_);if(U.total++,K>0){x++,x>v&&(v=x),U.hit++;const $=zo(x),P=$>1?Math.round(K*($-1)):0;g+=P,U.comboBonus+=P;const F=Math.max(1,Math.ceil((M.duration||.25)/o)),C=re.length>=F,L=C?Math.round(Math.max(10,Math.round(100*(M.duration||1)))*l*(!h&&M.isGold?1.5:1)*d):0,B=C&&!h&&M.isGold?Math.round(Math.max(10,Math.round(100*(M.duration||1)))*c*d):0;p+=L,y+=B,m.push({noteKey:`${M.line??0}-${M.idx??0}`,segments:re,totalAdded:K,completed:C,completionBonus:L,goldFullBonus:B})}else x=0});const b=[];for(const[M,I]of S.entries()){const A=I.total>0?I.hit/I.total:0;b.push({verseIndex:M,hitFraction:A,label:Do(A),comboBonus:I.comboBonus})}const k={maxCombo:v,currentCombo:0,totalComboBonus:g},j=g+p+y,N=m.length,R=m.filter(M=>M.completed).length,w={hits:N,misses:e.length-N,good:N-R,perfect:R,maxCombo:v};return{classicScore:f,bonusScore:j,totalScore:f+j,total:f,perNote:m,combo:k,verseRatings:b,noteStats:w}}function Fo(e,t){let r=0;for(const a of e){const s=Math.max(10,Math.round(100*(a.duration||1))),i=!t&&a.isGold?2:1;r+=s*i}return r}function Oo(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function Bo(e,t,r){const a=Fo(t,r);if(a<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const s=Oo(e.classicScore,a),i=Math.round(e.bonusScore/a*1e4);return{...e,classicScore:s,bonusScore:i,totalScore:s+i,total:s}}const kn={maxCombo:0,currentCombo:0,totalComboBonus:0},Hs={hits:0,misses:0,good:0,perfect:0,maxCombo:0};function Go({livePitch:e,uploadedSong:t,isPlaying:r,difficulty:a,players:s,isPadMode:i}){const[o,l]=u.useState(0),[c,d]=u.useState(0),[h,f]=u.useState(0),[p,y]=u.useState([]),[m,x]=u.useState(kn),[v,g]=u.useState([]),[S,b]=u.useState([]),[k,j]=u.useState({}),[N,R]=u.useState({}),[w,M]=u.useState({}),[I,A]=u.useState({}),[T,O]=u.useState({});return u.useEffect(()=>{if(!t||!r)return;const E=Hn(t.notes.map(B=>B.noteLine),t.bpm??void 0),V=(t.gap??0)/1e3,ee=Qa(E,V),z=zr(a),q=[];let K=null,re=null,_=null,U=[];const $={},P={},F={},D={},C={},L=i?s[0]:s.find(B=>!!B.micId)||s[0];for(let B=0;B<s.length;B++){const G=s[B],H=(G==null?void 0:G.id)!=null?e[G.id]||[]:[];if(H.length===0){q.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||et[B%et.length],classicScore:0,bonusScore:0,totalScore:0}),$[G.id]=[],P[G.id]={...kn},F[G.id]=[],D[G.id]=0,C[G.id]={...Hs};continue}const X=Va(G.id),oe=!!(X!=null&&X.disableGoldNotes),le=_o(ee,H,{semitoneTolerance:z.semitoneTolerance,preWindow:z.preWindow,postExtra:z.postExtra,difficultyMult:z.difficultyMult,disableGoldNotes:oe}),ne=Bo(le,ee,oe);q.push({id:G.id,name:G.name||`Player ${G.id}`,color:G.color||et[B%et.length],classicScore:ne.classicScore,bonusScore:ne.bonusScore,totalScore:ne.totalScore}),$[G.id]=So(le.perNote,E,V),P[G.id]=le.combo??{...kn},F[G.id]=le.verseRatings??[],D[G.id]=ne.totalScore,C[G.id]=le.noteStats??{...Hs},G.id===(L==null?void 0:L.id)&&(K=ne,re=le.combo??null,_=le.verseRatings??null,U=$[G.id])}b(q),j($),R(P),M(F),A(D),O(C),K?(l(K.classicScore),d(K.bonusScore),f(K.totalScore),y(U),x(re??kn),g(_??[])):(l(0),d(0),f(0),y([]),x(kn),g([]))},[e,t,r,a,s,i]),{liveScore:o,liveBonusScore:c,liveTotalScore:h,liveSegmentScores:p,liveCombo:m,liveVerseRatings:v,perPlayerScores:S,perPlayerSegmentScores:k,perPlayerCombo:N,perPlayerVerseRatings:w,perPlayerTotalScores:I,perPlayerNoteStats:T}}const Bh=e=>!!e&&/youtu(\.be|be\.com)/i.test(e),Gh=({players:e,song:t,initialSong:r=null,difficulty:a="normal",gameMode:s="normal",height:i=480,showTimelines:o=!0,showLyrics:l=!0,singleTimeline:c=!1,requestMicPermission:d=!0,initiallyActivated:h=!1,showUploader:f=!1,parseSong:p,micAlgorithms:y,defaultPitchAlgorithm:m="pitchy",micRmsThresholds:x,micOffsets:v,micGains:g,micPitchThresholds:S,micSmoothingWindows:b,micHysteresisFrames:k,micUseHanning:j,micMonitorEnabled:N,micMonitorVolumes:R,searchYouTubeByArtistTitle:w,fetchTopSingings:M,onSaveResults:I,rtc:A,onSongChange:T,onPlayingChange:O,onTimeUpdate:E,onEnded:V,onContinue:ee,renderReport:z,t:q,className:K,style:re,id:_,accessMode:U,"data-testid":$})=>{var Fe;const{t:P}=Te(),F=q??P,[D,C]=u.useState(t??r??null),[L,B]=u.useState(!1),[G,H]=u.useState(0),[X,oe]=u.useState(h),[le,ne]=u.useState(!1),[Z,Y]=u.useState([]),[se,ae]=u.useState(""),[ue,J]=u.useState(null),[de,me]=u.useState(0),ve=s==="pad",[ce,ye]=u.useState([]),[ke,ie]=u.useState([]),[he,Le]=u.useState([]),[Oe,Pe]=u.useState([]),Xe=u.useRef(null),je=u.useRef(null),He=u.useRef(null),pt=u.useRef(!1),tt=u.useRef(0);u.useEffect(()=>{tt.current=G},[G]);const Ze=u.useRef(t);u.useEffect(()=>{t!==void 0&&t!==Ze.current&&(Ze.current=t,C(t),ne(!1),H(0),me(ge=>ge+1))},[t]);const It=u.useMemo(()=>JSON.stringify(e.map(ge=>({id:ge.id,micId:ge.micId}))),[e]),{livePitch:ft,setLivePitch:Lt,recordings:dt,remoteLatencyMs:fe}=Lo({isPlaying:L,gameMode:s,players:e,playersMicKey:It,micAlgorithms:y,defaultPitchAlgorithm:m,micRmsThresholds:x,micOffsets:v,micGains:g,micPitchThresholds:S,micSmoothingWindows:b,micHysteresisFrames:k,micUseHanning:j,micMonitorEnabled:N,micMonitorVolumes:R,currentTimeRef:tt,isPadMode:ve,rtc:A}),be=Go({livePitch:ft,uploadedSong:D,isPlaying:L,difficulty:a,players:e,isPadMode:ve}),_e=u.useRef(be);_e.current=be;const St=u.useMemo(()=>D?jo(D,s):null,[D,s]),pe=((Fe=e[0])==null?void 0:Fe.id)??1;u.useEffect(()=>{var Re;if(!ve||!L||!D){(Re=Xe.current)==null||Re.stop(),Xe.current=null,ye([]),ie([]),Le([]),Pe([]);return}const ge=new Eo({difficulty:a,noteLines:D.notes.map(Ae=>Ae.noteLine),bpm:D.bpm??void 0,gap:D.gap??0,onPitch:Ae=>{const We=tt.current;Lt(ze=>{const rt=ze[pe]||[];return{...ze,[pe]:[...rt,{t:We,hz:Ae}]}})},onHitFeedback:Ae=>Pe(We=>[...We.slice(-20),Ae]),onLaneActive:Ae=>Le(Ae)});return ye(ge.getLanes()),ie(ge.getEvents()),Le(new Array(ge.getLanes().length).fill(!1)),ge.start(()=>tt.current),Xe.current=ge,()=>{ge.stop(),Xe.current=null}},[ve,L,D,a,pe,Lt]);const xe=u.useCallback(ge=>{B(ge),O==null||O(ge)},[O]),qe=u.useCallback(ge=>{H(ge),E==null||E(ge)},[E]),Ie=u.useCallback(()=>{var Re;try{Gt()}catch{}const ge=()=>{oe(!0),pt.current=!0};!ve&&d&&((Re=navigator.mediaDevices)!=null&&Re.getUserMedia)?navigator.mediaDevices.getUserMedia({audio:!0}).then(Ae=>Ae.getTracks().forEach(We=>We.stop())).catch(()=>{}).finally(ge):ge()},[ve,d]);u.useEffect(()=>{if(!X||!pt.current)return;pt.current=!1;const ge=window.setInterval(()=>{je.current&&(window.clearInterval(ge),je.current.play())},100),Re=window.setTimeout(()=>window.clearInterval(ge),3e3);return()=>{window.clearInterval(ge),window.clearTimeout(Re)}},[X]);const Me=u.useCallback(()=>{ne(!0),V==null||V();const ge=(D==null?void 0:D.id)??0,Re=_e.current,Ae=[];for(const ze of e){const rt=Re.perPlayerTotalScores[ze.id]??0;if(rt<=0)continue;const Ye=Re.perPlayerNoteStats[ze.id];Ae.push({playerId:ze.id,songId:ge,score:rt,hits:(Ye==null?void 0:Ye.hits)??0,misses:(Ye==null?void 0:Ye.misses)??0,good:(Ye==null?void 0:Ye.good)??0,perfect:(Ye==null?void 0:Ye.perfect)??0,combo:(Ye==null?void 0:Ye.maxCombo)??0})}const We=()=>{M&&ge>0&&Promise.resolve(M(ge)).then(Y).catch(()=>{})};I&&Ae.length>0?Promise.resolve(I(Ae)).then(We).catch(We):We()},[e,D,I,M,V]);u.useEffect(()=>{var ge;s==="demo"&&L&&G>=12&&((ge=je.current)==null||ge.pause(),Me())},[s,L,G,Me]),u.useEffect(()=>{if(!D||de===0||!w||Bh(D.videoPath))return;if(D.youtubeId){const Re=`https://www.youtube.com/watch?v=${D.youtubeId}`;C(Ae=>Ae&&{...Ae,videoPath:Re});return}if(!D.artist||!D.title)return;let ge=!1;return ae(F("karaokeManager.ytSearching","Searching YouTube…")),J("searching"),Promise.resolve(w(D.artist,D.title)).then(Re=>{if(!ge)if(Re){const Ae=`https://www.youtube.com/watch?v=${Re}`;C(We=>We&&{...We,videoPath:Ae}),ae(""),J(null)}else ae(F("karaokeManager.ytNotFound","Not found on YouTube")),J("error"),window.setTimeout(()=>{ge||(ae(""),J(null))},4e3)}).catch(()=>{ge||(ae(F("karaokeManager.ytSearchError","Search error")),J("error"))}),()=>{ge=!0}},[de,D,w,F]);const Ne=u.useCallback(()=>{var ge,Re;ne(!1),Lt({}),(ge=je.current)==null||ge.seekTo(0),(Re=je.current)==null||Re.play()},[Lt]),Be=u.useCallback(()=>{ne(!1),ee==null||ee()},[ee]),Ge=u.useCallback(ge=>{C(ge),ne(!1),H(0),me(Re=>Re+1),T==null||T(ge)},[T]),Je=u.useMemo(()=>{if(!c)return e;const ge=e.find(Re=>!!Re.micId)||e[0];return ge?[ge]:[]},[e,c]),Ee=((D==null?void 0:D.gap)??0)/1e3;return U==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-manager${K?` ${K}`:""}`,style:{position:"relative",textAlign:"center",minHeight:i,...re},id:_,"data-testid":$,children:[se&&n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,margin:"10px auto",padding:"8px 16px",maxWidth:420,borderRadius:8,fontSize:14,fontWeight:500,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:[ue==="error"?n.jsx(W.NtdClose,{size:16}):n.jsx(W.NtdSearch,{size:16}),se]}),!D&&f&&n.jsx(Ro,{onSongUpload:Ge,parseSong:p,t:F}),D&&!X&&n.jsxs("button",{type:"button",className:"nice-karaoke-manager__activate",onClick:Ie,style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,border:"none",cursor:"pointer",background:"var(--nice-overlay-80, rgba(0,0,0,0.82))",color:"#fff"},children:[n.jsx("div",{style:{fontSize:56,lineHeight:0},children:ve?n.jsx(W.NtdGamepad,{size:56}):n.jsx(W.NtdMicrophone,{size:56})}),n.jsx("h2",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff"},children:F("karaokeManager.activateAudio","Tap to start")}),n.jsx("p",{style:{margin:0,maxWidth:360,fontSize:14,color:"var(--nice-text-muted, #94a3b8)"},children:ve?F("karaokeManager.padHint","Hit the notes with your keys or pad!"):F("karaokeManager.micHint","Your browser needs a tap to unlock the microphone and audio.")})]}),D&&n.jsxs("div",{ref:He,style:{position:"relative",width:"100%",maxWidth:1200,margin:"0 auto"},children:[n.jsx("div",{style:{width:"100%",position:"relative",zIndex:10},children:n.jsx(Za,{tracks:St?[St]:[],autoPlay:!1,uiMode:"nobuttons",height:i,externalRef:je,onPlayingChange:xe,onTimeUpdate:qe,onEnded:Me})}),o&&X&&n.jsx("div",{style:{position:"absolute",inset:0,zIndex:20,pointerEvents:"none"},children:Je.map((ge,Re)=>{const Ae=ft[ge.id]||[],We=Ee?Ae.map(ze=>({t:ze.t-Ee,hz:ze.hz})):Ae;return n.jsx(Ka,{song:D,currentTime:G,playerRef:He,userPitch:We,segmentScores:be.perPlayerSegmentScores[ge.id],combo:be.perPlayerCombo[ge.id],verseRatings:be.perPlayerVerseRatings[ge.id],config:{playerName:ge.name,score:be.perPlayerTotalScores[ge.id]??0,playerBgColor:ge.color||et[Re%et.length],difficultyLevel:a,isPlaying:L,playerCount:Je.length,latencyMs:fe[ge.id]??null,top:30+Re*160}},ge.id)})}),ve&&ce.length>0&&n.jsx(No,{lanes:ce,events:ke,currentTime:G,activeLanes:he,difficulty:a,feedbackQueue:Oe,isPlaying:L}),l&&X&&n.jsx("div",{style:{position:"absolute",bottom:20,left:0,right:0,zIndex:25,pointerEvents:"none"},children:n.jsx(_a,{song:D,currentTime:G})})]}),le&&Object.keys(dt).length>0&&n.jsx(Wh,{recordings:dt,players:e,t:F}),le&&n.jsx(Xa,{uploadedSong:D,playerScores:be.perPlayerScores,topSingings:Z,onRestart:Ne,onContinue:Be,t:F,renderReport:z})]})},Wh=({recordings:e,players:t,t:r})=>{const a=u.useMemo(()=>{const s={};for(const[i,o]of Object.entries(e))o&&(s[Number(i)]=URL.createObjectURL(o));return s},[e]);return u.useEffect(()=>()=>{for(const s of Object.values(a))URL.revokeObjectURL(s)},[a]),n.jsxs("div",{style:{margin:"24px auto",maxWidth:640,background:"var(--nice-bg-tertiary)",borderRadius:12,padding:16,textAlign:"left"},children:[n.jsxs("h4",{style:{marginTop:0,color:"var(--nice-text-primary, #fff)"},children:[n.jsx(W.NtdMicrophone,{size:16})," ",r("karaokeManager.playerRecordings","Player recordings")]}),n.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,color:"var(--nice-text-primary, #fff)"},children:t.map(s=>n.jsxs("li",{style:{marginBottom:12,display:"flex",alignItems:"center",gap:10},children:[n.jsx("b",{children:s.name||`Player ${s.id}`}),a[s.id]?n.jsxs(n.Fragment,{children:[n.jsx("audio",{controls:!0,src:a[s.id],style:{flex:1,maxWidth:300}}),n.jsxs("a",{href:a[s.id],download:`${s.name||`player-${s.id}`}-recording.webm`,style:{color:"var(--nice-accent-light, #4fc3f7)",whiteSpace:"nowrap"},children:[n.jsx(W.NtdDownload,{size:13})," ",r("karaokeManager.download","Download")]})]}):n.jsx("span",{style:{opacity:.6},children:r("karaokeManager.noRecording","No recording")})]},s.id))})]})},Wo=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function an(e){return 12*Math.log2(e/440)+69}function er(e){const t=Wo[Math.round(e)%12],r=Math.floor(Math.round(e)/12)-1;return`${t}${r}`}function Zr(e,t){if(e.length===0)return 0;const r=t/100*(e.length-1),a=Math.floor(r),s=Math.ceil(r);return a===s?e[a]:e[a]+(e[s]-e[a])*(r-a)}function Uo(e){const{playerName:t,playerColor:r,songTitle:a,songArtist:s,songBpm:i,difficulty:o,pitchPoints:l,notes:c,verseRatings:d,combo:h,classicScore:f,bonusScore:p,totalScore:y,micSettings:m}=e,x=l.filter(ie=>ie.hz>0),v=x.map(ie=>an(ie.hz)),g=[],S=[],b=[],k=[...c].sort((ie,he)=>ie.startTime-he.startTime);function j(ie){let he=0,Le=k.length-1;for(;he<=Le;){const Oe=he+Le>>>1,Pe=k[Oe];if(ie<Pe.startTime)Le=Oe-1;else if(ie>Pe.startTime+Pe.duration)he=Oe+1;else return Pe.pitch}return 0}for(const ie of l){const he=ie.hz>0?an(ie.hz):0,Le=j(ie.t);if(S.push({t:ie.t,sung:he,expected:Le}),he>0&&Le>0){const Oe=(he-Le)*100;g.push(Oe)}}let N=0;for(const ie of k){const he=ie.startTime-.3,Le=ie.startTime+ie.duration;for(;N<x.length&&x[N].t<he;)N++;N<x.length&&x[N].t<=Le&&b.push((x[N].t-ie.startTime)*1e3)}const R=g.map(Math.abs),w=[...R].sort((ie,he)=>ie-he),M=R.length>0?R.reduce((ie,he)=>ie+he,0)/R.length:0,I=Zr(w,50),A=R.length>1?Math.sqrt(R.reduce((ie,he)=>ie+(he-M)**2,0)/(R.length-1)):0,T=R.filter(ie=>ie<=50).length,O=R.filter(ie=>ie<=15).length,E=R.length>0?T/R.length*100:0,V=R.length>0?O/R.length*100:0,ee=["< −100","−100 to −50","−50 to −25","−25 to −15","−15 to 0","0 to +15","+15 to +25","+25 to +50","+50 to +100","> +100"],z=new Array(10).fill(0);for(const ie of g){const he=ie<-100?0:ie<-50?1:ie<-25?2:ie<-15?3:ie<0?4:ie<15?5:ie<25?6:ie<50?7:ie<100?8:9;z[he]++}const q=ee.map((ie,he)=>({centRange:ie,count:z[he],pct:g.length>0?z[he]/g.length*100:0})),K=x.map(ie=>ie.hz).sort((ie,he)=>ie-he),re=K.length>0?K[0]:0,_=K.length>0?K[K.length-1]:0,U=re>0?an(re):0,$=_>0?an(_):0,P=$-U,F=[...v].sort((ie,he)=>ie-he),D=Zr(F,10),C=Zr(F,90),L=new Array(12).fill(0);for(const ie of v){const he=Math.round(ie)%12;he>=0&&he<12&&L[he]++}const B=L.reduce((ie,he)=>ie+he,0),G=Wo.map((ie,he)=>({note:ie,count:L[he],pct:B>0?L[he]/B*100:0})),H=Uh(x),X=b.length>0?b.reduce((ie,he)=>ie+he,0)/b.length:0,oe=b.length>1?Math.sqrt(b.reduce((ie,he)=>ie+(he-X)**2,0)/(b.length-1)):0,le=oe>0?Math.max(0,Math.min(100,100-oe/2)):100;let ne=0,Z=0;for(let ie=1;ie<v.length;ie++){const he=Math.abs(v[ie]-v[ie-1]);ne+=he,Z++}const Y=Z>0?ne/Z*100/12:0,se=l.filter(ie=>ie.hz<=0).length,ae=l.length>0?(1-se/l.length)*100:0,ue=new Map;for(const ie of c){const he=ie.line??0;ue.has(he)||ue.set(he,[]),ue.get(he).push(ie)}const J=new Map;for(const ie of x){const he=j(ie.t);if(he<=0)continue;let Le=0,Oe=k.length-1,Pe=-1;for(;Le<=Oe;){const je=Le+Oe>>>1,He=k[je];if(ie.t<He.startTime)Oe=je-1;else if(ie.t>He.startTime+He.duration)Le=je+1;else{Pe=He.line??0;break}}if(Pe<0)continue;const Xe=Math.abs((an(ie.hz)-he)*100);J.has(Pe)||J.set(Pe,[]),J.get(Pe).push(Xe)}const de=d.map(ie=>{const he=ue.get(ie.verseIndex)??[],Le=J.get(ie.verseIndex)??[],Oe=Le.length>0?Le.reduce((Pe,Xe)=>Pe+Xe,0)/Le.length:0;return{verseIndex:ie.verseIndex,label:ie.label,hitFraction:ie.hitFraction,avgCentDeviation:Math.round(Oe*10)/10,noteCount:he.length,notesHit:Math.round(ie.hitFraction*he.length),comboBonus:ie.comboBonus}}),me=2,ve=.5,ce=l.length>0?l[l.length-1].t:0,ye=[],ke=S.filter(ie=>ie.sung>0&&ie.expected>0);if(ke.length>0){let ie=0,he=0,Le=0;for(let Oe=0;Oe<=ce;Oe+=ve){const Pe=Oe-me/2,Xe=Oe+me/2;for(;he<ke.length&&ke[he].t<Xe;)Math.abs(ke[he].sung-ke[he].expected)<=.5&&Le++,he++;for(;ie<he&&ke[ie].t<Pe;)Math.abs(ke[ie].sung-ke[ie].expected)<=.5&&Le--,ie++;const je=he-ie;ye.push({t:Oe,accuracy:je>0?Le/je*100:0})}}else for(let ie=0;ie<=ce;ie+=ve)ye.push({t:ie,accuracy:0});return{playerName:t,playerColor:r,songTitle:a,songArtist:s,songBpm:i,difficulty:o,timestamp:new Date().toISOString(),classicScore:f,bonusScore:p,totalScore:y,maxCombo:(h==null?void 0:h.maxCombo)??0,totalComboBonus:(h==null?void 0:h.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(M*10)/10,medianCentDeviation:Math.round(I*10)/10,stdDevCents:Math.round(A*10)/10,intonationAccuracyPct:Math.round(E*10)/10,perfectHitPct:Math.round(V*10)/10,pitchDeviationHistogram:q,lowestHz:Math.round(re*10)/10,highestHz:Math.round(_*10)/10,lowestNote:U>0?er(U):"—",highestNote:$>0?er($):"—",rangeInSemitones:Math.round(P*10)/10,tessituraLow:D>0?er(D):"—",tessituraHigh:C>0?er(C):"—",pitchClassDistribution:G,vibrato:H,avgOnsetDeviationMs:Math.round(X*10)/10,rhythmStabilityPct:Math.round(le*10)/10,jitterPct:Math.round(Y*100)/100,shimmerProxy:Math.round(ae*10)/10,verseMetrics:de,micSettings:m,pitchOverTime:S,accuracyOverTime:ye}}function Uh(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(y=>an(y.hz)),r=e.map(y=>y.t),a=.5,s=[],i=[];let o=0,l=0,c=0;for(let y=0;y<e.length;y++){for(l+=t[y],c++;o<y&&r[y]-r[o]>=a;)l-=t[o],c--,o++;if(c<6||(y-o)%10!==0)continue;const m=l/c;let x=0,v=t[o]-m,g=Math.abs(v);for(let k=o+1;k<=y;k++){const j=t[k]-m;j*v<0&&x++,v=j;const N=Math.abs(j);N>g&&(g=N)}const S=r[y]-r[o];if(S<=0)continue;const b=x/2/S;b>=3&&b<=12&&(s.push(b),i.push(g*100))}if(s.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=s.reduce((y,m)=>y+m,0)/s.length,h=i.reduce((y,m)=>y+m,0)/i.length,f=Math.sqrt(s.reduce((y,m)=>y+(m-d)**2,0)/s.length),p=Math.max(0,Math.min(100,100-f*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(h*10)/10,regularityPct:Math.round(p)}}const Q={overlay:{position:"fixed",inset:0,background:"var(--nice-overlay-90, rgba(0,0,0,0.92))",display:"flex",alignItems:"flex-start",justifyContent:"center",zIndex:250,color:"var(--nice-text, #e2e8f0)",overflowY:"auto",padding:"24px 12px"},container:{background:"var(--nice-bg, #0f172a)",borderRadius:16,padding:32,width:"min(960px, 95vw)",boxShadow:"0 16px 48px var(--nice-overlay-60, rgba(0,0,0,0.6))",fontFamily:"'Segoe UI', system-ui, -apple-system, sans-serif"},header:{textAlign:"center",marginBottom:24,borderBottom:"2px solid var(--nice-border, #334155)",paddingBottom:20},title:{fontSize:28,fontWeight:800,color:"var(--nice-text, #f1f5f9)",margin:"0 0 4px"},subtitle:{fontSize:14,color:"var(--nice-text-muted, #64748b)",margin:0},sectionTitle:{fontSize:18,fontWeight:700,color:"var(--nice-accent, #38bdf8)",margin:"28px 0 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",paddingBottom:6,display:"flex",alignItems:"center",gap:8},table:{width:"100%",borderCollapse:"collapse",fontSize:13,margin:"8px 0"},th:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"left",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},thRight:{background:"var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #94a3b8)",padding:"8px 12px",textAlign:"right",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.5,borderBottom:"2px solid var(--nice-border, #334155)"},td:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-secondary, #cbd5e1)"},tdRight:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",textAlign:"right",color:"var(--nice-text, #e2e8f0)",fontWeight:500},tdBold:{padding:"6px 12px",borderBottom:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text, #f1f5f9)",fontWeight:700},kpiGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:12,margin:"12px 0"},kpiCard:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:"14px 16px",textAlign:"center",border:"1px solid var(--nice-border, #334155)"},kpiValue:{fontSize:26,fontWeight:800,color:"var(--nice-warning, #fbbf24)"},kpiLabel:{fontSize:11,color:"var(--nice-text-muted, #64748b)",marginTop:2,textTransform:"uppercase",letterSpacing:.8},kpiUnit:{fontSize:13,fontWeight:400,color:"var(--nice-text-muted, #94a3b8)",marginLeft:2},chartWrap:{background:"var(--nice-bg-secondary, #1e293b)",borderRadius:10,padding:16,margin:"12px 0",border:"1px solid var(--nice-border, #334155)"},chartTitle:{fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:8,textAlign:"center"},badge:e=>({display:"inline-block",padding:"2px 10px",borderRadius:20,background:e,color:"#fff",fontSize:12,fontWeight:700}),btnPrimary:{background:"var(--nice-info, #3b82f6)",color:"#fff",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:700,cursor:"pointer"},btnSecondary:{background:"var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)",border:"none",borderRadius:8,padding:"10px 22px",fontSize:14,fontWeight:600,cursor:"pointer"},row:{display:"flex",gap:16,flexWrap:"wrap"},half:{flex:"1 1 45%",minWidth:280},footer:{textAlign:"center",marginTop:24,paddingTop:16,borderTop:"1px solid var(--nice-bg-secondary, #1e293b)",color:"var(--nice-text-muted, #475569)",fontSize:11}};function yt(e){return e>=90?"#22c55e":e>=70?"#84cc16":e>=50?"#eab308":e>=30?"#f97316":"#ef4444"}function Ks(e){switch(e){case"Perfect":return"#22c55e";case"Great":return"#84cc16";case"Good":return"#eab308";case"OK":return"#f97316";default:return"#ef4444"}}const qh=({reports:e,noteCount:t,uploadedSong:r=null,playerScores:a,livePitch:s,liveVerseRatings:i,liveCombo:o,difficulty:l="normal",micSettings:c,onClose:d,t:h,className:f,style:p,id:y,accessMode:m,"data-testid":x})=>{const{t:v}=Te(),g=h??v,S=u.useRef(null),b=u.useMemo(()=>{if(e||!r)return[];const _=Hn(r.notes.map($=>$.noteLine),r.bpm??void 0),U=(r.gap??0)/1e3;return Qa(_,U)},[e,r]),k=u.useMemo(()=>e||(!r||!a||!o?[]:a.map(_=>{const U=(s==null?void 0:s[_.id])||[];return Uo({playerName:_.name,playerColor:_.color,songTitle:r.title,songArtist:r.artist,songBpm:r.bpm??0,difficulty:l,pitchPoints:U,notes:b,verseRatings:i??[],combo:o,classicScore:_.classicScore,bonusScore:_.bonusScore,totalScore:_.totalScore,micSettings:(c==null?void 0:c[_.id])??null})})),[e,r,a,s,i,o,l,b,c]),j=u.useCallback(()=>{var F,D;if(!S.current)return;const _=`<!DOCTYPE html>
48
48
  <html lang="en"><head><meta charset="utf-8">
49
- <title>Vocal Performance Report — ${((I=S[0])==null?void 0:I.songTitle)??"Karaoke"}</title>
49
+ <title>Vocal Performance Report — ${((F=k[0])==null?void 0:F.songTitle)??"Karaoke"}</title>
50
50
  <style>
51
51
  body{margin:0;padding:24px;background:var(--nice-bg, #0f172a);color:var(--nice-text, #e2e8f0);font-family:'Segoe UI',system-ui,sans-serif}
52
52
  table{border-collapse:collapse;width:100%}th,td{padding:6px 10px;border-bottom:1px solid var(--nice-bg-secondary, #1e293b);text-align:left}
@@ -55,19 +55,19 @@ th{background:var(--nice-bg-secondary, #1e293b);color:var(--nice-text-muted, #94
55
55
  .val{font-size:24px;font-weight:800;color:var(--nice-warning, #fbbf24)}.lbl{font-size:11px;color:var(--nice-text-muted, #64748b);text-transform:uppercase}
56
56
  @media print{body{background:#fff;color:#000}th{background:var(--nice-bg-secondary, #f0f0f0);color:var(--nice-text-muted, #333)}td{color:var(--nice-text-muted, #333);border-color:var(--nice-border, #ddd)}}
57
57
  </style></head><body>
58
- ${k.current.innerHTML}
59
- </body></html>`,W=new Blob([D],{type:"text/html"}),j=URL.createObjectURL(W),F=document.createElement("a");F.href=j,F.download=`vocal-report-${(((P=S[0])==null?void 0:P.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,F.click(),URL.revokeObjectURL(j)},[S]),R=d.useCallback(()=>window.print(),[]),N=d.useCallback(()=>{var I;const D=JSON.stringify(S,null,2),W=new Blob([D],{type:"application/json"}),j=URL.createObjectURL(W),F=document.createElement("a");F.href=j,F.download=`vocal-data-${(((I=S[0])==null?void 0:I.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,F.click(),URL.revokeObjectURL(j)},[S]);if(m==="hidden")return null;if(S.length===0)return r.jsx("div",{className:p,style:{...Q.overlay,...f},id:y,"data-testid":v,onClick:D=>D.target===D.currentTarget&&(u==null?void 0:u()),children:r.jsxs("div",{style:{...Q.container,textAlign:"center"},children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h2",{style:Q.title,children:[r.jsx(se.NtdBarChart,{size:24})," ",g("karaoke.report.title","Vocal Performance Report")]}),r.jsx("p",{style:Q.subtitle,children:g("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),u&&r.jsxs("button",{style:Q.btnSecondary,onClick:u,children:[r.jsx(se.NtdClose,{size:16})," ",g("common.close","Close")]})]})});const C=S[0],w=t??b.length,O=Ir(l),$=C.intonationAccuracyPct*.3+C.perfectHitPct*.2+C.rhythmStabilityPct*.15+C.shimmerProxy*.1+Math.min(100,C.maxCombo/Math.max(w,1)*100)*.1+Math.min(100,C.totalScore/1e4*100)*.15,E=$>=95?"A+":$>=90?"A":$>=85?"A−":$>=80?"B+":$>=75?"B":$>=70?"B−":$>=65?"C+":$>=60?"C":$>=55?"C−":$>=50?"D+":$>=45?"D":$>=40?"D−":"F",_={"A+":g("vocalReport.gradeAPlus","Outstanding — professional-level control."),A:g("vocalReport.gradeA","Excellent intonation and timing."),"A−":g("vocalReport.gradeAMinus","Very strong performance."),"B+":g("vocalReport.gradeBPlus","Great, with minor pitch slips."),B:g("vocalReport.gradeB","Solid and consistent."),"B−":g("vocalReport.gradeBMinus","Good, room to tighten timing."),"C+":g("vocalReport.gradeCPlus","Decent — practice pitch accuracy."),C:g("vocalReport.gradeC","Average; work on intonation."),"C−":g("vocalReport.gradeCMinus","Passable; needs steadier pitch."),"D+":g("vocalReport.gradeDPlus","Below average — keep practising."),D:g("vocalReport.gradeD","Weak intonation throughout."),"D−":g("vocalReport.gradeDMinus","Struggling with pitch and timing."),F:g("vocalReport.gradeF","Off-pitch for most notes.")};let L=0;const U=[{metric:g("vocalReport.radarIntonation","Intonation"),value:C.intonationAccuracyPct,max:100},{metric:g("vocalReport.radarPerfectHits","Perfect hits"),value:C.perfectHitPct,max:100},{metric:g("vocalReport.radarRhythm","Rhythm"),value:C.rhythmStabilityPct,max:100},{metric:g("vocalReport.radarVocalRange","Range"),value:Math.min(100,C.rangeInSemitones/24*100),max:100},{metric:g("vocalReport.radarStability","Stability"),value:C.shimmerProxy,max:100},{metric:g("vocalReport.radarCombo","Combo"),value:Math.min(100,C.maxCombo/Math.max(w,1)*100),max:100}],Z=[{name:g("vocalReport.perfLabel","Perfect"),value:C.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:g("vocalReport.goodLabel","Good"),value:C.intonationAccuracyPct-C.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:g("vocalReport.offPitch","Off-pitch"),value:100-C.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(D=>D.value>0),A=C.pitchClassDistribution.filter(D=>D.count>0).sort((D,W)=>W.pct-D.pct),q=C.verseMetrics.map(D=>({verse:`V${D.verseIndex+1}`,accuracy:Math.round(D.hitFraction*100),label:D.label})),H=(()=>{const D=C.pitchOverTime;if(D.length<=500)return D;const W=Math.ceil(D.length/500);return D.filter((j,F)=>F%W===0)})(),re=g("vocalReport.cents","cents");return r.jsxs("div",{className:p,style:{...Q.overlay,...f},id:y,"data-testid":v,onClick:D=>D.target===D.currentTarget&&(u==null?void 0:u()),children:[r.jsx("style",{children:`
58
+ ${S.current.innerHTML}
59
+ </body></html>`,U=new Blob([_],{type:"text/html"}),$=URL.createObjectURL(U),P=document.createElement("a");P.href=$,P.download=`vocal-report-${(((D=k[0])==null?void 0:D.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.html`,P.click(),URL.revokeObjectURL($)},[k]),N=u.useCallback(()=>window.print(),[]),R=u.useCallback(()=>{var F;const _=JSON.stringify(k,null,2),U=new Blob([_],{type:"application/json"}),$=URL.createObjectURL(U),P=document.createElement("a");P.href=$,P.download=`vocal-data-${(((F=k[0])==null?void 0:F.songTitle)??"karaoke").replace(/[^a-z0-9]/gi,"_")}.json`,P.click(),URL.revokeObjectURL($)},[k]);if(m==="hidden")return null;if(k.length===0)return n.jsx("div",{className:f,style:{...Q.overlay,...p},id:y,"data-testid":x,onClick:_=>_.target===_.currentTarget&&(d==null?void 0:d()),children:n.jsxs("div",{style:{...Q.container,textAlign:"center"},children:[n.jsxs("div",{style:Q.header,children:[n.jsxs("h2",{style:Q.title,children:[n.jsx(W.NtdBarChart,{size:24})," ",g("karaoke.report.title","Vocal Performance Report")]}),n.jsx("p",{style:Q.subtitle,children:g("karaoke.report.empty","No performance data yet — sing a song to see the report.")})]}),d&&n.jsxs("button",{style:Q.btnSecondary,onClick:d,children:[n.jsx(W.NtdClose,{size:16})," ",g("common.close","Close")]})]})});const w=k[0],M=t??b.length,I=zr(l),A=w.intonationAccuracyPct*.3+w.perfectHitPct*.2+w.rhythmStabilityPct*.15+w.shimmerProxy*.1+Math.min(100,w.maxCombo/Math.max(M,1)*100)*.1+Math.min(100,w.totalScore/1e4*100)*.15,T=A>=95?"A+":A>=90?"A":A>=85?"A−":A>=80?"B+":A>=75?"B":A>=70?"B−":A>=65?"C+":A>=60?"C":A>=55?"C−":A>=50?"D+":A>=45?"D":A>=40?"D−":"F",O={"A+":g("vocalReport.gradeAPlus","Outstanding — professional-level control."),A:g("vocalReport.gradeA","Excellent intonation and timing."),"A−":g("vocalReport.gradeAMinus","Very strong performance."),"B+":g("vocalReport.gradeBPlus","Great, with minor pitch slips."),B:g("vocalReport.gradeB","Solid and consistent."),"B−":g("vocalReport.gradeBMinus","Good, room to tighten timing."),"C+":g("vocalReport.gradeCPlus","Decent — practice pitch accuracy."),C:g("vocalReport.gradeC","Average; work on intonation."),"C−":g("vocalReport.gradeCMinus","Passable; needs steadier pitch."),"D+":g("vocalReport.gradeDPlus","Below average — keep practising."),D:g("vocalReport.gradeD","Weak intonation throughout."),"D−":g("vocalReport.gradeDMinus","Struggling with pitch and timing."),F:g("vocalReport.gradeF","Off-pitch for most notes.")};let E=0;const V=[{metric:g("vocalReport.radarIntonation","Intonation"),value:w.intonationAccuracyPct,max:100},{metric:g("vocalReport.radarPerfectHits","Perfect hits"),value:w.perfectHitPct,max:100},{metric:g("vocalReport.radarRhythm","Rhythm"),value:w.rhythmStabilityPct,max:100},{metric:g("vocalReport.radarVocalRange","Range"),value:Math.min(100,w.rangeInSemitones/24*100),max:100},{metric:g("vocalReport.radarStability","Stability"),value:w.shimmerProxy,max:100},{metric:g("vocalReport.radarCombo","Combo"),value:Math.min(100,w.maxCombo/Math.max(M,1)*100),max:100}],ee=[{name:g("vocalReport.perfLabel","Perfect"),value:w.perfectHitPct,fill:"var(--nice-success, #22c55e)"},{name:g("vocalReport.goodLabel","Good"),value:w.intonationAccuracyPct-w.perfectHitPct,fill:"var(--nice-success, #84cc16)"},{name:g("vocalReport.offPitch","Off-pitch"),value:100-w.intonationAccuracyPct,fill:"var(--nice-danger, #ef4444)"}].filter(_=>_.value>0),z=w.pitchClassDistribution.filter(_=>_.count>0).sort((_,U)=>U.pct-_.pct),q=w.verseMetrics.map(_=>({verse:`V${_.verseIndex+1}`,accuracy:Math.round(_.hitFraction*100),label:_.label})),K=(()=>{const _=w.pitchOverTime;if(_.length<=500)return _;const U=Math.ceil(_.length/500);return _.filter(($,P)=>P%U===0)})(),re=g("vocalReport.cents","cents");return n.jsxs("div",{className:f,style:{...Q.overlay,...p},id:y,"data-testid":x,onClick:_=>_.target===_.currentTarget&&(d==null?void 0:d()),children:[n.jsx("style",{children:`
60
60
  @media print {
61
61
  body { background: #fff !important; color: #000 !important; }
62
62
  * { color-adjust: exact !important; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
63
63
  }
64
- `}),r.jsxs("div",{ref:k,style:Q.container,children:[r.jsxs("div",{style:Q.header,children:[r.jsxs("h1",{style:{...Q.title,display:"inline-flex",alignItems:"center",gap:8},children:[r.jsx(se.NtdBarChart,{size:26})," ",g("vocalReport.title","Vocal Performance Report")]}),r.jsxs("p",{style:Q.subtitle,children:[C.songArtist," — ",C.songTitle,"  | ",g("vocalReport.difficulty","Difficulty"),": ",r.jsx("strong",{children:C.difficulty})," "," | ",new Date(C.timestamp).toLocaleString()]}),r.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[r.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${gt($)}44, ${gt($)})`,border:`3px solid ${gt($)}`,boxShadow:`0 0 20px ${gt($)}44`},children:r.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:E})}),r.jsxs("div",{style:{textAlign:"left"},children:[r.jsxs("div",{style:{fontSize:14,fontWeight:700,color:gt($)},children:[g("vocalReport.overallGrade","Overall grade"),": ",$.toFixed(1),"%"]}),r.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:_[E]??""})]})]})]}),r.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[r.jsxs("button",{style:Q.btnPrimary,onClick:M,children:[r.jsx(se.NtdDownload,{size:14})," ",g("vocalReport.downloadHtml","Download HTML")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:R,children:[r.jsx(se.NtdPrint,{size:14})," ",g("vocalReport.printPdf","Print / PDF")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:N,children:[r.jsx(se.NtdCode,{size:14})," ",g("vocalReport.exportJson","Export JSON")]}),r.jsxs("button",{style:Q.btnSecondary,onClick:u,children:[r.jsx(se.NtdClose,{size:14})," ",g("vocalReport.close","Close")]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.scoreOverview","Score overview")]}),r.jsxs("div",{style:Q.kpiGrid,children:[r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:C.totalScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.totalScore","Total score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:C.classicScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.classicScore","Classic score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsx("div",{style:Q.kpiValue,children:C.bonusScore.toLocaleString()}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.bonusScore","Bonus score")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:Q.kpiValue,children:[C.maxCombo,"×"]}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.maxCombo","Max combo")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:gt(C.intonationAccuracyPct)},children:[C.intonationAccuracyPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.intonationAccuracy","Intonation accuracy")})]}),r.jsxs("div",{style:Q.kpiCard,children:[r.jsxs("div",{style:{...Q.kpiValue,color:gt(C.perfectHitPct)},children:[C.perfectHitPct,"%"]}),r.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.perfectHits","Perfect hits")})]})]}),S.length>1&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.playerComparison","Player comparison")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:"#"}),r.jsx("th",{style:Q.th,children:g("vocalReport.player","Player")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.classic","Classic")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.bonus","Bonus")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.total","Total")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.intonation","Intonation")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.perfect","Perfect")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.range","Range")})]})}),r.jsx("tbody",{children:S.map((D,W)=>r.jsxs("tr",{children:[r.jsx("td",{style:Q.td,children:W+1}),r.jsx("td",{style:{...Q.tdBold,color:D.playerColor},children:D.playerName}),r.jsx("td",{style:Q.tdRight,children:D.classicScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:D.bonusScore.toLocaleString()}),r.jsx("td",{style:{...Q.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:D.totalScore.toLocaleString()}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(D.intonationAccuracyPct)),children:[D.intonationAccuracyPct,"%"]})}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(D.perfectHitPct)),children:[D.perfectHitPct,"%"]})}),r.jsxs("td",{style:Q.tdRight,children:[D.lowestNote,"–",D.highestNote]})]},W))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.pitchAccuracy","Pitch accuracy")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:g("vocalReport.metric","Metric")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.meanAbsDev","Mean abs. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[C.avgCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),r.jsx("td",{style:Q.td,children:g("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.medianDev","Median deviation")}),r.jsxs("td",{style:Q.tdRight,children:[C.medianCentDeviation,r.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),r.jsx("td",{style:Q.td,children:g("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.stdDev","Std. deviation")}),r.jsxs("td",{style:Q.tdRight,children:[C.stdDevCents,r.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),r.jsx("td",{style:Q.td,children:g("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),r.jsxs("td",{style:{...Q.tdRight,color:gt(C.intonationAccuracyPct)},children:[C.intonationAccuracyPct,"%"]}),r.jsx("td",{style:Q.td,children:g("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.perfectHitRate","Perfect-hit rate")}),r.jsxs("td",{style:{...Q.tdRight,color:gt(C.perfectHitPct)},children:[C.perfectHitPct,"%"]}),r.jsx("td",{style:Q.td,children:g("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalPitchSamples","Total pitch samples")}),r.jsx("td",{style:Q.tdRight,children:C.totalPitchPoints.toLocaleString()}),r.jsx("td",{style:Q.td,children:g("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.deviationDistribution","Deviation distribution")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.BarChart,{data:C.pitchDeviationHistogram,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"centRange",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:10},angle:-25,textAnchor:"end",height:50}),r.jsx(Ne.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"count",name:g("vocalReport.samples","Samples"),radius:[4,4,0,0],children:C.pitchDeviationHistogram.map((D,W)=>r.jsx(Ne.Cell,{fill:D.centRange.includes("−15 to 0")||D.centRange.includes("0 to +15")?"var(--nice-success, #22c55e)":D.centRange.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"},W))})]})})]}),r.jsxs("div",{style:Q.row,children:[r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.hitClassification","Hit classification")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.PieChart,{children:[r.jsx(Ne.Pie,{data:Z,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:D,value:W})=>`${D}: ${Number(W).toFixed(1)}%`,labelLine:{stroke:"var(--nice-text-muted, #64748b)"},stroke:"var(--nice-bg, #0f172a)",strokeWidth:2,children:Z.map((D,W)=>r.jsx(Ne.Cell,{fill:D.fill},W))}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}})]})})]}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.performanceProfile","Performance profile")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:220,children:r.jsxs(Ne.RadarChart,{data:U,cx:"50%",cy:"50%",outerRadius:75,children:[r.jsx(Ne.PolarGrid,{stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.PolarAngleAxis,{dataKey:"metric",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Radar,{name:"Score",dataKey:"value",stroke:"var(--nice-info, #3b82f6)",fill:"var(--nice-info, #3b82f6)",fillOpacity:.3,strokeWidth:2})]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.pitchTracking","Pitch tracking")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.sungVsExpected","Sung vs expected")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:260,children:r.jsxs(Ne.LineChart,{data:H,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:D=>`${D.toFixed(0)}s`}),r.jsx(Ne.YAxis,{domain:["auto","auto"],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Legend,{wrapperStyle:{color:"var(--nice-text-muted, #94a3b8)",fontSize:12}}),r.jsx(Ne.Line,{type:"monotone",dataKey:"expected",name:g("vocalReport.expected","Expected"),stroke:"var(--nice-success, #22c55e)",dot:!1,strokeWidth:2,strokeOpacity:.6}),r.jsx(Ne.Line,{type:"monotone",dataKey:"sung",name:g("vocalReport.sung","Sung"),stroke:"var(--nice-info, #3b82f6)",dot:!1,strokeWidth:1.5})]})})]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.rollingAccuracy","Rolling accuracy")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:180,children:r.jsxs(Ne.AreaChart,{data:C.accuracyOverTime,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:D=>`${D.toFixed(0)}s`}),r.jsx(Ne.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Area,{type:"monotone",dataKey:"accuracy",stroke:"var(--nice-accent, #8b5cf6)",fill:"var(--nice-accent, #8b5cf6)",fillOpacity:.2,strokeWidth:2})]})})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.vocalRange","Vocal range")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.lowestNote","Lowest note")}),r.jsxs("td",{style:Q.tdRight,children:[C.lowestNote," (",C.lowestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.highestNote","Highest note")}),r.jsxs("td",{style:Q.tdRight,children:[C.highestNote," (",C.highestHz," Hz)"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.rangeLabel","Range")}),r.jsxs("td",{style:Q.tdRight,children:[C.rangeInSemitones," ",g("vocalReport.semitones","semitones")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.tessitura","Tessitura")}),r.jsxs("td",{style:Q.tdRight,children:[C.tessituraLow," — ",C.tessituraHigh]})]})]})})}),r.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.chromagram","Chromagram")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:180,children:r.jsxs(Ne.BarChart,{data:A,margin:{top:5,right:10,bottom:5,left:10},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"note",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"pct",name:g("vocalReport.usagePct","Usage %"),radius:[4,4,0,0],fill:"var(--nice-primary, #6366f1)"})]})})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.vibratoStability","Vibrato & stability")]}),r.jsxs("div",{style:Q.row,children:[r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.vibratoDetected","Vibrato detected")}),r.jsx("td",{style:Q.tdRight,children:r.jsx("span",{style:Q.badge(C.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:C.vibrato.detected?g("vocalReport.yes","Yes"):g("vocalReport.no","No")})})]}),C.vibrato.detected&&r.jsxs(r.Fragment,{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgRate","Avg. rate")}),r.jsxs("td",{style:Q.tdRight,children:[C.vibrato.avgRateHz," Hz"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgExtent","Avg. extent")}),r.jsxs("td",{style:Q.tdRight,children:["±",C.vibrato.avgExtentCents," ",re]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.regularity","Regularity")}),r.jsxs("td",{style:Q.tdRight,children:[C.vibrato.regularityPct,"%"]})]})]})]})})}),r.jsx("div",{style:Q.half,children:r.jsx("table",{style:Q.table,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.jitter","Jitter")}),r.jsxs("td",{style:Q.tdRight,children:[C.jitterPct,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.vocalPresence","Vocal presence")}),r.jsxs("td",{style:Q.tdRight,children:[C.shimmerProxy,"%"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgOnsetDev","Avg. onset deviation")}),r.jsxs("td",{style:Q.tdRight,children:[C.avgOnsetDeviationMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.rhythmStability","Rhythm stability")}),r.jsx("td",{style:Q.tdRight,children:r.jsxs("span",{style:Q.badge(gt(C.rhythmStabilityPct)),children:[C.rhythmStabilityPct,"%"]})})]})]})})})]}),C.verseMetrics.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.verseBreakdown","Per-verse breakdown")]}),r.jsxs("div",{style:Q.chartWrap,children:[r.jsx("div",{style:Q.chartTitle,children:g("vocalReport.accuracyByVerse","Accuracy by verse")}),r.jsx(Ne.ResponsiveContainer,{width:"100%",height:200,children:r.jsxs(Ne.BarChart,{data:q,margin:{top:5,right:20,bottom:5,left:20},children:[r.jsx(Ne.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),r.jsx(Ne.XAxis,{dataKey:"verse",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),r.jsx(Ne.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),r.jsx(Ne.Bar,{dataKey:"accuracy",name:g("vocalReport.hitPct","Hit %"),radius:[4,4,0,0],children:q.map((D,W)=>r.jsx(Ne.Cell,{fill:Vs(D.label)},W))})]})})]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:g("vocalReport.verse","Verse")}),r.jsx("th",{style:Q.th,children:g("vocalReport.rating","Rating")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.hitPct","Hit %")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.avgDeviation","Avg. dev.")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.notes","Notes")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.notesHit","Hit")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.comboBonus","Combo bonus")})]})}),r.jsx("tbody",{children:C.verseMetrics.map((D,W)=>r.jsxs("tr",{children:[r.jsxs("td",{style:Q.td,children:[g("vocalReport.verse","Verse")," ",D.verseIndex+1]}),r.jsx("td",{style:Q.td,children:r.jsx("span",{style:Q.badge(Vs(D.label)),children:D.label})}),r.jsxs("td",{style:Q.tdRight,children:[(D.hitFraction*100).toFixed(1),"%"]}),r.jsxs("td",{style:Q.tdRight,children:[D.avgCentDeviation," ¢"]}),r.jsx("td",{style:Q.tdRight,children:D.noteCount}),r.jsx("td",{style:Q.tdRight,children:D.notesHit}),r.jsxs("td",{style:Q.tdRight,children:["+",D.comboBonus]})]},W))})]})]}),r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.scoringConfig","Scoring configuration")]}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:g("vocalReport.parameter","Parameter")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),r.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyLevel","Difficulty level")}),r.jsx("td",{style:Q.tdRight,children:C.difficulty}),r.jsx("td",{style:Q.td,children:g("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.semitoneTolerance","Semitone tolerance")}),r.jsx("td",{style:Q.tdRight,children:O.semitoneTolerance}),r.jsx("td",{style:Q.td,children:g("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.preWindow","Pre window")}),r.jsxs("td",{style:Q.tdRight,children:[O.preWindow," s"]}),r.jsx("td",{style:Q.td,children:g("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.postExtra","Post extra")}),r.jsxs("td",{style:Q.tdRight,children:[O.postExtra," s"]}),r.jsx("td",{style:Q.td,children:g("vocalReport.postExtraDesc","Grace time after a note.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyMultiplier","Difficulty multiplier")}),r.jsxs("td",{style:Q.tdRight,children:[O.difficultyMult,"×"]}),r.jsx("td",{style:Q.td,children:g("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.songBpm","Song BPM")}),r.jsx("td",{style:Q.tdRight,children:C.songBpm}),r.jsx("td",{style:Q.td,children:g("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalNotes","Total notes")}),r.jsx("td",{style:Q.tdRight,children:w}),r.jsx("td",{style:Q.td,children:g("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),S.some(D=>D.micSettings)&&r.jsxs(r.Fragment,{children:[r.jsxs("h2",{style:Q.sectionTitle,children:[++L,". ",g("vocalReport.micConfig","Microphone configuration")]}),S.map((D,W)=>D.micSettings&&r.jsxs("div",{style:{marginBottom:16},children:[S.length>1&&r.jsx("h4",{style:{color:D.playerColor,margin:"0 0 8px",fontSize:14},children:D.playerName}),r.jsxs("table",{style:Q.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:Q.th,children:g("vocalReport.setting","Setting")}),r.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")})]})}),r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.device","Device")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.deviceLabel||D.micSettings.deviceId})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchAlgorithm","Pitch algorithm")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.algorithm})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.inputGain","Input gain")}),r.jsxs("td",{style:Q.tdRight,children:[D.micSettings.gain,"×"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.rmsThreshold","RMS threshold")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.rmsThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchThreshold","Pitch threshold")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.pitchThreshold})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.smoothingWindow","Smoothing window")}),r.jsxs("td",{style:Q.tdRight,children:[D.micSettings.smoothingWindow," ",g("vocalReport.frames","frames")]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.hysteresisFrames","Hysteresis frames")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.hysteresisFrames})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.hanningWindow","Hanning window")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.useHanning?g("vocalReport.enabled","Enabled"):g("vocalReport.disabled","Disabled")})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.latencyOffset","Latency offset")}),r.jsxs("td",{style:Q.tdRight,children:[D.micSettings.latencyOffsetMs," ms"]})]}),r.jsxs("tr",{children:[r.jsx("td",{style:Q.tdBold,children:g("vocalReport.monitor","Monitor")}),r.jsx("td",{style:Q.tdRight,children:D.micSettings.monitorEnabled?`${g("vocalReport.on","On")} (${Math.round(D.micSettings.monitorVolume*100)}%)`:g("vocalReport.off","Off")})]})]})]})]},W))]}),r.jsx("div",{style:Q.footer,children:r.jsxs("p",{children:[g("vocalReport.footerGenerated","Report generated")," ·"," ",C.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Bh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function Gh(e){if(!e)return"";const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function Hs(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,n)=>t.localeCompare(n))}const Uo=d.memo(({song:e,index:t,active:n,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:u,onToggleSelect:h,onFocusRow:p})=>{const f=()=>{o?h(e.id):l||u==null||u(e)};return r.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${n?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:n?0:-1,onClick:f,onFocus:()=>p(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),f())},children:[o&&r.jsx("input",{type:"checkbox",className:"nice-ksb-row__check",checked:i,onChange:()=>h(e.id),onClick:y=>y.stopPropagation(),"aria-label":e.title}),r.jsx("img",{className:"nice-ksb-row__cover",src:a,alt:"",loading:"lazy"}),r.jsxs("div",{className:"nice-ksb-row__main",children:[r.jsx("div",{className:"nice-ksb-row__title",children:e.title}),r.jsx("div",{className:"nice-ksb-row__artist",children:e.artist||"—"})]}),r.jsxs("div",{className:"nice-ksb-row__meta",children:[e.genre&&r.jsx("span",{className:"nice-ksb-badge",children:e.genre}),e.year&&r.jsx("span",{className:"nice-ksb-badge",children:e.year}),e.durationSec?r.jsx("span",{className:"nice-ksb-badge",children:Gh(e.durationSec)}):null,e.externalSource&&r.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&r.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[r.jsx(se.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&r.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),u==null||u(e)},children:[r.jsx(se.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})});Uo.displayName="NiceKaraokeSongRow";const Wh=({songs:e,fetchSongs:t,loading:n=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:u=!0,enableGamepad:h=!0,disabled:p=!1,disabledReason:f,t:y,className:m,style:v,id:x,accessMode:g,"data-testid":k})=>{const{t:b}=Te(),S=y??b,[M,R]=d.useState(""),[N,C]=d.useState(""),[w,O]=d.useState(""),[$,E]=d.useState(""),[_,L]=d.useState("artist"),[U,Z]=d.useState("asc"),[A,q]=d.useState({type:"all"}),[H,re]=d.useState(new Set),[D,W]=d.useState([]),[j,F]=d.useState(!1);d.useEffect(()=>{const ce=setTimeout(()=>C(M),300);return()=>clearTimeout(ce)},[M]),d.useEffect(()=>{if(e||!t)return;let ce=!1;return F(!0),Promise.resolve(t({searchQuery:N.trim()||void 0,genres:w?[w]:void 0,languages:$?[$]:void 0})).then(ye=>!ce&&W(ye)).catch(()=>!ce&&W([])).finally(()=>!ce&&F(!1)),()=>{ce=!0}},[e,t,N,w,$]);const I=e??D,P=d.useMemo(()=>Hs(I.map(ce=>ce.genre)),[I]),T=d.useMemo(()=>Hs(I.map(ce=>ce.language)),[I]),z=d.useMemo(()=>{let ce=I;const ye=N.trim().toLowerCase();ye&&(ce=ce.filter(ae=>`${ae.title} ${ae.artist}`.toLowerCase().includes(ye))),w&&(ce=ce.filter(ae=>ae.genre===w)),$&&(ce=ce.filter(ae=>ae.language===$)),A.type==="genre"&&(ce=ce.filter(ae=>ae.genre===A.value)),A.type==="language"&&(ce=ce.filter(ae=>ae.language===A.value));const Se=U==="asc"?1:-1;return[...ce].sort((ae,ue)=>{const Ie=ae[_]??"",ze=ue[_]??"";return typeof Ie=="number"&&typeof ze=="number"?(Ie-ze)*Se:String(Ie).localeCompare(String(ze))*Se})},[I,N,w,$,A,_,U]),B=ce=>{re(ye=>{const Se=new Set(ye);return Se.has(ce)?Se.delete(ce):(c===0||Se.size<c)&&Se.add(ce),Se})},G=()=>{const ce=I.filter(ye=>H.has(ye.id));o==null||o({songs:ce})},Y=n||j,X=ce=>{ce===_?Z(ye=>ye==="asc"?"desc":"asc"):(L(ce),Z("asc"))},ie=d.useRef(null),[le,te]=d.useState(0),V=d.useRef(0),K=d.useRef(z);K.current=z,d.useEffect(()=>{te(ce=>{const ye=Math.min(Math.max(0,ce),Math.max(0,z.length-1));return V.current=ye,ye})},[z.length]);const oe=d.useCallback(ce=>{var Se;const ye=(Se=ie.current)==null?void 0:Se.querySelector(`[data-ksb-index="${ce}"]`);ye==null||ye.focus(),ye==null||ye.scrollIntoView({block:"nearest"})},[]),ne=d.useCallback(ce=>{V.current=ce,te(ce)},[]),he=d.useCallback((ce,ye=!0)=>{const Se=K.current.length;if(Se===0)return;const ae=Math.min(Se-1,Math.max(0,ce));V.current=ae,te(ae),ye&&requestAnimationFrame(()=>oe(ae))},[oe]),J=d.useCallback(ce=>he(V.current+ce),[he]),de=ce=>{const ye=K.current[ce];ye&&(l?B(ye.id):p||i==null||i(ye))},me=ce=>{switch(ce.key){case"ArrowDown":ce.preventDefault(),J(1);break;case"ArrowUp":ce.preventDefault(),J(-1);break;case"Home":ce.preventDefault(),he(0);break;case"End":ce.preventDefault(),he(K.current.length-1);break;case"PageDown":ce.preventDefault(),J(5);break;case"PageUp":ce.preventDefault(),J(-5);break}},xe=aa.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>J(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>J(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>J(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>J(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>de(V.current)},confirm:{button:"Start",onPress:()=>{l&&G()}}}});return g==="hidden"?null:r.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:v,id:x,"data-testid":k,children:[u&&r.jsxs("aside",{className:"nice-ksb__sidebar",children:[r.jsxs("button",{type:"button",className:`nice-ksb__node${A.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>q({type:"all"}),children:[r.jsx(se.NtdMusic,{size:14})," ",S("karaokeBrowser.allSongs","All songs")," (",I.length,")"]}),P.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:S("karaokeBrowser.genres","Genres")}),P.map(ce=>r.jsx("button",{type:"button",className:`nice-ksb__node${A.type==="genre"&&A.value===ce?" nice-ksb__node--active":""}`,onClick:()=>q({type:"genre",value:ce}),children:ce},ce))]}),T.length>0&&r.jsxs("div",{className:"nice-ksb__facet",children:[r.jsx("div",{className:"nice-ksb__facet-title",children:S("karaokeBrowser.languages","Languages")}),T.map(ce=>r.jsx("button",{type:"button",className:`nice-ksb__node${A.type==="language"&&A.value===ce?" nice-ksb__node--active":""}`,onClick:()=>q({type:"language",value:ce}),children:ce},ce))]})]}),r.jsxs("div",{className:"nice-ksb__main",children:[r.jsxs("div",{className:"nice-ksb__toolbar",children:[r.jsx("input",{className:"nice-ksb__search",type:"search",value:M,placeholder:S("karaokeBrowser.search","Search title or artist…"),onChange:ce=>R(ce.target.value)}),r.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(ce=>r.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${_===ce?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(ce),children:[S(`karaokeBrowser.sort.${ce}`,ce),_===ce&&(U==="asc"?r.jsx(se.NtdChevronUp,{size:12}):r.jsx(se.NtdChevronDown,{size:12}))]},ce))}),r.jsxs("span",{className:`nice-ksb__navhint${xe.connected?" nice-ksb__navhint--pad":""}`,title:S("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[xe.connected?r.jsx(se.NtdGamepad,{size:14}):r.jsx(se.NtdMove,{size:14}),r.jsx("span",{className:"nice-ksb__navhint-keys",children:xe.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),p&&f&&r.jsx("div",{className:"nice-ksb__disabled",children:f}),r.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":S("karaokeBrowser.songs","Songs"),ref:ie,onKeyDown:me,children:Y?r.jsx("div",{className:"nice-ksb__empty",children:S("karaokeBrowser.loading","Loading…")}):z.length===0?r.jsx("div",{className:"nice-ksb__empty",children:S("karaokeBrowser.noResults","No songs found")}):z.map((ce,ye)=>r.jsx(Uo,{song:ce,index:ye,active:ye===le,coverUrl:(a==null?void 0:a(ce))||ce.coverImage||ce.externalCoverUrl||ce.coverPath||Bh,topScore:s==null?void 0:s(ce),selected:H.has(ce.id),multiSelect:l,disabled:p,t:S,onPlay:i,onToggleSelect:B,onFocusRow:ne},ce.id))}),l&&r.jsxs("div",{className:"nice-ksb__footer",children:[r.jsxs("span",{children:[H.size,c>0?` / ${c}`:""," ",S("karaokeBrowser.selected","selected")]}),r.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:H.size===0,onClick:G,children:S("karaokeBrowser.confirm","Add selected")})]})]})]})};function qo(e,t,n=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(n/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const u=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=u)}return l}function Ks(e,t,n=1e3){const a=Math.max(1,Math.round(t/n)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,u=Math.min(e.length,c+a);let h=0;for(let p=c;p<u;p++)h+=Math.abs(e[p]);i[l]=h/(u-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function Uh(e,t){const n=e.length,a=t.length;if(n===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,u=0;for(let f=0;f<n;f++){const y=f+o+Math.floor((a-n)/2);if(y<0||y>=a)continue;const m=e[f],v=t[y];l+=m*v,c+=m*m,u+=v*v}const h=Math.sqrt(Math.max(1e-9,c*u)),p=l/h;p>s.score&&(s={lag:o,score:p})}return s.lag}function Vo(e,t,n=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=qo(s,t,n,a),o=Ks(e,t,1e3),l=Ks(i,t,1e3),u=Uh(l.env,o.env)*1e3/1e3;return Math.round(u)}catch{return null}}const qh=({deviceId:e,initialOffsetMs:t=null,onSave:n,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:u,"data-testid":h})=>{const{t:p}=Te(),f=i??p,[y,m]=d.useState(null),[v,x]=d.useState(t),[g,k]=d.useState(!1),[b,S]=d.useState([]),[M,R]=d.useState(0),[N,C]=d.useState(!1),w=d.useRef(!1);d.useEffect(()=>{x(t??null)},[t,e]);const O=async()=>{const L=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),U=new AudioContext,Z=U.sampleRate,A=U.createMediaStreamSource(L),q=U.createScriptProcessor(2048,1,1);A.connect(q),q.connect(U.destination);const H=1200,re=Math.round(H/1e3*Z),D=new Float32Array(re);let W=0,j=!1;q.onaudioprocess=B=>{if(j)return;const G=B.inputBuffer.getChannelData(0),Y=Math.min(G.length,re-W);Y>0&&(D.set(G.subarray(0,Y),W),W+=Y),W>=re&&(j=!0)},await new Promise(B=>setTimeout(B,80));const F=new AudioContext,I=F.createOscillator(),P=F.createGain();I.type="sine",I.frequency.value=1e3,P.gain.value=1e-4,I.connect(P),P.connect(F.destination);const T=F.currentTime+.05;P.gain.setValueAtTime(1e-4,T-.01),P.gain.linearRampToValueAtTime(1,T),P.gain.linearRampToValueAtTime(1e-4,T+.06),I.start(T-.02),I.stop(T+.1),await new Promise(B=>{const G=()=>{if(j||W>=re){B();return}setTimeout(G,50)};setTimeout(()=>{j=!0,B()},H+500),G()}),q.onaudioprocess=null;try{q.disconnect()}catch{}try{A.disconnect()}catch{}try{await F.close()}catch{}try{await U.close()}catch{}L.getTracks().forEach(B=>B.stop());const z=D.subarray(0,W);return Vo(z,Z,130,30)},$=async()=>{if(!w.current){w.current=!0,C(!0),m(f("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),x(null),S([]),R(0);try{const L=[];for(let Z=0;Z<s;Z++){m(`${f("latencyCalibrator.playingTone","Playing test tone and recording…")} (${Z+1}/${s})`),R(Math.round(Z/s*100));const A=await O();A!==null&&(L.push(Math.max(-500,Math.min(2e3,Math.round(A)))),S([...L])),Z<s-1&&await new Promise(q=>setTimeout(q,400))}if(R(100),L.length===0){m(f("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let U;if(L.length>=3){const A=[...L].sort((q,H)=>q-H).slice(1,-1);U=Math.round(A.reduce((q,H)=>q+H,0)/A.length)}else U=Math.round(L.reduce((Z,A)=>Z+A,0)/L.length);x(U),m(`${f("latencyCalibrator.measured","Measured")} ~${U} ms (${L.length}: ${L.join(", ")} ms)`)}catch(L){m(`${f("latencyCalibrator.calibrationError","Calibration error: ")}${L instanceof Error?L.message:String(L)}`)}finally{w.current=!1,C(!1)}}},E=async()=>{if(!(v===null||!n)){k(!0);try{await n(Math.round(v)),m(f("latencyCalibrator.saved","Saved"))}catch(L){m(`${f("latencyCalibrator.saveError","Save error: ")}${String(L)}`)}finally{k(!1)}}},_={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return u==="hidden"?null:r.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[r.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdSettings,{size:16})," ",f("latencyCalibrator.title","Latency calibrator — microphone")]}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[f("latencyCalibrator.device","Device"),": ",r.jsx("small",{children:e||"—"})]}),r.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[r.jsx("button",{type:"button",onClick:$,disabled:N,style:{..._,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-bg, #fff)"},children:f("latencyCalibrator.calibrate","Calibrate")}),r.jsx("button",{type:"button",onClick:()=>{x(null),m(null),S([]),R(0)},style:{..._,background:"var(--bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:f("latencyCalibrator.clear","Clear")})]}),N&&r.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${M}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),b.length>0&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[f("latencyCalibrator.rounds","Rounds"),": ",b.join(", ")," ms"]}),r.jsxs("div",{style:{marginTop:8,fontSize:13},children:[r.jsxs("div",{children:[f("latencyCalibrator.status","Status"),": ",y??f("latencyCalibrator.none","none")]}),r.jsxs("div",{children:[f("latencyCalibrator.measuredOffset","Measured offset"),":"," ",v!==null?r.jsxs("strong",{children:[v," ms"]}):"—"]})]}),r.jsxs("div",{style:{marginTop:12,display:"flex",gap:8},children:[n&&r.jsx("button",{type:"button",onClick:E,disabled:v===null||g,style:{..._,background:"var(--nice-success, #22c55e)",color:"var(--nice-bg, #fff)",opacity:v===null||g?.5:1},children:f("latencyCalibrator.save","Save")}),a&&r.jsx("button",{type:"button",onClick:a,style:{..._,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:f("latencyCalibrator.close","Close")})]})]})},Vh=[{value:"normal",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMicrophone,{size:14})," Mic"]})},{value:"pad",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdGamepad,{size:14})," Pad"]})},{value:"demo",label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdStopwatch,{size:14})," Demo"]})}],Ho=({players:e,onPlayersChange:t,gameMode:n="normal",onGameModeChange:a,gameModes:s=Vh,difficulty:i="normal",onDifficultyChange:o,audioInputs:l,maxPlayers:c=4,onCalibrate:u,t:h,className:p,style:f,id:y,accessMode:m,"data-testid":v})=>{const{t:x}=Te(),g=h??x,[k,b]=d.useState([]);d.useEffect(()=>{var $,E,_;if(l||!(($=navigator.mediaDevices)!=null&&$.enumerateDevices))return;let w=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then(L=>!w&&b(L.filter(U=>U.kind==="audioinput"))).catch(()=>{});return O(),(_=(E=navigator.mediaDevices).addEventListener)==null||_.call(E,"devicechange",O),()=>{var L,U;w=!0,(U=(L=navigator.mediaDevices).removeEventListener)==null||U.call(L,"devicechange",O)}},[l]);const S=l??k,M=d.useMemo(()=>[{value:"",label:g("karaokeSetup.noMic","No microphone")},...S.map((w,O)=>({value:w.deviceId,label:w.label||`${g("karaokeSetup.microphone","Microphone")} ${O+1}`}))],[S,g]),R=(w,O)=>t(e.map($=>$.id===w?{...$,...O}:$)),N=()=>{if(e.length>=c)return;const w=e.reduce((O,$)=>Math.max(O,$.id),0)+1;t([...e,{id:w,name:`${g("karaokeSetup.player","Player")} ${e.length+1}`,color:Je[e.length%Je.length],micId:null}])},C=w=>t(e.filter(O=>O.id!==w));return m==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-setup${p?` ${p}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...f},id:y,"data-testid":v,children:[r.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:g("karaokeSetup.mode","Game mode")}),r.jsx(we.NiceSegmentedControl,{options:s,value:n,onChange:w=>a==null?void 0:a(w)})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:g("karaokeSetup.difficulty","Difficulty")}),r.jsx(we.NiceSegmentedControl,{options:[{value:"easy",label:g("karaokeSetup.easy","Easy")},{value:"normal",label:g("karaokeSetup.normal","Normal")},{value:"hard",label:g("karaokeSetup.hard","Hard")}],value:i,onChange:w=>o==null?void 0:o(w)})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[r.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[g("karaokeSetup.players","Players")," (",e.length,"/",c,")"]}),e.map(w=>r.jsx(we.NiceCard,{children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[r.jsx(we.NiceColorPicker,{value:w.color||Je[0],onChange:O=>R(w.id,{color:O})}),r.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:r.jsx(we.NiceTextInput,{value:w.name,onChange:O=>R(w.id,{name:O}),placeholder:g("karaokeSetup.playerName","Player name"),size:"sm"})}),r.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:r.jsx(we.NiceSelect,{options:M,value:w.micId??"",onChange:O=>R(w.id,{micId:(typeof O=="string"?O:O[0])||null}),placeholder:g("karaokeSetup.selectMic","Microphone"),size:"sm"})}),u&&w.micId&&r.jsxs(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>u(w.micId),children:[r.jsx(se.NtdSettings,{size:14})," ",g("karaokeSetup.calibrate","Calibrate")]}),r.jsx(we.NiceButton,{variant:"danger",size:"sm",onClick:()=>C(w.id),"aria-label":g("karaokeSetup.remove","Remove"),children:r.jsx(se.NtdClose,{size:14})})]})},w.id)),r.jsx("div",{children:r.jsxs(we.NiceButton,{variant:"primary",onClick:N,disabled:e.length>=c,children:[r.jsx(se.NtdPlus,{size:14})," ",g("karaokeSetup.addPlayer","Add player")]})})]})]})},Hh=["freeForAll","roundRobin","hostOnly","firstCome"],Kh={freeForAll:se.NtdDice,roundRobin:se.NtdRepeat,hostOnly:se.NtdCrown,firstCome:se.NtdLightning},Yh={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},Ko=({players:e,mode:t,onModeChange:n,turnTimeSec:a=30,hostIndex:s=0,onActivePlayerChange:i,myPlayerIndex:o,t:l,className:c,style:u,id:h,accessMode:p,"data-testid":f})=>{const{t:y}=Te(),m=l??y,v={freeForAll:m("songSelection.freeForAll","Free for all"),roundRobin:m("songSelection.roundRobin","Round robin"),hostOnly:m("songSelection.hostOnly","Host only"),firstCome:m("songSelection.firstCome","First come")},[x,g]=d.useState(0),[k,b]=d.useState(a),S=d.useRef(null),[M,R]=d.useState(null),[N,C]=d.useState(!1),[w,O]=d.useState(null),$=d.useRef(null),E=d.useMemo(()=>t==="hostOnly"?s:t==="roundRobin"?x%Math.max(1,e.length):t==="firstCome"?N?-1:w??-1:-1,[t,x,e.length,s,N,w]);d.useEffect(()=>{i==null||i(E)},[E,i]),d.useEffect(()=>{if(t!=="roundRobin"||a<=0){S.current&&clearInterval(S.current);return}return b(a),S.current=setInterval(()=>{b(A=>A<=1?(g(q=>q+1),a):A-1)},1e3),()=>{S.current&&clearInterval(S.current)}},[t,a,x]);const _=d.useCallback(()=>{O(null),C(!1),R(3),$.current&&clearInterval($.current),$.current=setInterval(()=>{R(A=>A===null||A<=1?($.current&&clearInterval($.current),C(!0),null):A-1)},1e3)},[]);d.useEffect(()=>()=>{$.current&&clearInterval($.current)},[]),d.useEffect(()=>{t!=="firstCome"&&(R(null),C(!1),O(null))},[t]);const L=d.useCallback(()=>{g(A=>A+1),b(a)},[a]),U=A=>{var q;return((q=e[A])==null?void 0:q.name)||`${m("songSelection.player","Player")} ${A+1}`},Z=E>=0&&E<e.length?e[E]:null;return p==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-selection-mode${c?` ${c}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...u},id:h,"data-testid":f,children:[r.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:Hh.map(A=>r.jsxs(we.NiceButton,{size:"sm",variant:t===A?Yh[A]:"outline",onClick:()=>n==null?void 0:n(A),children:[d.createElement(Kh[A],{size:14})," ",v[A]]},A))}),t!=="freeForAll"&&t!=="firstCome"&&Z&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsxs(we.NiceBadge,{variant:E===o?"success":"secondary",children:[r.jsx(se.NtdMicrophone,{size:12})," ",U(E)]}),E===o&&r.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:m("songSelection.yourTurn","Your turn!")})]}),t==="roundRobin"&&a>0&&r.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:r.jsx(we.NiceProgress,{value:k,max:a,variant:k<=5?"error":k<=10?"warning":"info",showLabel:!0,formatValue:A=>`${A}s`})}),t==="roundRobin"&&r.jsxs(we.NiceButton,{size:"sm",variant:"ghost",onClick:L,children:[m("songSelection.next","Next")," ",r.jsx(se.NtdPlay,{size:12})]}),t==="firstCome"&&r.jsxs(r.Fragment,{children:[M!==null&&r.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:M}),N&&w===null&&r.jsxs(we.NiceBadge,{variant:"danger",children:[r.jsx(se.NtdLightning,{size:12})," ",m("songSelection.raceGo","GO! Pick a song!")]}),w!==null&&w<e.length&&r.jsxs(we.NiceBadge,{variant:"success",children:[r.jsx(se.NtdTrophy,{size:12})," ",U(w)," ",m("songSelection.raceWon","picks!")]}),r.jsx(we.NiceButton,{size:"sm",variant:M!==null?"secondary":"danger",onClick:_,disabled:M!==null,children:w!==null?r.jsxs(r.Fragment,{children:[r.jsx(se.NtdRepeat,{size:12})," ",m("songSelection.raceAgain","New race")]}):r.jsxs(r.Fragment,{children:[r.jsx(se.NtdLightning,{size:12})," ",m("songSelection.raceStart","Start race")]})})]})]})};function Zh(e,t,n,a){return d.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===n:e==="roundRobin"?a===t:!1,[e,t,n,a])}const Xh=({players:e,onPlayersChange:t,gameMode:n,onGameModeChange:a,gameModes:s,difficulty:i,onDifficultyChange:o,audioInputs:l,maxPlayers:c=4,onCalibrate:u,initialSelectionMode:h="freeForAll",turnTimeSec:p=30,hostIndex:f=0,myPlayerIndex:y,onChange:m,variant:v="bar",t:x,className:g,style:k,id:b,accessMode:S,"data-testid":M})=>{const{t:R}=Te(),N=x??R,[C,w]=d.useState([]);d.useEffect(()=>{var F,I,P;if(l||!((F=navigator.mediaDevices)!=null&&F.enumerateDevices))return;let W=!1;const j=()=>navigator.mediaDevices.enumerateDevices().then(T=>!W&&w(T.filter(z=>z.kind==="audioinput"))).catch(()=>{});return j(),(P=(I=navigator.mediaDevices).addEventListener)==null||P.call(I,"devicechange",j),()=>{var T,z;W=!0,(z=(T=navigator.mediaDevices).removeEventListener)==null||z.call(T,"devicechange",j)}},[l]);const O=l??C,$=O.length===0,E=e.some(W=>!W.micId),_=!E,[L,U]=d.useState(h),[Z,A]=d.useState(-1),q=d.useCallback((W,j)=>{m==null||m({selectionMode:W,activePickerIndex:j,allMicsAssigned:_,noInputDevices:$})},[m,_,$]),H=d.useCallback(W=>{U(W),q(W,Z)},[q,Z]),re=d.useCallback(W=>{A(W),q(L,W)},[q,L]),D=d.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return S==="hidden"?null:r.jsxs("div",{className:`nice-karaoke-session-join${g?` ${g}`:""}`,style:v==="card"?{background:"var(--bg-secondary)",borderRadius:12,padding:16,...k}:k,id:b,"data-testid":M,children:[r.jsx(Ho,{players:e,onPlayersChange:t,gameMode:n,onGameModeChange:a,gameModes:s,difficulty:i,onDifficultyChange:o,audioInputs:O,maxPlayers:c,onCalibrate:u,t:N}),$&&r.jsxs("div",{style:{...D,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[N("karaokeSessionJoin.noInputDevices","No microphone detected"),r.jsx("br",{}),r.jsx("span",{style:{fontWeight:400,fontSize:13},children:N("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!$&&E&&r.jsx("div",{style:{...D,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-bg, #222)",fontSize:14},children:N("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),e.length>1&&r.jsx("div",{style:{marginTop:12},children:r.jsx(Ko,{players:e,mode:L,onModeChange:H,onActivePlayerChange:re,turnTimeSec:p,hostIndex:f,myPlayerIndex:y,t:N})})]})};function We(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=n==="otf"?"opentype":n==="woff2"?"woff2":n==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const Qh=[We("Belagak","BelagakRegular-dr1zE.otf"),We("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),We("Gerhaus","Gerhaus-PK69E.ttf"),We("Gerhaus Italic","GerhausItalic-d96l7.ttf"),We("Handone Medium","HandoneMedium-nAevO.otf"),We("Handson Bold","HandsonBold-9MnrL.otf"),We("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),We("Kineks Round Light","KineksRoundLight-m2r35.ttf"),We("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),We("Kineks Round","KineksRoundRegular-PVRl7.ttf"),We("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),We("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),We("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),We("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),We("Lemon Milk Light","LemonMilkLight-owxMq.otf"),We("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),We("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),We("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),We("Lemon Milk","LemonMilkRegular-X3XE2.otf"),We("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),We("Pemage","PemageRegular-YqrdO.otf"),We("Rosmatika","RosmatikaRegular-BWA45.ttf"),We("Scabber","Scabber-q2Mn0.ttf"),We("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),We("Super Adorable","SuperAdorable-MAvyp.ttf"),We("Super Chiby","SuperChiby-BL62V.ttf"),We("Super Joyful","SuperJoyful-lxwPq.ttf"),We("Super Kindly","SuperKindly-drE8E.ttf"),We("Super Meatball","SuperMeatball-Yq1Gy.ttf")],Qa="nice2dev-karaoke-display",Jh=[{value:"Arial",label:"Arial (default)"},{value:"Georgia, serif",label:"Georgia"},{value:"'Courier New', monospace",label:"Courier New"},{value:"'Trebuchet MS', sans-serif",label:"Trebuchet MS"},{value:"Impact, sans-serif",label:"Impact"},...Qh.map(e=>({value:e.family,label:e.family}))],Yo=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],pn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let Ys=!1;function Zo(){try{const e=localStorage.getItem(Qa);if(e){const t=JSON.parse(e);return{...pn,...t}}}catch{}return{...pn}}async function ep(e){if(Ys||(Ys=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),a={...pn,...n};localStorage.setItem(Qa,JSON.stringify(a))}catch{}}function tp(e){const t=JSON.stringify(e);localStorage.setItem(Qa,t),Ja(e)}function Xo(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Yo.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:pn.customSungGradient,goldGradient:pn.customGoldGradient,glowColor:pn.customGlowColor}}function Ja(e){const{sungGradient:t,goldGradient:n,glowColor:a}=Xo(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${n[0]}, ${n[1]}, ${n[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${n[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function np(){const e=Zo();Ja(e)}function rp(e){const t=(e||"").split(/\r?\n/),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,u=isNaN(l)?0:l/10;n.push({lineIndex:a,start:c,duration:u,raw:t[a]})}}return n}const ap=({index:e,style:t,data:n})=>{const{lines:a,notes:s,currentIndex:i,animationConfig:o}=n,l=a[e]??"",c=s.findIndex(k=>k.lineIndex===e),u=c>=0&&c===i,h=(o==null?void 0:o.enabled)??!0,p=(o==null?void 0:o.durationMs)??300,f=(o==null?void 0:o.translateX)??8,y=(o==null?void 0:o.scale)??1.01,m=(o==null?void 0:o.easing)??"cubic-bezier(.22,1,.36,1)",v=(o==null?void 0:o.opacityInactive)??.9,x=(o==null?void 0:o.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",g={transition:h?`transform ${p}ms ${m}, opacity ${p}ms ${m}`:"none",transform:u?`translateX(${f}px) scale(${y})`:"translateX(0px) scale(1)",opacity:u?1:v,boxShadow:u?x:"none"};return r.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":c>=0?c:void 0,children:r.jsx("div",{style:{...g,background:u?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:r.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:l})})})},Qo=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:a})=>{const{t:s}=Te(),i=d.useRef(null),o=n??i,[l,c]=d.useState(!1),u=d.useMemo(()=>rp(e),[e]),h=d.useRef(null),p=d.useRef(null),f=d.useRef(null),y=d.useRef(0),m=d.useRef(0),[v,x]=d.useState(-1),g=d.useMemo(()=>(e||"").split(/\r?\n/),[e]),k=28,b=g.length*k,S=d.useMemo(()=>({lines:g,notes:u,currentIndex:v,animationConfig:a}),[g,u,v,a]);return d.useEffect(()=>{const M=o.current;M&&(l?M.play().catch(()=>c(!1)):M.pause())},[l,o]),d.useEffect(()=>{const M=o.current;if(!M)return;let R=-1;const N=a??null,C=N&&typeof N.scrollSmooth=="number"?N.scrollSmooth:.18;let w=performance.now();const O=()=>{var D,W;const $=performance.now(),E=Math.max(0,Math.min(.2,($-w)/1e3));w=$;const _=M.currentTime||0;y.current=_;let L=-1;for(let j=0;j<u.length;j++){const F=u[j];if(_>=F.start&&_<F.start+Math.max(.001,F.duration)){L=j;break}}L!==R&&(R=L,x(L));let U=0;if(R>=0){const j=((D=u[R])==null?void 0:D.lineIndex)??0,F=((W=p.current)==null?void 0:W.clientHeight)??220;U=j*k-F/2+k/2;const I=Math.max(0,b-F);(isNaN(U)||!isFinite(U))&&(U=0),U=Math.max(0,Math.min(U,I))}const Z=1-Math.pow(Math.max(0,1-C),Math.min(4,E*60)),re=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?j=>j:j=>1-Math.pow(1-j,3))(Z);m.current=m.current+(U-m.current)*re;try{const j=p.current;j&&typeof j.scrollTop=="number"&&(j.scrollTop=Math.round(m.current))}catch{}f.current=requestAnimationFrame(O)};return f.current=requestAnimationFrame(O),()=>{f.current&&cancelAnimationFrame(f.current)}},[o,u,b,a]),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[r.jsx("button",{onClick:()=>c(M=>!M),disabled:!t,children:l?"Pause":"Play"}),r.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(y.current||0).toFixed(2),"s"]}),r.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",u.length]})]}),r.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?r.jsx(Hc.FixedSizeList,{height:220,width:"100%",itemCount:g.length,itemSize:k,ref:h,outerRef:p,itemData:S,children:ap}):r.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!n&&r.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function sp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),n=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;n.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:n}}function Jo({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:a}){const s=d.useRef(null),i=d.useRef(null),o=d.useRef([]),l=d.useRef([]),c=d.useRef(null),u=d.useRef(t);return u.current=t,d.useEffect(()=>{const{lines:h,notes:p}=sp(e);o.current=h,l.current=p;const f=c.current;f&&"rebuildTexts"in f&&typeof f.rebuildTexts=="function"&&f.rebuildTexts()},[e]),d.useEffect(()=>{let h=!0;return(async()=>{var R;if(!h||!s.current)return;const p=await import("phaser"),f="default"in p?p.default:p;if(!s.current||!h)return;const y=o,m=l,v=c,x=n,g=a,k=u;class b extends f.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(v.current=this,this.rebuildTexts(),g!=null&&g.current)this.audioEl=null;else if(x!=null&&x.current)this.audioEl=x.current;else{const C=document.querySelector("audio");C instanceof HTMLAudioElement?this.audioEl=C:k.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=k.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const E of this.texts)E.destroy();this.texts=[];const C={font:"18px monospace",color:"var(--nice-bg, #fff)"},w=22;let O=20;const $=y.current;for(let E=0;E<$.length;E++){const _=this.add.text(10,O,$[E]||" ",C).setOrigin(0,0);this.texts.push(_),O+=w}}update(){let C=0;if(g!=null&&g.current&&typeof g.current.getCurrentTime=="function")try{C=g.current.getCurrentTime()||0}catch{C=0}else C=this.audioEl&&this.audioEl.currentTime||0;for(let O=0;O<this.texts.length;O++)this.texts[O].setStyle({backgroundColor:void 0,color:"var(--nice-bg, #fff)"});const w=m.current;for(const O of w)if(C>=O.start&&C<O.start+Math.max(.001,O.duration)){const $=this.texts[O.lineIndex];$&&$.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"var(--nice-info, #00aaff)"})}}}const S=((R=s.current)==null?void 0:R.clientWidth)??640,M={type:f.AUTO,parent:s.current,width:S,height:Math.round(S/2),backgroundColor:"#101010",scene:[b]};i.current=new f.Game(M)})(),()=>{h=!1,c.current=null;try{const p=i.current;p&&typeof p.destroy=="function"&&p.destroy(!0)}catch{}}},[]),r.jsx("div",{ref:s,style:{width:"100%",height:340}})}const ip=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Zs=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`},Yr={border:"1px solid var(--border-color)",borderRadius:8,padding:"6px 10px",background:"var(--bg-secondary)",color:"var(--text-primary)",cursor:"pointer"},op=({isPlaying:e,index:t,count:n,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:u,onVolume:h})=>{const{t:p}=Te();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[r.jsx("div",{}),r.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)"},children:[Zs(a)," / ",Zs(s)]})]}),r.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{onClick:o,disabled:t<=0,title:p("playerControls.prev","Prev"),"aria-label":p("playerControls.previousTrack","Previous track"),style:Yr,children:r.jsx(se.NtdSkipBack,{size:16})}),r.jsx("button",{onClick:c,title:e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),"aria-label":e?p("playerControls.pause","Pause"):p("playerControls.play","Play"),style:Yr,children:e?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsx("button",{onClick:l,disabled:t>=n-1,title:p("playerControls.next","Next"),"aria-label":p("playerControls.nextTrack","Next track"),style:Yr,children:r.jsx(se.NtdSkipForward,{size:16})})]}),r.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,"aria-label":p("playerControls.seekPosition","Seek position"),onChange:f=>u(parseFloat(f.target.value))}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx(se.NtdVolume,{size:16}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":p("playerControls.volume","Volume"),onChange:f=>h(parseFloat(f.target.value))})]})]})]})},el=d.memo(op);function lp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,f=n-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,f,l-2,h)}}function cp(e,t,n,a,s,i){if(!i.current){const p=[];for(let y=0;y<24;y++)p.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});i.current={nodes:p}}const o=i.current,l=t/2,c=n/2,u=26+a*80,h=[];for(const p of o.nodes){p.phase+=.02+a*.06;const f=p.baseR+Math.sin(p.phase)*u,y=l+Math.cos(p.ang)*f,m=c+Math.sin(p.ang)*f;h.push([y,m])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let p=0;p<h.length;p++){const[f,y]=h[p],[m,v]=h[(p+1)%h.length],x=(f+m)/2,g=(y+v)/2;p===0?e.moveTo(x,g):e.quadraticCurveTo(f,y,x,g)}e.closePath(),e.fill(),e.stroke()}function dp(e,t,n,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const u=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);u.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),u.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),u.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=u,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const up="var(--nice-text-muted, #94a3b8)",hp=({height:e,coverUrl:t,title:n,subtitle:a,label:s})=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:t?r.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:up},children:s??a??"—"})]})});function Xt(e,t){return e+Math.random()*(t-e)}function pp(e,t,n,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const u=6;for(let p=0;p<u;p++){const f=(p+.5)/u*t,y=(a[Math.floor((p+1)/(u+1)*a.length)]||0)/255,m=n*.18+(.25+s*.6+y*.7)*n*.55,v=e.createLinearGradient(f,n,f,n-m);v.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),v.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),v.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const x=Math.sin(l.t*1.2+p*.8)*(15+s*30);e.fillStyle=v,e.beginPath(),e.moveTo(f-20,n),e.bezierCurveTo(f-35,n-m*.45,f-25+x,n-m*.75,f+x,n-m),e.bezierCurveTo(f+25+x*.3,n-m*.65,f+35,n-m*.35,f+20,n),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let p=0;p<h;p++)l.embers.push({x:Xt(t*.25,t*.75),y:n-Xt(4,14),r:Xt(1,3),vx:Xt(-.15,.15),vy:-Xt(.6,1.8)-s*1.2,life:Xt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let p=l.embers.length-1;p>=0;p--){const f=l.embers[p];if(f.x+=f.vx,f.y+=f.vy,f.vy-=.01,f.life-=.015+s*.02,f.life<=0||f.y<-10){l.embers.splice(p,1);continue}const y=e.createRadialGradient(f.x,f.y,0,f.x,f.y,f.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(f.x,f.y,f.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,n-10,t*.6,6),l.t+=.02+s*.08}function fp(e,t,n,a,s){const i=t/2,o=n/2,l=Math.min(t,n)*.28,c=96,u=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const p=(a[h*u]??0)/255,f=h/c*Math.PI*2,y=p*(Math.min(t,n)*.22)+6,m=i+Math.cos(f)*l,v=o+Math.sin(f)*l,x=i+Math.cos(f)*(l+y),g=o+Math.sin(f)*(l+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+p*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(m,v),e.lineTo(x,g),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,o,l-8,0,Math.PI*2),e.fill()}function mp(e,t,n,a,s){const l=t/14,c=n/8;for(let u=0;u<8;u++)for(let h=0;h<14;h++){const p=Math.min(a.length-1,u*14+h),f=a[p]/255,y=(s+h/14*210+u/8*90)%360,m=65+f*30,v=20+f*40,x=(1-f)*4;e.fillStyle=`hsl(${y}, ${m}%, ${v}%)`,e.fillRect(h*l+x,u*c+x,Math.max(1,l-2*x),Math.max(1,c-2*x))}}function gp(e){const n=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(n)}async function yp(e,t,n,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await gp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=u=>l[u%Math.max(1,l.length)]??new Image;for(let u=0;u<n;u++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(u),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function bp(e,t,n,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const u=t/2,h=n/2,p=900,f=1+a*2;for(const m of c.sprites){m.ang+=m.spin*f,m.z-=m.vz*(.8+a*2.4),m.z<40&&(m.z=p);const v=Math.min(t,n)*.32+Math.sin(m.ang*.8)*18;m.x=Math.cos(m.ang)*v,m.y=Math.sin(m.ang*1.1)*v*.6}const y=[...c.sprites].sort((m,v)=>v.z-m.z);for(const m of y){const v=p/(p-m.z)*.6*m.size,x=u+m.x*v,g=h+m.y*v,k=64*v,b=64*v;e.save(),e.globalAlpha=.12+(1-m.z/p)*.2,e.fillStyle=`hsl(${(s+(1-m.z/p)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(x,g,k*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,x-k/2,g-b/2,k,b):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(x-k/2,g-b/2,k,b),e.restore())}}function Sn(e,t){return e+Math.random()*(t-e)}function xp(e,t,n,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(u,h)=>({x:Sn(t*.2,t*.8),y:Sn(n*.2,n*.8),r:Sn(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:Sn(-.6,.6),vy:Sn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>n-c.r&&(c.y=n-c.r,c.vy=-Math.abs(c.vy));const u=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${u}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(u+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${u}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle="var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function vp(e,t,n,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,n)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,u=n/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const p=Math.max(40,Math.min(h.r,Math.min(t,n)*.48));e.save(),e.translate(c,u),e.rotate(h.a),e.strokeStyle=`hsla(${(s+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let f=1;f<3;f++){const y=f*Math.PI*2/3;e.lineTo(Math.cos(y)*p,Math.sin(y)*p)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Sp(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.42;i.current+=.01;for(let h=0;h<c;h++){const p=(h+1)/(c+1),f=p*u;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(o,l,f,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*p|0),m=(a[y]??0)/255,v=6+h*2;for(let x=0;x<v;x++){const g=i.current*(1+h*.15)+x/v*Math.PI*2,k=f+Math.sin(g*2)*6*m,b=o+Math.cos(g)*k,S=l+Math.sin(g)*k;e.fillStyle=`hsla(${(s+h*30+x*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(b,S,2+m*4,0,Math.PI*2),e.fill()}}}function kp(e,t,n,a,s){const l=t/12,c=n/6;for(let u=0;u<6;u++)for(let h=0;h<12;h++){const p=(u*12+h)%a.length,f=a[p]/255,y=(s+h/12*180+u/6*90)%360,m=70+f*25,v=25+f*35;e.fillStyle=`hsl(${y}, ${m}%, ${v}%)`,e.fillRect(h*l,u*c,Math.ceil(l),Math.ceil(c))}}function wp(e,t,n,a,s,i){const o=t/2,l=n/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const p=Math.random()*Math.PI*2,f=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(p)*f,vy:Math.sin(p)*f,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const u=i.current;for(let h=u.length-1;h>=0;h--){const p=u[h];p.x+=p.vx,p.y+=p.vy,p.life+=1;const f=1-p.life/p.max;e.fillStyle=`hsla(${p.hue},85%,60%,${Math.max(0,f)})`,e.beginPath(),e.arc(p.x,p.y,2+f*3,0,Math.PI*2),e.fill(),(p.life>=p.max||p.x<-20||p.y<-20||p.x>t+20||p.y>n+20)&&u.splice(h,1)}u.length>1200&&u.splice(0,u.length-1200)}function jp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const o=t/2,l=n/2,c=Math.min(t,n)*(.38+s*.12),u=e.createRadialGradient(o,l,c*.1,o,l,c);u.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),u.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),u.addColorStop(1,"transparent"),e.fillStyle=u,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let p=0;p<h;p++){const f=p/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+p*1.7)+Math.cos(a*1.3+p*2.1))*.15,m=c*(.4+.55*Math.abs(Math.sin(a*1.2+p))),v=6;e.save(),e.translate(o,l),e.rotate(f+y),e.beginPath(),e.moveTo(0,0);for(let g=1;g<=v;g++){const k=m/v*g,b=(Math.sin(a*3+p*.8+g)*.6+Math.cos(a*2+p+g*.7))*(8+24*s),S=k,M=b;e.lineTo(M,S)}e.globalCompositeOperation="lighter";const x=(i+p*(240/h))%360;e.strokeStyle=`hsla(${x}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Cp(e,t,n,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=n/2,u=Math.min(t,n)*.22,h=Math.min(t,n)*.48;for(let p=0;p<96;p++){const f=a[p*o]/255,y=p/96*Math.PI*2,m=u,v=u+f*(h-u),x=l+Math.cos(y)*m,g=c+Math.sin(y)*m,k=l+Math.cos(y)*v,b=c+Math.sin(y)*v;e.strokeStyle=`hsl(${p/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(x,g),e.lineTo(k,b),e.stroke()}e.fillStyle="var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.beginPath(),e.arc(l,c,u*.85,0,Math.PI*2),e.fill()}function Mp(e,t,n,a,s,i){const o=t/2,l=n/2,c=Math.min(t,n)*.5,u=Xs(a,0,Math.floor(a.length*.1))/255,h=Xs(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const p=24;for(let f=0;f<p;f++){const y=i.current+f/p*Math.PI*2,m=(.35+u*.55)*c,v=o+Math.cos(y)*m,x=l+Math.sin(y)*m,g=e.createRadialGradient(o,l,0,o,l,m),k=f/p*360+s;g.addColorStop(0,`hsla(${k},85%,65%,0.0)`),g.addColorStop(1,`hsla(${k},85%,65%,0.9)`),e.strokeStyle=g,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(v,x),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function Xs(e,t,n){let a=0,s=0;for(let i=t;i<n;i++)a+=e[i],s++;return s?a/s:0}function Rp(e,t,n,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const o=n/2,l=Math.max(8,18-s*10),c=n*.35*(.6+s*.7),u=a.length,h=t/(u-1);e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,v=Math.sin(i*1.5+y*.03)*.12,x=y*h,g=o-l-(m+v)*c;y===0?e.moveTo(x,g):e.lineTo(x,g)}const p=e.createLinearGradient(0,0,0,o-l);p.addColorStop(0,"hsla(260,90%,75%,0.9)"),p.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<u;y++){const m=(a[y]-128)/128,v=Math.cos(i*1.3+y*.035)*.12,x=y*h,g=o+l+(m+v)*c;y===0?e.moveTo(x,g):e.lineTo(x,g)}const f=e.createLinearGradient(0,o+l,0,n);f.addColorStop(0,"hsla(190,90%,65%,0.9)"),f.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle="var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function Np(e,t,n,a,s,i){const o=t/2,l=n/2,c=5,u=Math.min(t,n)*.12;for(let h=0;h<c;h++){const p=Math.floor(h/c*a.length),f=a[p]/255,y=u+h*u*.55+f*u*.5,m=(i+h*40)%360;e.lineWidth=3+f*6,e.strokeStyle=`hsla(${m},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(o,l,y,0,Math.PI*2),e.stroke()}}function Tp(e,t,n,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const u=a[c*o]/255,h=u*(n-6),p=c*l,f=n-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+u*30)}%)`,e.fillRect(p+1,f,l-2,h)}}function $p(e,t,n,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*n,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Pp(e,t,n,a,s,i){const o=i.current,l=t/2,c=n/2,u=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=u,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*n,h.z=900,h.pz=h.z);const p=h.x/h.z*600,f=h.y/h.z*600,y=h.x/h.pz*600,m=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(s+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(y,m),e.lineTo(p,f),e.stroke()}e.restore()}function Ap(e,t,n,a){e.lineWidth=2,e.strokeStyle="var(--nice-primary-light, #c7d2fe)",e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=n/2+o*(n*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const Ep=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-text, #334155)"}`,background:e?"rgba(99,102,241,.12)":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-border, #e2e8f0)":"var(--nice-border, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),es=({modes:e=[],active:t,setActive:n,rows:a=2})=>{const s=Math.max(1,a);return!e||e.length===0?null:r.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:r.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${s}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(i=>r.jsx(Ep,{active:t===i,onClick:()=>n(i),title:`Tryb: ${i}`,children:i},i))})})};function Ip(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const Lp=({vu:e,hide:t})=>{if(t)return null;const n=12,a=Math.round(e*n);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((s,i)=>{const o=120*(i/n);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},Dp="var(--player-bg, #0f172a)";function _p(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function Fp(e,t){const n=e.length;for(let a=0;a<n;a++){const s=a/n*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const ts=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,imageUrls:p,imageCount:f=14,autoAnimate:y=!1})=>{const m=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),v=d.useMemo(()=>{const D=m.includes(c)?c:m[0];try{const W=localStorage.getItem(u);if(!W)return D;const j=JSON.parse(W);return m.includes(j)?j:D}catch{return D}},[m,c,u]),[x,g]=Ip(u,v),k=d.useRef(null),b=d.useRef(null),S=d.useRef(null),M=d.useRef(null),R=d.useRef(null),N=d.useRef(null),C=d.useRef(0),w=d.useRef(0),O=d.useRef([]),[$,E]=d.useState(0),_=d.useRef(null),L=d.useRef(null),U=d.useRef(null),Z=d.useRef(null),A=d.useRef(null),q=d.useRef(null),H=d.useRef(null),re=x!=="cover"&&x!=="video";return d.useEffect(()=>{var T;if(e==="youtube"||(b.current&&(cancelAnimationFrame(b.current),b.current=null),!re))return;Bt();const D=mn(),W=t.current;if(!W&&!y)return;if(W&&!S.current)try{S.current=D.createMediaElementSource(W)}catch{}if(W&&!M.current){const z=D.createAnalyser();z.fftSize=2048,z.smoothingTimeConstant=.85,M.current=z;try{(T=S.current)==null||T.connect(z)}catch{}try{z.connect(D.destination)}catch{}}const j=M.current;R.current=new Uint8Array(j?j.frequencyBinCount:1024),N.current=new Uint8Array(j?j.fftSize:2048);const F=()=>{const z=k.current,B=Math.max(1,Math.floor(window.devicePixelRatio||1));z.width=Math.floor(z.clientWidth*B),z.height=Math.floor(z.clientHeight*B);const G=z.getContext("2d");G==null||G.setTransform(1,0,0,1,0,0),G==null||G.scale(B,B)};F();const I=()=>F();window.addEventListener("resize",I),$p(U,220,k.current.width,k.current.height);const P=async()=>{const z=k.current;if(!z)return;const B=z.getContext("2d");if(!B)return;const G=Math.max(1,Math.floor(window.devicePixelRatio||1)),Y=z.width/G,X=z.height/G,ie=performance.now()*.001,le=x==="waveform"||x==="rift";j&&(le?j.getByteTimeDomainData(N.current):j.getByteFrequencyData(R.current)),y&&(_p(R.current,ie),Fp(N.current,ie));let te=0;const V=le?N.current:R.current;for(let K=0;K<V.length;K++){const oe=le?(V[K]-128)/128:V[K]/255;te+=oe*oe}if(te=Math.sqrt(te/V.length),E(Math.min(1,te)),B.clearRect(0,0,Y,X),x==="spectrum")Tp(B,Y,X,R.current,C.current);else if(x==="bars")lp(B,Y,X,R.current,C.current);else if(x==="waveform")Ap(B,Y,X,N.current);else if(x==="palette"){const K=(C.current+te*120)%360;kp(B,Y,X,R.current,K)}else if(x==="radial")Cp(B,Y,X,R.current,C.current);else if(x==="rays")Mp(B,Y,X,R.current,C.current,w);else if(x==="particles")wp(B,Y,X,te,C.current,O);else if(x==="rings")Np(B,Y,X,R.current,te,C.current);else if(x==="grid"){const K=(C.current+te*160)%360;mp(B,Y,X,R.current,K)}else if(x==="imageTornado"){const K=p!=null&&p.length?p:s?[s]:[];await yp(_,K,f,Y,X);const oe=(C.current+te*100)%360;bp(B,Y,X,te,oe,_)}else if(x==="colorRipples"){const K=(C.current+te*120)%360;dp(B,Y,X,te,K,L)}else if(x==="starfield"){const K=(C.current+60)%360;Pp(B,Y,X,te,K,U)}else if(x==="orbitals"){const K=(C.current+te*180)%360;Sp(B,Y,X,R.current,K,w)}else if(x==="eqcircle"){const K=(C.current+120)%360;fp(B,Y,X,R.current,K)}else if(x==="triangles"){const K=(C.current+40)%360;vp(B,Y,X,te,K,Z)}else if(x==="blob"){const K=(C.current+90)%360;cp(B,Y,X,te,K,A)}else if(x==="plasma"){const K=(C.current+te*200)%360;jp(B,Y,X,ie,te,K)}else if(x==="rift")Rp(B,Y,X,N.current,te,ie);else if(x==="lavaLamp"){const K=(C.current+te*80)%360;xp(B,Y,X,te,K,q)}else if(x==="cozyFire"){const K=(C.current+te*140)%360;pp(B,Y,X,R.current,te,K,H)}C.current=(C.current+.4)%360,b.current=requestAnimationFrame(P)};return b.current=requestAnimationFrame(P),()=>{window.removeEventListener("resize",I),b.current&&cancelAnimationFrame(b.current)}},[re,e,t,x,p,f,s,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:x==="cover"?"transparent":Dp},children:x==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:r.jsx(hp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):r.jsx("canvas",{ref:k,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx(es,{modes:m,active:x,setActive:g,rows:2}),r.jsx(Lp,{vu:$,hide:e==="youtube"})]})]})},tl=({height:e,autoPlay:t,track:n,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:u,extractVideoId:h})=>{d.useEffect(()=>{const m=i.current;if(m){if(m.volume=u,m.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&ip(a.url)){const v=()=>{m.src=a.url,m.load(),t&&m.play().catch(()=>{})};if(m.canPlayType("application/vnd.apple.mpegurl")){v();return}(async()=>{const g=(await import("hls.js")).default;if(g.isSupported()){const k=new g({xhrSetup:b=>{if(a!=null&&a.withCredentials&&(b.withCredentials=!0),a!=null&&a.headers)for(const[S,M]of Object.entries(a.headers))b.setRequestHeader(S,String(M))}});o.current=k,k.loadSource(a.url),k.attachMedia(m),k.on(g.Events.MANIFEST_PARSED,()=>t&&m.play().catch(()=>{}))}else v()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(m.src=a.url,m.load(),t&&m.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,u,t]);const p=(a==null?void 0:a.kind)==="youtube",f=p?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return r.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:p?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&r.jsx(Ma,{videoId:a.videoId??h(a.url),onReady:m=>{s.current=m.target,l(u),t&&m.target.playVideo()},onEnd:c,opts:{width:"100%",height:"100%",playerVars:{autoplay:t?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3}},style:{width:"100%",height:"100%"}}),((a==null?void 0:a.kind)==="audio"||(a==null?void 0:a.kind)==="hls")&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:n!=null&&n.coverUrl?r.jsx("img",{alt:"cover",src:n.coverUrl,style:{height:e-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[n==null?void 0:n.artist," — ",n==null?void 0:n.title]}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim()})]})}),r.jsx("audio",{ref:i,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:a!=null&&a.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),r.jsx(ts,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:f,storageKey:y},`vis-${y}`)]})};function zp(e,t){const[n,a]=d.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return d.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,a]}const Op="var(--text-dim, #94a3b8)",Bp=({active:e,onClick:t,title:n,children:a})=>r.jsx("button",{type:"button",onClick:t,title:n,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--accent, #6366f1)":"var(--border-muted, #334155)"}`,background:e?"var(--accent-muted, rgba(99,102,241,.12))":"var(--surface-overlay, rgba(15,23,42,.6))",color:e?"var(--text-on-accent, #e2e8f0)":"var(--text, #cbd5e1)",cursor:"pointer"},children:a}),nl=({kind:e,audioRef:t,width:n="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:u="gp-stage:mode",allowedModes:h,overlayOnly:p=!1})=>{const f=d.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),y=d.useMemo(()=>{const E=f.includes(c)?c:f[0];try{const _=localStorage.getItem(u);if(!_)return E;const L=JSON.parse(_);return f.includes(L)?L:E}catch{return E}},[f,c,u]),[m,v]=zp(u,y),x=d.useRef(null),[g,k]=d.useState(0),b=d.useRef(null),S=d.useRef(null),M=d.useRef(null),R=d.useRef(null),N=d.useRef(null),C=d.useRef(0),w=m==="spectrum"||m==="bars"||m==="waveform"||m==="palette";d.useEffect(()=>{var A;if(e==="youtube")return;if(!w){b.current&&cancelAnimationFrame(b.current);return}Bt();const E=mn(),_=t.current;if(!_)return;if(!S.current)try{S.current=E.createMediaElementSource(_)}catch{}if(!M.current){const q=E.createAnalyser();q.fftSize=2048,q.smoothingTimeConstant=.85,M.current=q;try{(A=S.current)==null||A.connect(q)}catch{}try{q.connect(E.destination)}catch{}}const L=M.current;R.current=new Uint8Array(L.frequencyBinCount),N.current=new Uint8Array(L.fftSize);const U=()=>{if(!x.current)return;const q=x.current,H=q.getContext("2d");if(!H)return;const re=q.width,D=q.height;H.clearRect(0,0,re,D),m==="waveform"?L.getByteTimeDomainData(N.current):L.getByteFrequencyData(R.current);let W=0;const j=m==="waveform"?N.current:R.current;for(let F=0;F<j.length;F++){const I=m==="waveform"?(j[F]-128)/128:j[F]/255;W+=I*I}if(W=Math.sqrt(W/j.length),k(Math.min(1,W)),m==="spectrum"||m==="bars"){const F=R.current,I=m==="bars"?48:Math.min(F.length,256),P=Math.floor(F.length/I),T=re/I;for(let z=0;z<I;z++){const B=F[z*P]/255,G=B*(D-6),Y=z*T,X=D-G,ie=z/I*240+C.current;H.fillStyle=`hsl(${ie%360}, 80%, ${Math.max(30,40+B*30)}%)`,H.fillRect(Y+1,X,T-2,G)}}else if(m==="waveform"){const F=N.current;H.lineWidth=2,H.strokeStyle="var(--nice-primary-light, #c7d2fe)",H.beginPath();const I=re/F.length;for(let P=0;P<F.length;P++){const T=(F[P]-128)/128,z=P*I,B=D/2+T*(D*.45);P===0?H.moveTo(z,B):H.lineTo(z,B)}H.stroke()}else if(m==="palette"){const P=re/12,T=D/6,z=(C.current+W*120)%360;for(let B=0;B<6;B++)for(let G=0;G<12;G++){const Y=(B*12+G)%R.current.length,X=R.current[Y]/255,ie=(z+G/12*180+B/6*90)%360,le=70+X*25,te=25+X*35;H.fillStyle=`hsl(${ie}, ${le}%, ${te}%)`,H.fillRect(G*P,B*T,Math.ceil(P),Math.ceil(T))}}H.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",b.current=requestAnimationFrame(U)},Z=()=>{var re;const q=x.current,H=Math.max(1,Math.floor(window.devicePixelRatio||1));q.width=Math.floor(q.clientWidth*H),q.height=Math.floor(q.clientHeight*H),(re=q.getContext("2d"))==null||re.scale(H,H)};return Z(),window.addEventListener("resize",Z),b.current=requestAnimationFrame(U),()=>{window.removeEventListener("resize",Z),b.current&&cancelAnimationFrame(b.current)}},[w,e,t,m]);const O=()=>{if(e==="youtube")return null;const E=12,_=Math.round(g*E);return r.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)"},children:Array.from({length:E}).map((L,U)=>{const Z=120*(U/E);return r.jsx("div",{style:{width:6,height:18,borderRadius:2,background:U<_?`hsl(${Z}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},U)})})},$=()=>r.jsx("div",{style:{textAlign:"center",color:"var(--nice-border, #e2e8f0)"},children:s?r.jsx("img",{alt:"cover",src:s,style:{height:a-24,objectFit:"contain"}}):r.jsxs("div",{style:{opacity:.8},children:[r.jsx("div",{style:{fontSize:18,fontWeight:600},children:i??""}),r.jsx("div",{style:{marginTop:8,fontSize:12,color:Op},children:l??o??""})]})});return r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:m==="cover"?r.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:$()}):r.jsx("canvas",{ref:x,style:{width:typeof n=="number"?`${n}px`:n,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),r.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px",borderRadius:10,border:"1px solid var(--nice-text, #334155)",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:f.map(E=>r.jsx(Bp,{active:m===E,onClick:()=>v(E),title:`Tryb: ${E}`,children:E},E))}),r.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:r.jsx(O,{})})]})]})},rl=({artist:e,title:t,hideControls:n=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=Te(),[l,c]=d.useState(e||""),[u,h]=d.useState(t||""),[p,f]=d.useState(null),[y,m]=d.useState(null),v=d.useRef(null),[x,g]=d.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});d.useEffect(()=>{e&&t&&i&&i(e,t).then(f)},[e,t,i]),d.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),d.useEffect(()=>{if(y&&s){const b=setInterval(()=>{const S=y.getCurrentTime();s(S)},100);return()=>clearInterval(b)}},[y,s]),d.useEffect(()=>{const b=()=>{if(v.current){const S=v.current.clientWidth,M=Math.round(S*(9/16));g({width:S,height:M})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const k=async()=>{if(!i)return;const b=await i(l,u);f(b)};return r.jsxs("div",{ref:v,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!p)&&r.jsxs("div",{children:[r.jsx("input",{value:l,onChange:b=>c(b.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),r.jsx("input",{value:u,onChange:b=>h(b.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),r.jsx("button",{onClick:k,children:o("youtubePlayer.search","Search")})]}),p&&r.jsxs("div",{children:[r.jsx(Ma,{videoId:p,opts:{width:x.width.toString(),height:x.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:b=>m(b.target)}),!n&&r.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[r.jsx("button",{onClick:()=>y==null?void 0:y.playVideo(),children:"? Play"}),r.jsx("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:"? Pause"})]})]})]})},Qs=e=>({name:e,dirs:new Map,files:[]}),Gp=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),Wp=e=>e.replace(/\\/g,"/"),Up=e=>{const t=Qs("/");for(const n of e){const a=Wp(n.path??n.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:n.file,path:a[0]??n.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,Qs(o)),s=s.dirs.get(o)}s.files.push({file:n.file,path:a[a.length-1]??n.file.name})}return t},pa=e=>e.slice().sort((t,n)=>(t.path??t.file.name).localeCompare(n.path??n.file.name)),qp={tidal:se.NtdWave,spotify:se.NtdMusic,youtube:se.NtdPlay},fa=({q:e,setQ:t,t:n})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceTextInput,{value:e,onChange:t,placeholder:n("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:r.jsx(se.NtdClose,{size:14})})]}),ma=({files:e,t,onOpenInEditor:n,onPlayFile:a})=>e.length?r.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),r.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),r.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return r.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[r.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),r.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),r.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[n&&r.jsxs(we.NiceButton,{variant:"outline",size:"sm",onClick:()=>n(s.file),children:[r.jsx(se.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[r.jsx(se.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):r.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),al=({streams:e,t,onPlayStream:n})=>e.length?r.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[r.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),r.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>r.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[r.jsxs("div",{style:{minWidth:0},children:[r.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),r.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[d.createElement(qp[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),n&&r.jsxs(we.NiceButton,{variant:"primary",size:"sm",onClick:()=>n(a),children:[r.jsx(se.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,Zr=({name:e,enabled:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[r.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),r.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),Vp=({variant:e="full",files:t=[],streams:n=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:u,id:h,accessMode:p,"data-testid":f})=>{const{t:y}=Te(),m=c??y,[v,x]=d.useState(""),g=d.useMemo(()=>Gp(t),[t]),k=d.useCallback(M=>{const R=v.trim().toLowerCase();return!R||M.toLowerCase().includes(R)},[v]),b=d.useMemo(()=>pa(g).filter(M=>k(`${M.path??M.file.name} ${M.file.type||""}`)),[g,k]),S=d.useMemo(()=>n.filter(M=>k(`${M.title} ${M.artist??""} ${M.provider}`)),[n,k]);return p==="hidden"?null:e==="minimal"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":f,children:[r.jsx(fa,{q:v,setQ:x,t:m}),r.jsx(ma,{files:b,t:m,onOpenInEditor:s,onPlayFile:i}),r.jsx(al,{streams:S,t:m,onPlayStream:o})]}):e==="onlyFiles"?r.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...u},id:h,"data-testid":f,children:[r.jsx(fa,{q:v,setQ:x,t:m}),r.jsx(ma,{files:b,t:m,onOpenInEditor:s,onPlayFile:i})]}):r.jsx(Hp,{q:v,setQ:x,normFiles:g,filteredStreams:S,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:u,id:h,"data-testid":f,t:m})},Hp=({q:e,setQ:t,normFiles:n,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:u,id:h,"data-testid":p,t:f})=>{const y=d.useMemo(()=>Up(n),[n]),[m,v]=d.useState({}),[x,g]=d.useState("/"),k=R=>v(N=>({...N,[R]:!N[R]})),b=(R,N)=>{const C=N==="/"?`/${R.name}`:`${N}${R.name}/`,w=N==="/"&&R.name==="/",O=m[C]??w,$=Array.from(R.dirs.keys()).sort();return r.jsxs("div",{children:[!w&&r.jsxs("button",{type:"button",onClick:()=>{k(C),g(C)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:x===C?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[r.jsx("span",{style:{display:"inline-flex"},children:O?r.jsx(se.NtdFolderOpen,{size:14}):r.jsx(se.NtdFolder,{size:14})}),r.jsx("span",{style:{fontSize:13},children:R.name})]}),(w||O)&&r.jsx("div",{style:{paddingLeft:w?0:16},children:$.map(E=>b(R.dirs.get(E),C))})]},C)},S=d.useMemo(()=>{let R;if(x==="/")R=pa(n);else{const N=x.replace(/^\//,"").split("/").filter(Boolean);let C=y;for(const w of N){const O=C.dirs.get(w);if(!O)return[];C=O}R=pa(C.files)}return e?R.filter(N=>(N.path??N.file.name).toLowerCase().includes(e.toLowerCase())):R},[x,y,n,e]),M={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return r.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...u},id:h,"data-testid":p,children:[r.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[r.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:f("libraryExplorer.library","Library")}),b(y,"/"),r.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[r.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:f("libraryExplorer.streaming","Streaming")}),r.jsx(Zr,{name:"Tidal",enabled:M.tidal}),r.jsx(Zr,{name:"Spotify",enabled:M.spotify}),r.jsx(Zr,{name:"YouTube",enabled:M.youtube})]})]}),r.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[r.jsx(fa,{q:e,setQ:t,t:f}),r.jsx(ma,{files:S,t:f,onOpenInEditor:i,onPlayFile:o}),(M.tidal||M.spotify||M.youtube)&&r.jsx(al,{streams:a.filter(R=>M[R.provider]),t:f,onPlayStream:l})]})]})},Kp=({kind:e,color:t})=>{const n={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return r.jsx("svg",{...n,children:r.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return r.jsx("svg",{...n,children:r.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},ns=({data:e,display:t,callbacks:n,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:u,sourcesAvailable:h=[]}=e,{allowVersion:p=!0,dragHandleProps:f}=t,{onChange:y,onRemove:m,onMoveUp:v,onMoveDown:x,onChangeLp:g,onSelectSource:k}=n,{readOnly:b=!1,canMoveUp:S=!0,canMoveDown:M=!0,activeSource:R}=a,{t:N}=Te(),C=d.useRef(null);d.useEffect(()=>{!o&&C.current&&C.current.focus()},[o]);const w=_=>{if(!b&&_.key==="Enter"){const L=_.target.closest("div.gpi-row"),U=L==null?void 0:L.querySelectorAll("input[data-role='field']");if(!U||U.length===0)return;const Z=Array.from(U).indexOf(_.target),A=U[Z+1]??U[0];A==null||A.focus()}},O=_=>{const L=h.includes(_),U=R===_,Z={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:U?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:L?1:.35,cursor:L&&k&&!b?"pointer":"default",transition:"transform .05s ease"},A=_==="youtube"?"var(--nice-danger, #ff0000)":_==="spotify"?"var(--nice-success, #1db954)":_==="tidal"?"var(--nice-text, #111827)":_==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",q=_==="youtube"?"YouTube":_==="spotify"?"Spotify":_==="tidal"?"TIDAL":_==="hls"?"HLS":"Audio",H=N("playlistItem.sourceLabel")+": "+q+(U?` ${N("playlistItem.sourceSelected")}`:""),re=()=>{!L||!k||b||k(_)};return r.jsx("button",{type:"button",title:q,onClick:re,disabled:!L||b,style:Z,"aria-pressed":U,"aria-label":H,children:r.jsx(Kp,{kind:_,color:A})},_)},$=["youtube","tidal","spotify","hls","audio"],E=typeof u=="number"?u:i+1;return r.jsxs("div",{className:"gpi-row",role:"group","aria-label":N("playlistItem.trackNumber")+" "+(i+1),style:{display:"grid",gridTemplateColumns:p?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"number",min:1,value:E,onChange:_=>g==null?void 0:g(Number(_.target.value)),disabled:b||!g,"aria-label":"Lp",title:N("playlistItem.positionOnList"),style:Yp}),r.jsx("input",{ref:C,"data-role":"field",type:"text",value:o,onChange:_=>y({artist:_.target.value}),placeholder:"Artist",onKeyDown:w,disabled:b,"aria-label":"Artist",className:"gpi-input",style:Xr}),r.jsx("input",{"data-role":"field",type:"text",value:l,onChange:_=>y({title:_.target.value}),placeholder:"Title",onKeyDown:w,disabled:b,"aria-label":"Title",className:"gpi-input",style:Xr}),p&&r.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:_=>y({version:_.target.value||void 0}),placeholder:N("playlistItem.versionOptional"),onKeyDown:w,disabled:b,"aria-label":"Version",className:"gpi-input",style:Xr}),r.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":N("playlistItem.availableSources"),children:$.map(O)}),r.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[f&&r.jsx("button",{type:"button",...f,draggable:!0,"aria-label":N("playlistItem.dragReorder"),title:N("playlistItem.dragReorder"),style:Jn,children:"≡"}),r.jsx("button",{type:"button",onClick:v,disabled:!S||b,"aria-label":N("playlistItem.moveUp"),title:N("playlistItem.moveUp"),style:Jn,children:"↑"}),r.jsx("button",{type:"button",onClick:x,disabled:!M||b,"aria-label":N("playlistItem.moveDown"),title:N("playlistItem.moveDown"),style:Jn,children:"↓"}),r.jsx("button",{type:"button",onClick:m,disabled:b,"aria-label":N("common.delete"),title:N("common.delete"),style:{...Jn,color:"var(--danger, #b91c1c)"},children:r.jsx(se.NtdClose,{size:14})})]})]})},Yp={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},Xr={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},Jn={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},ga=()=>Math.random().toString(36).slice(2,10),er=e=>(e??[]).map(t=>({id:ga(),...t})),Zp=e=>e.map(({id:t,...n})=>n),Xp=null,Qp=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-�]\s/);if(n.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=n[0].trim(),s=n.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},sl=({value:e,defaultValue:t,onChange:n,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=Xp,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:u=!0})=>{const{t:h}=Te(),p=e!==void 0,[f,y]=d.useState(()=>er(e||t)),[m,v]=d.useState(""),x=d.useRef(null),[g,k]=d.useState(null);d.useEffect(()=>{p&&y(er(e))},[p,JSON.stringify(e)]);const b=d.useCallback(H=>{n==null||n(Zp(H))},[n]),S=d.useCallback(H=>{if(p){const re=H(er(e));b(re)}else y(re=>{const D=H(re);return b(D),D})},[b,p,e]),M=s?f.length<s:!0,R=d.useCallback(()=>{!M||l||S(H=>[...H,{id:ga(),artist:"",title:"",version:void 0}])},[M,l,S]),N=d.useCallback((H,re)=>{S(D=>D.map(W=>W.id===H?{...W,...re}:W))},[S]),C=d.useCallback(H=>{l||S(re=>re.filter(D=>D.id!==H))},[l,S]),w=d.useCallback((H,re)=>{S(D=>{const W=D.findIndex(P=>P.id===H);if(W<0)return D;const j=W+re;if(j<0||j>=D.length)return D;const F=[...D],[I]=F.splice(W,1);return F.splice(j,0,I),F})},[S]),O=d.useCallback((H,re)=>{S(D=>{const W=D.findIndex(P=>P.id===H);if(W<0)return D;const j=Math.max(0,Math.min(D.length-1,re-1));if(W===j)return D;const F=[...D],[I]=F.splice(W,1);return F.splice(j,0,I),F})},[S]),$=H=>re=>{l||(x.current=H,re.dataTransfer.effectAllowed="move",re.dataTransfer.setData("text/plain",H))},E=H=>re=>{l||(re.preventDefault(),re.dataTransfer.dropEffect="move",k(H))},_=H=>()=>k(re=>re===H?null:re),L=H=>re=>{if(l)return;re.preventDefault();const D=x.current??re.dataTransfer.getData("text/plain");k(null),x.current=null,!(!D||D===H)&&S(W=>{const j=W.findIndex(T=>T.id===D),F=W.findIndex(T=>T.id===H);if(j<0||F<0||j===F)return W;const I=[...W],[P]=I.splice(j,1);return I.splice(F,0,P),I})},U=()=>{x.current=null,k(null)},Z=d.useCallback(()=>{if(!u||l)return;const re=m.split(/\r?\n/).map(D=>D.trim()).filter(Boolean).map(Qp).filter(D=>!!D);re.length!==0&&(S(D=>{const W=(s??1/0)-D.length,j=re.slice(0,Math.max(0,W)).map(F=>({id:ga(),...F}));return[...D,...j]}),v(""))},[u,l,m,s,S]);d.useEffect(()=>{},[f.length,c]);const A=o??r.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),q=i??h("genericPlaylist.addSong","Add song");return r.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[r.jsx("h3",{style:{margin:0,fontSize:16},children:h("genericPlaylist.playlist","Playlist")}),r.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:r.jsxs("button",{type:"button",onClick:R,disabled:!M||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":q,children:["+ ",q]})})]}),f.length===0?r.jsx("div",{className:"gp-empty",children:A}):r.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:f.map((H,re)=>{const D=g===H.id;return r.jsx("li",{draggable:!l,onDragStart:$(H.id),onDragOver:E(H.id),onDragLeave:_(H.id),onDrop:L(H.id),onDragEnd:U,style:{border:D?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:D?4:0},children:r.jsx(ns,{data:{id:H.id,index:re,lp:re+1,artist:H.artist,title:H.title,version:a?H.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:$(H.id)}},callbacks:{onChange:W=>N(H.id,W),onRemove:()=>C(H.id),onMoveUp:()=>w(H.id,-1),onMoveDown:()=>w(H.id,1),onChangeLp:W=>O(H.id,W)},state:{readOnly:l,canMoveUp:re>0,canMoveDown:re<f.length-1}})},H.id)})}),u&&!l&&r.jsx("div",{style:{marginTop:12},children:r.jsxs("details",{children:[r.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),r.jsxs("div",{style:{marginTop:6},children:[r.jsx("textarea",{value:m,onChange:H=>v(H.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
64
+ `}),n.jsxs("div",{ref:S,style:Q.container,children:[n.jsxs("div",{style:Q.header,children:[n.jsxs("h1",{style:{...Q.title,display:"inline-flex",alignItems:"center",gap:8},children:[n.jsx(W.NtdBarChart,{size:26})," ",g("vocalReport.title","Vocal Performance Report")]}),n.jsxs("p",{style:Q.subtitle,children:[w.songArtist," — ",w.songTitle,"  | ",g("vocalReport.difficulty","Difficulty"),": ",n.jsx("strong",{children:w.difficulty})," "," | ",new Date(w.timestamp).toLocaleString()]}),n.jsxs("div",{style:{marginTop:16,display:"flex",justifyContent:"center",alignItems:"center",gap:16},children:[n.jsx("div",{style:{width:72,height:72,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(135deg, ${yt(A)}44, ${yt(A)})`,border:`3px solid ${yt(A)}`,boxShadow:`0 0 20px ${yt(A)}44`},children:n.jsx("span",{style:{fontSize:28,fontWeight:900,color:"#fff"},children:T})}),n.jsxs("div",{style:{textAlign:"left"},children:[n.jsxs("div",{style:{fontSize:14,fontWeight:700,color:yt(A)},children:[g("vocalReport.overallGrade","Overall grade"),": ",A.toFixed(1),"%"]}),n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",maxWidth:360},children:O[T]??""})]})]})]}),n.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end",marginBottom:16,flexWrap:"wrap"},children:[n.jsxs("button",{style:Q.btnPrimary,onClick:j,children:[n.jsx(W.NtdDownload,{size:14})," ",g("vocalReport.downloadHtml","Download HTML")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:N,children:[n.jsx(W.NtdPrint,{size:14})," ",g("vocalReport.printPdf","Print / PDF")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:R,children:[n.jsx(W.NtdCode,{size:14})," ",g("vocalReport.exportJson","Export JSON")]}),n.jsxs("button",{style:Q.btnSecondary,onClick:d,children:[n.jsx(W.NtdClose,{size:14})," ",g("vocalReport.close","Close")]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.scoreOverview","Score overview")]}),n.jsxs("div",{style:Q.kpiGrid,children:[n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:w.totalScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.totalScore","Total score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:w.classicScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.classicScore","Classic score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsx("div",{style:Q.kpiValue,children:w.bonusScore.toLocaleString()}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.bonusScore","Bonus score")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:Q.kpiValue,children:[w.maxCombo,"×"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.maxCombo","Max combo")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:{...Q.kpiValue,color:yt(w.intonationAccuracyPct)},children:[w.intonationAccuracyPct,"%"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.intonationAccuracy","Intonation accuracy")})]}),n.jsxs("div",{style:Q.kpiCard,children:[n.jsxs("div",{style:{...Q.kpiValue,color:yt(w.perfectHitPct)},children:[w.perfectHitPct,"%"]}),n.jsx("div",{style:Q.kpiLabel,children:g("vocalReport.perfectHits","Perfect hits")})]})]}),k.length>1&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.playerComparison","Player comparison")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:"#"}),n.jsx("th",{style:Q.th,children:g("vocalReport.player","Player")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.classic","Classic")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.bonus","Bonus")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.total","Total")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.intonation","Intonation")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.perfect","Perfect")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.range","Range")})]})}),n.jsx("tbody",{children:k.map((_,U)=>n.jsxs("tr",{children:[n.jsx("td",{style:Q.td,children:U+1}),n.jsx("td",{style:{...Q.tdBold,color:_.playerColor},children:_.playerName}),n.jsx("td",{style:Q.tdRight,children:_.classicScore.toLocaleString()}),n.jsx("td",{style:Q.tdRight,children:_.bonusScore.toLocaleString()}),n.jsx("td",{style:{...Q.tdRight,fontWeight:700,color:"var(--nice-warning, #fbbf24)"},children:_.totalScore.toLocaleString()}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(yt(_.intonationAccuracyPct)),children:[_.intonationAccuracyPct,"%"]})}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(yt(_.perfectHitPct)),children:[_.perfectHitPct,"%"]})}),n.jsxs("td",{style:Q.tdRight,children:[_.lowestNote,"–",_.highestNote]})]},U))})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.pitchAccuracy","Pitch accuracy")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.metric","Metric")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),n.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.meanAbsDev","Mean abs. deviation")}),n.jsxs("td",{style:Q.tdRight,children:[w.avgCentDeviation,n.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.meanAbsDevDesc","Average distance from the target pitch.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.medianDev","Median deviation")}),n.jsxs("td",{style:Q.tdRight,children:[w.medianCentDeviation,n.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.medianDevDesc","Typical deviation, robust to outliers.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.stdDev","Std. deviation")}),n.jsxs("td",{style:Q.tdRight,children:[w.stdDevCents,n.jsxs("span",{style:Q.kpiUnit,children:[" ",re]})]}),n.jsx("td",{style:Q.td,children:g("vocalReport.stdDevDesc","Consistency of pitch (lower = steadier).")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.intonationAccuracyLabel","Intonation accuracy")}),n.jsxs("td",{style:{...Q.tdRight,color:yt(w.intonationAccuracyPct)},children:[w.intonationAccuracyPct,"%"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.intonationAccuracyDesc","Share of frames within tolerance.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.perfectHitRate","Perfect-hit rate")}),n.jsxs("td",{style:{...Q.tdRight,color:yt(w.perfectHitPct)},children:[w.perfectHitPct,"%"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.perfectHitRateDesc","Notes hit dead-on.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalPitchSamples","Total pitch samples")}),n.jsx("td",{style:Q.tdRight,children:w.totalPitchPoints.toLocaleString()}),n.jsx("td",{style:Q.td,children:g("vocalReport.totalPitchSamplesDesc","Number of analysed pitch frames.")})]})]})]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.deviationDistribution","Deviation distribution")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:220,children:n.jsxs($e.BarChart,{data:w.pitchDeviationHistogram,margin:{top:5,right:20,bottom:5,left:20},children:[n.jsx($e.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),n.jsx($e.XAxis,{dataKey:"centRange",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:10},angle:-25,textAnchor:"end",height:50}),n.jsx($e.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),n.jsx($e.Bar,{dataKey:"count",name:g("vocalReport.samples","Samples"),radius:[4,4,0,0],children:w.pitchDeviationHistogram.map((_,U)=>n.jsx($e.Cell,{fill:_.centRange.includes("−15 to 0")||_.centRange.includes("0 to +15")?"var(--nice-success, #22c55e)":_.centRange.includes("25")?"var(--nice-warning, #eab308)":"var(--nice-danger, #ef4444)"},U))})]})})]}),n.jsxs("div",{style:Q.row,children:[n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.hitClassification","Hit classification")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:220,children:n.jsxs($e.PieChart,{children:[n.jsx($e.Pie,{data:ee,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:_,value:U})=>`${_}: ${Number(U).toFixed(1)}%`,labelLine:{stroke:"var(--nice-text-muted, #64748b)"},stroke:"var(--nice-bg, #0f172a)",strokeWidth:2,children:ee.map((_,U)=>n.jsx($e.Cell,{fill:_.fill},U))}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}})]})})]}),n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.performanceProfile","Performance profile")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:220,children:n.jsxs($e.RadarChart,{data:V,cx:"50%",cy:"50%",outerRadius:75,children:[n.jsx($e.PolarGrid,{stroke:"var(--nice-border, #334155)"}),n.jsx($e.PolarAngleAxis,{dataKey:"metric",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Radar,{name:"Score",dataKey:"value",stroke:"var(--nice-info, #3b82f6)",fill:"var(--nice-info, #3b82f6)",fillOpacity:.3,strokeWidth:2})]})})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.pitchTracking","Pitch tracking")]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.sungVsExpected","Sung vs expected")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:260,children:n.jsxs($e.LineChart,{data:K,margin:{top:5,right:20,bottom:5,left:20},children:[n.jsx($e.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),n.jsx($e.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:_=>`${_.toFixed(0)}s`}),n.jsx($e.YAxis,{domain:["auto","auto"],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),n.jsx($e.Legend,{wrapperStyle:{color:"var(--nice-text-muted, #94a3b8)",fontSize:12}}),n.jsx($e.Line,{type:"monotone",dataKey:"expected",name:g("vocalReport.expected","Expected"),stroke:"var(--nice-success, #22c55e)",dot:!1,strokeWidth:2,strokeOpacity:.6}),n.jsx($e.Line,{type:"monotone",dataKey:"sung",name:g("vocalReport.sung","Sung"),stroke:"var(--nice-info, #3b82f6)",dot:!1,strokeWidth:1.5})]})})]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.rollingAccuracy","Rolling accuracy")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:180,children:n.jsxs($e.AreaChart,{data:w.accuracyOverTime,margin:{top:5,right:20,bottom:5,left:20},children:[n.jsx($e.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),n.jsx($e.XAxis,{dataKey:"t",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11},tickFormatter:_=>`${_.toFixed(0)}s`}),n.jsx($e.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),n.jsx($e.Area,{type:"monotone",dataKey:"accuracy",stroke:"var(--nice-accent, #8b5cf6)",fill:"var(--nice-accent, #8b5cf6)",fillOpacity:.2,strokeWidth:2})]})})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.vocalRange","Vocal range")]}),n.jsxs("div",{style:Q.row,children:[n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.lowestNote","Lowest note")}),n.jsxs("td",{style:Q.tdRight,children:[w.lowestNote," (",w.lowestHz," Hz)"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.highestNote","Highest note")}),n.jsxs("td",{style:Q.tdRight,children:[w.highestNote," (",w.highestHz," Hz)"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rangeLabel","Range")}),n.jsxs("td",{style:Q.tdRight,children:[w.rangeInSemitones," ",g("vocalReport.semitones","semitones")]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.tessitura","Tessitura")}),n.jsxs("td",{style:Q.tdRight,children:[w.tessituraLow," — ",w.tessituraHigh]})]})]})})}),n.jsxs("div",{style:{...Q.chartWrap,...Q.half},children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.chromagram","Chromagram")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:180,children:n.jsxs($e.BarChart,{data:z,margin:{top:5,right:10,bottom:5,left:10},children:[n.jsx($e.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),n.jsx($e.XAxis,{dataKey:"note",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.YAxis,{tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),n.jsx($e.Bar,{dataKey:"pct",name:g("vocalReport.usagePct","Usage %"),radius:[4,4,0,0],fill:"var(--nice-primary, #6366f1)"})]})})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.vibratoStability","Vibrato & stability")]}),n.jsxs("div",{style:Q.row,children:[n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.vibratoDetected","Vibrato detected")}),n.jsx("td",{style:Q.tdRight,children:n.jsx("span",{style:Q.badge(w.vibrato.detected?"var(--nice-success, #22c55e)":"var(--nice-text-muted, #64748b)"),children:w.vibrato.detected?g("vocalReport.yes","Yes"):g("vocalReport.no","No")})})]}),w.vibrato.detected&&n.jsxs(n.Fragment,{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgRate","Avg. rate")}),n.jsxs("td",{style:Q.tdRight,children:[w.vibrato.avgRateHz," Hz"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgExtent","Avg. extent")}),n.jsxs("td",{style:Q.tdRight,children:["±",w.vibrato.avgExtentCents," ",re]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.regularity","Regularity")}),n.jsxs("td",{style:Q.tdRight,children:[w.vibrato.regularityPct,"%"]})]})]})]})})}),n.jsx("div",{style:Q.half,children:n.jsx("table",{style:Q.table,children:n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.jitter","Jitter")}),n.jsxs("td",{style:Q.tdRight,children:[w.jitterPct,"%"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.vocalPresence","Vocal presence")}),n.jsxs("td",{style:Q.tdRight,children:[w.shimmerProxy,"%"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.avgOnsetDev","Avg. onset deviation")}),n.jsxs("td",{style:Q.tdRight,children:[w.avgOnsetDeviationMs," ms"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rhythmStability","Rhythm stability")}),n.jsx("td",{style:Q.tdRight,children:n.jsxs("span",{style:Q.badge(yt(w.rhythmStabilityPct)),children:[w.rhythmStabilityPct,"%"]})})]})]})})})]}),w.verseMetrics.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.verseBreakdown","Per-verse breakdown")]}),n.jsxs("div",{style:Q.chartWrap,children:[n.jsx("div",{style:Q.chartTitle,children:g("vocalReport.accuracyByVerse","Accuracy by verse")}),n.jsx($e.ResponsiveContainer,{width:"100%",height:200,children:n.jsxs($e.BarChart,{data:q,margin:{top:5,right:20,bottom:5,left:20},children:[n.jsx($e.CartesianGrid,{strokeDasharray:"3 3",stroke:"var(--nice-border, #334155)"}),n.jsx($e.XAxis,{dataKey:"verse",tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.YAxis,{domain:[0,100],tick:{fill:"var(--nice-text-muted, #94a3b8)",fontSize:11}}),n.jsx($e.Tooltip,{contentStyle:{background:"var(--nice-bg-secondary, #1e293b)",border:"1px solid var(--nice-border, #334155)",borderRadius:8,color:"var(--nice-text, #e2e8f0)"}}),n.jsx($e.Bar,{dataKey:"accuracy",name:g("vocalReport.hitPct","Hit %"),radius:[4,4,0,0],children:q.map((_,U)=>n.jsx($e.Cell,{fill:Ks(_.label)},U))})]})})]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.verse","Verse")}),n.jsx("th",{style:Q.th,children:g("vocalReport.rating","Rating")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.hitPct","Hit %")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.avgDeviation","Avg. dev.")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.notes","Notes")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.notesHit","Hit")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.comboBonus","Combo bonus")})]})}),n.jsx("tbody",{children:w.verseMetrics.map((_,U)=>n.jsxs("tr",{children:[n.jsxs("td",{style:Q.td,children:[g("vocalReport.verse","Verse")," ",_.verseIndex+1]}),n.jsx("td",{style:Q.td,children:n.jsx("span",{style:Q.badge(Ks(_.label)),children:_.label})}),n.jsxs("td",{style:Q.tdRight,children:[(_.hitFraction*100).toFixed(1),"%"]}),n.jsxs("td",{style:Q.tdRight,children:[_.avgCentDeviation," ¢"]}),n.jsx("td",{style:Q.tdRight,children:_.noteCount}),n.jsx("td",{style:Q.tdRight,children:_.notesHit}),n.jsxs("td",{style:Q.tdRight,children:["+",_.comboBonus]})]},U))})]})]}),n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.scoringConfig","Scoring configuration")]}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.parameter","Parameter")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")}),n.jsx("th",{style:Q.th,children:g("vocalReport.description","Description")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyLevel","Difficulty level")}),n.jsx("td",{style:Q.tdRight,children:w.difficulty}),n.jsx("td",{style:Q.td,children:g("vocalReport.difficultyLevelDesc","Affects tolerance and multiplier.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.semitoneTolerance","Semitone tolerance")}),n.jsx("td",{style:Q.tdRight,children:I.semitoneTolerance}),n.jsx("td",{style:Q.td,children:g("vocalReport.semitoneToleranceDesc","Pitch window counted as a hit.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.preWindow","Pre window")}),n.jsxs("td",{style:Q.tdRight,children:[I.preWindow," s"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.preWindowDesc","Lead-in time before a note.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.postExtra","Post extra")}),n.jsxs("td",{style:Q.tdRight,children:[I.postExtra," s"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.postExtraDesc","Grace time after a note.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.difficultyMultiplier","Difficulty multiplier")}),n.jsxs("td",{style:Q.tdRight,children:[I.difficultyMult,"×"]}),n.jsx("td",{style:Q.td,children:g("vocalReport.difficultyMultiplierDesc","Score scaling for difficulty.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.songBpm","Song BPM")}),n.jsx("td",{style:Q.tdRight,children:w.songBpm}),n.jsx("td",{style:Q.td,children:g("vocalReport.songBpmDesc","Tempo used for note timing.")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.totalNotes","Total notes")}),n.jsx("td",{style:Q.tdRight,children:M}),n.jsx("td",{style:Q.td,children:g("vocalReport.totalNotesDesc","Number of scored notes in the song.")})]})]})]}),k.some(_=>_.micSettings)&&n.jsxs(n.Fragment,{children:[n.jsxs("h2",{style:Q.sectionTitle,children:[++E,". ",g("vocalReport.micConfig","Microphone configuration")]}),k.map((_,U)=>_.micSettings&&n.jsxs("div",{style:{marginBottom:16},children:[k.length>1&&n.jsx("h4",{style:{color:_.playerColor,margin:"0 0 8px",fontSize:14},children:_.playerName}),n.jsxs("table",{style:Q.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{style:Q.th,children:g("vocalReport.setting","Setting")}),n.jsx("th",{style:Q.thRight,children:g("vocalReport.value","Value")})]})}),n.jsxs("tbody",{children:[n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.device","Device")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.deviceLabel||_.micSettings.deviceId})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchAlgorithm","Pitch algorithm")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.algorithm})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.inputGain","Input gain")}),n.jsxs("td",{style:Q.tdRight,children:[_.micSettings.gain,"×"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.rmsThreshold","RMS threshold")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.rmsThreshold})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.pitchThreshold","Pitch threshold")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.pitchThreshold})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.smoothingWindow","Smoothing window")}),n.jsxs("td",{style:Q.tdRight,children:[_.micSettings.smoothingWindow," ",g("vocalReport.frames","frames")]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.hysteresisFrames","Hysteresis frames")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.hysteresisFrames})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.hanningWindow","Hanning window")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.useHanning?g("vocalReport.enabled","Enabled"):g("vocalReport.disabled","Disabled")})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.latencyOffset","Latency offset")}),n.jsxs("td",{style:Q.tdRight,children:[_.micSettings.latencyOffsetMs," ms"]})]}),n.jsxs("tr",{children:[n.jsx("td",{style:Q.tdBold,children:g("vocalReport.monitor","Monitor")}),n.jsx("td",{style:Q.tdRight,children:_.micSettings.monitorEnabled?`${g("vocalReport.on","On")} (${Math.round(_.micSettings.monitorVolume*100)}%)`:g("vocalReport.off","Off")})]})]})]})]},U))]}),n.jsx("div",{style:Q.footer,children:n.jsxs("p",{children:[g("vocalReport.footerGenerated","Report generated")," ·"," ",w.timestamp.replace(/[-:T.Z]/g,"").slice(0,14)]})})]})]})},Vh="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23334155'/%3E%3Ccircle cx='42' cy='64' r='8' fill='%2394a3b8'/%3E%3Crect x='48' y='34' width='3' height='32' fill='%2394a3b8'/%3E%3C/svg%3E";function Hh(e){if(!e)return"";const t=Math.floor(e/60),r=Math.round(e%60);return`${t}:${r.toString().padStart(2,"0")}`}function Ys(e){return Array.from(new Set(e.filter(t=>!!t))).sort((t,r)=>t.localeCompare(r))}const qo=u.memo(({song:e,index:t,active:r,coverUrl:a,topScore:s,selected:i,multiSelect:o,disabled:l,t:c,onPlay:d,onToggleSelect:h,onFocusRow:f})=>{const p=()=>{o?h(e.id):l||d==null||d(e)};return n.jsxs("div",{className:`nice-ksb-row${i?" nice-ksb-row--selected":""}${r?" nice-ksb-row--active":""}`,role:"option","aria-selected":i,"data-ksb-index":t,tabIndex:r?0:-1,onClick:p,onFocus:()=>f(t),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p())},children:[o&&n.jsx("input",{type:"checkbox",className:"nice-ksb-row__check",checked:i,onChange:()=>h(e.id),onClick:y=>y.stopPropagation(),"aria-label":e.title}),n.jsx("img",{className:"nice-ksb-row__cover",src:a,alt:"",loading:"lazy"}),n.jsxs("div",{className:"nice-ksb-row__main",children:[n.jsx("div",{className:"nice-ksb-row__title",children:e.title}),n.jsx("div",{className:"nice-ksb-row__artist",children:e.artist||"—"})]}),n.jsxs("div",{className:"nice-ksb-row__meta",children:[e.genre&&n.jsx("span",{className:"nice-ksb-badge",children:e.genre}),e.year&&n.jsx("span",{className:"nice-ksb-badge",children:e.year}),e.durationSec?n.jsx("span",{className:"nice-ksb-badge",children:Hh(e.durationSec)}):null,e.externalSource&&n.jsx("span",{className:"nice-ksb-badge nice-ksb-badge--src",children:e.externalSource}),s&&n.jsxs("span",{className:"nice-ksb-badge nice-ksb-badge--score",title:s.playerName,children:[n.jsx(W.NtdTrophy,{size:11})," ",s.score.toLocaleString()]})]}),!o&&n.jsxs("button",{type:"button",className:"nice-ksb-row__play",disabled:l,onClick:y=>{y.stopPropagation(),d==null||d(e)},children:[n.jsx(W.NtdPlay,{size:13})," ",c("karaokeBrowser.play","Play")]})]})});qo.displayName="NiceKaraokeSongRow";const Kh=({songs:e,fetchSongs:t,loading:r=!1,getCover:a,getTopScore:s,onPlay:i,onSelect:o,multiSelect:l=!1,maxSelections:c=0,showSidebar:d=!0,enableGamepad:h=!0,disabled:f=!1,disabledReason:p,t:y,className:m,style:x,id:v,accessMode:g,"data-testid":S})=>{const{t:b}=Te(),k=y??b,[j,N]=u.useState(""),[R,w]=u.useState(""),[M,I]=u.useState(""),[A,T]=u.useState(""),[O,E]=u.useState("artist"),[V,ee]=u.useState("asc"),[z,q]=u.useState({type:"all"}),[K,re]=u.useState(new Set),[_,U]=u.useState([]),[$,P]=u.useState(!1);u.useEffect(()=>{const ce=setTimeout(()=>w(j),300);return()=>clearTimeout(ce)},[j]),u.useEffect(()=>{if(e||!t)return;let ce=!1;return P(!0),Promise.resolve(t({searchQuery:R.trim()||void 0,genres:M?[M]:void 0,languages:A?[A]:void 0})).then(ye=>!ce&&U(ye)).catch(()=>!ce&&U([])).finally(()=>!ce&&P(!1)),()=>{ce=!0}},[e,t,R,M,A]);const F=e??_,D=u.useMemo(()=>Ys(F.map(ce=>ce.genre)),[F]),C=u.useMemo(()=>Ys(F.map(ce=>ce.language)),[F]),L=u.useMemo(()=>{let ce=F;const ye=R.trim().toLowerCase();ye&&(ce=ce.filter(ie=>`${ie.title} ${ie.artist}`.toLowerCase().includes(ye))),M&&(ce=ce.filter(ie=>ie.genre===M)),A&&(ce=ce.filter(ie=>ie.language===A)),z.type==="genre"&&(ce=ce.filter(ie=>ie.genre===z.value)),z.type==="language"&&(ce=ce.filter(ie=>ie.language===z.value));const ke=V==="asc"?1:-1;return[...ce].sort((ie,he)=>{const Le=ie[O]??"",Oe=he[O]??"";return typeof Le=="number"&&typeof Oe=="number"?(Le-Oe)*ke:String(Le).localeCompare(String(Oe))*ke})},[F,R,M,A,z,O,V]),B=ce=>{re(ye=>{const ke=new Set(ye);return ke.has(ce)?ke.delete(ce):(c===0||ke.size<c)&&ke.add(ce),ke})},G=()=>{const ce=F.filter(ye=>K.has(ye.id));o==null||o({songs:ce})},H=r||$,X=ce=>{ce===O?ee(ye=>ye==="asc"?"desc":"asc"):(E(ce),ee("asc"))},oe=u.useRef(null),[le,ne]=u.useState(0),Z=u.useRef(0),Y=u.useRef(L);Y.current=L,u.useEffect(()=>{ne(ce=>{const ye=Math.min(Math.max(0,ce),Math.max(0,L.length-1));return Z.current=ye,ye})},[L.length]);const se=u.useCallback(ce=>{var ke;const ye=(ke=oe.current)==null?void 0:ke.querySelector(`[data-ksb-index="${ce}"]`);ye==null||ye.focus(),ye==null||ye.scrollIntoView({block:"nearest"})},[]),ae=u.useCallback(ce=>{Z.current=ce,ne(ce)},[]),ue=u.useCallback((ce,ye=!0)=>{const ke=Y.current.length;if(ke===0)return;const ie=Math.min(ke-1,Math.max(0,ce));Z.current=ie,ne(ie),ye&&requestAnimationFrame(()=>se(ie))},[se]),J=u.useCallback(ce=>ue(Z.current+ce),[ue]),de=ce=>{const ye=Y.current[ce];ye&&(l?B(ye.id):f||i==null||i(ye))},me=ce=>{switch(ce.key){case"ArrowDown":ce.preventDefault(),J(1);break;case"ArrowUp":ce.preventDefault(),J(-1);break;case"Home":ce.preventDefault(),ue(0);break;case"End":ce.preventDefault(),ue(Y.current.length-1);break;case"PageDown":ce.preventDefault(),J(5);break;case"PageUp":ce.preventDefault(),J(-5);break}},ve=Se.useGamepad({enabled:h,actions:{navUp:{button:"DpadUp",onPress:()=>J(-1),repeatDelay:350,repeatRate:110},navDown:{button:"DpadDown",onPress:()=>J(1),repeatDelay:350,repeatRate:110},stickUp:{axis:"LeftY",axisDirection:"negative",onPress:()=>J(-1),repeatDelay:350,repeatRate:130},stickDown:{axis:"LeftY",axisDirection:"positive",onPress:()=>J(1),repeatDelay:350,repeatRate:130},select:{button:"A",onPress:()=>de(Z.current)},confirm:{button:"Start",onPress:()=>{l&&G()}}}});return g==="hidden"?null:n.jsxs("div",{className:`nice-ksb${m?` ${m}`:""}`,style:x,id:v,"data-testid":S,children:[d&&n.jsxs("aside",{className:"nice-ksb__sidebar",children:[n.jsxs("button",{type:"button",className:`nice-ksb__node${z.type==="all"?" nice-ksb__node--active":""}`,onClick:()=>q({type:"all"}),children:[n.jsx(W.NtdMusic,{size:14})," ",k("karaokeBrowser.allSongs","All songs")," (",F.length,")"]}),D.length>0&&n.jsxs("div",{className:"nice-ksb__facet",children:[n.jsx("div",{className:"nice-ksb__facet-title",children:k("karaokeBrowser.genres","Genres")}),D.map(ce=>n.jsx("button",{type:"button",className:`nice-ksb__node${z.type==="genre"&&z.value===ce?" nice-ksb__node--active":""}`,onClick:()=>q({type:"genre",value:ce}),children:ce},ce))]}),C.length>0&&n.jsxs("div",{className:"nice-ksb__facet",children:[n.jsx("div",{className:"nice-ksb__facet-title",children:k("karaokeBrowser.languages","Languages")}),C.map(ce=>n.jsx("button",{type:"button",className:`nice-ksb__node${z.type==="language"&&z.value===ce?" nice-ksb__node--active":""}`,onClick:()=>q({type:"language",value:ce}),children:ce},ce))]})]}),n.jsxs("div",{className:"nice-ksb__main",children:[n.jsxs("div",{className:"nice-ksb__toolbar",children:[n.jsx("input",{className:"nice-ksb__search",type:"search",value:j,placeholder:k("karaokeBrowser.search","Search title or artist…"),onChange:ce=>N(ce.target.value)}),n.jsx("div",{className:"nice-ksb__sort",children:["artist","title","year","genre"].map(ce=>n.jsxs("button",{type:"button",className:`nice-ksb__sort-btn${O===ce?" nice-ksb__sort-btn--active":""}`,onClick:()=>X(ce),children:[k(`karaokeBrowser.sort.${ce}`,ce),O===ce&&(V==="asc"?n.jsx(W.NtdChevronUp,{size:12}):n.jsx(W.NtdChevronDown,{size:12}))]},ce))}),n.jsxs("span",{className:`nice-ksb__navhint${ve.connected?" nice-ksb__navhint--pad":""}`,title:k("karaokeBrowser.navHint","Navigate with ↑ ↓ or the D-pad · Enter / A to play"),children:[ve.connected?n.jsx(W.NtdGamepad,{size:14}):n.jsx(W.NtdMove,{size:14}),n.jsx("span",{className:"nice-ksb__navhint-keys",children:ve.connected?"D-pad · A":"↑ ↓ · Enter"})]})]}),f&&p&&n.jsx("div",{className:"nice-ksb__disabled",children:p}),n.jsx("div",{className:"nice-ksb__list",role:"listbox","aria-multiselectable":l,"aria-label":k("karaokeBrowser.songs","Songs"),ref:oe,onKeyDown:me,children:H?n.jsx("div",{className:"nice-ksb__empty",children:k("karaokeBrowser.loading","Loading…")}):L.length===0?n.jsx("div",{className:"nice-ksb__empty",children:k("karaokeBrowser.noResults","No songs found")}):L.map((ce,ye)=>n.jsx(qo,{song:ce,index:ye,active:ye===le,coverUrl:(a==null?void 0:a(ce))||ce.coverImage||ce.externalCoverUrl||ce.coverPath||Vh,topScore:s==null?void 0:s(ce),selected:K.has(ce.id),multiSelect:l,disabled:f,t:k,onPlay:i,onToggleSelect:B,onFocusRow:ae},ce.id))}),l&&n.jsxs("div",{className:"nice-ksb__footer",children:[n.jsxs("span",{children:[K.size,c>0?` / ${c}`:""," ",k("karaokeBrowser.selected","selected")]}),n.jsx("button",{type:"button",className:"nice-ksb__confirm",disabled:K.size===0,onClick:G,children:k("karaokeBrowser.confirm","Add selected")})]})]})]})};function Vo(e,t,r=50,a=30){const s=Math.round(e/1e3*t),i=Math.round(r/1e3*t),o=Math.max(1,Math.round(a/1e3*t)),l=new Float32Array(s);for(let c=0;c<o;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(o-1))),h=i+c-Math.floor(o/2);h>=0&&h<s&&(l[h]=d)}return l}function Xs(e,t,r=1e3){const a=Math.max(1,Math.round(t/r)),s=Math.ceil(e.length/a),i=new Float32Array(s);for(let l=0;l<s;l++){const c=l*a,d=Math.min(e.length,c+a);let h=0;for(let f=c;f<d;f++)h+=Math.abs(e[f]);i[l]=h/(d-c||1)}let o=0;for(let l=0;l<i.length;l++)i[l]>o&&(o=i[l]);if(o>0)for(let l=0;l<i.length;l++)i[l]=i[l]/o;return{env:i,factor:a}}function Yh(e,t){const r=e.length,a=t.length;if(r===0||a===0)return 0;let s={lag:0,score:-1/0};const i=Math.min(2e3,a);for(let o=-i;o<=i;o++){let l=0,c=0,d=0;for(let p=0;p<r;p++){const y=p+o+Math.floor((a-r)/2);if(y<0||y>=a)continue;const m=e[p],x=t[y];l+=m*x,c+=m*m,d+=x*x}const h=Math.sqrt(Math.max(1e-9,c*d)),f=l/h;f>s.score&&(s={lag:o,score:f})}return s.lag}function Ho(e,t,r=50,a=30){try{const s=Math.max(300,Math.round(e.length/t*1e3)),i=Vo(s,t,r,a),o=Xs(e,t,1e3),l=Xs(i,t,1e3),d=Yh(l.env,o.env)*1e3/1e3;return Math.round(d)}catch{return null}}const Xh=({deviceId:e,initialOffsetMs:t=null,onSave:r,onClose:a,rounds:s=3,t:i,className:o,style:l,id:c,accessMode:d,"data-testid":h})=>{const{t:f}=Te(),p=i??f,[y,m]=u.useState(null),[x,v]=u.useState(t),[g,S]=u.useState(!1),[b,k]=u.useState([]),[j,N]=u.useState(0),[R,w]=u.useState(!1),M=u.useRef(!1);u.useEffect(()=>{v(t??null)},[t,e]);const I=async()=>{const E=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),V=new AudioContext,ee=V.sampleRate,z=V.createMediaStreamSource(E),q=V.createScriptProcessor(2048,1,1);z.connect(q),q.connect(V.destination);const K=1200,re=Math.round(K/1e3*ee),_=new Float32Array(re);let U=0,$=!1;q.onaudioprocess=B=>{if($)return;const G=B.inputBuffer.getChannelData(0),H=Math.min(G.length,re-U);H>0&&(_.set(G.subarray(0,H),U),U+=H),U>=re&&($=!0)},await new Promise(B=>setTimeout(B,80));const P=new AudioContext,F=P.createOscillator(),D=P.createGain();F.type="sine",F.frequency.value=1e3,D.gain.value=1e-4,F.connect(D),D.connect(P.destination);const C=P.currentTime+.05;D.gain.setValueAtTime(1e-4,C-.01),D.gain.linearRampToValueAtTime(1,C),D.gain.linearRampToValueAtTime(1e-4,C+.06),F.start(C-.02),F.stop(C+.1),await new Promise(B=>{const G=()=>{if($||U>=re){B();return}setTimeout(G,50)};setTimeout(()=>{$=!0,B()},K+500),G()}),q.onaudioprocess=null;try{q.disconnect()}catch{}try{z.disconnect()}catch{}try{await P.close()}catch{}try{await V.close()}catch{}E.getTracks().forEach(B=>B.stop());const L=_.subarray(0,U);return Ho(L,ee,130,30)},A=async()=>{if(!M.current){M.current=!0,w(!0),m(p("latencyCalibrator.requestingMic","Requesting microphone — click allow if prompted")),v(null),k([]),N(0);try{const E=[];for(let ee=0;ee<s;ee++){m(`${p("latencyCalibrator.playingTone","Playing test tone and recording…")} (${ee+1}/${s})`),N(Math.round(ee/s*100));const z=await I();z!==null&&(E.push(Math.max(-500,Math.min(2e3,Math.round(z)))),k([...E])),ee<s-1&&await new Promise(q=>setTimeout(q,400))}if(N(100),E.length===0){m(p("latencyCalibrator.noSignal","No signal detected — try louder or check the microphone"));return}let V;if(E.length>=3){const z=[...E].sort((q,K)=>q-K).slice(1,-1);V=Math.round(z.reduce((q,K)=>q+K,0)/z.length)}else V=Math.round(E.reduce((ee,z)=>ee+z,0)/E.length);v(V),m(`${p("latencyCalibrator.measured","Measured")} ~${V} ms (${E.length}: ${E.join(", ")} ms)`)}catch(E){m(`${p("latencyCalibrator.calibrationError","Calibration error: ")}${E instanceof Error?E.message:String(E)}`)}finally{M.current=!1,w(!1)}}},T=async()=>{if(!(x===null||!r)){S(!0);try{await r(Math.round(x)),m(p("latencyCalibrator.saved","Saved"))}catch(E){m(`${p("latencyCalibrator.saveError","Save error: ")}${String(E)}`)}finally{S(!1)}}},O={padding:"7px 16px",border:"none",borderRadius:8,cursor:"pointer",fontWeight:600};return d==="hidden"?null:n.jsxs("div",{className:`nice-latency-calibrator${o?` ${o}`:""}`,style:{padding:12,color:"var(--nice-text, inherit)",...l},id:c,"data-testid":h,children:[n.jsxs("h5",{style:{margin:"0 0 8px",display:"flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdSettings,{size:16})," ",p("latencyCalibrator.title","Latency calibrator — microphone")]}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("latencyCalibrator.device","Device"),": ",n.jsx("small",{children:e||"—"})]}),n.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[n.jsx("button",{type:"button",onClick:A,disabled:R,style:{...O,background:"var(--nice-accent, #3b82f6)",color:"var(--nice-text-on-primary, #fff)"},children:p("latencyCalibrator.calibrate","Calibrate")}),n.jsx("button",{type:"button",onClick:()=>{v(null),m(null),k([]),N(0)},style:{...O,background:"var(--nice-bg-tertiary)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.clear","Clear")})]}),R&&n.jsx("div",{style:{marginTop:8,height:6,borderRadius:3,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${j}%`,background:"var(--nice-accent, #3b82f6)",transition:"width 0.2s"}})}),b.length>0&&n.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:[p("latencyCalibrator.rounds","Rounds"),": ",b.join(", ")," ms"]}),n.jsxs("div",{style:{marginTop:8,fontSize:13},children:[n.jsxs("div",{children:[p("latencyCalibrator.status","Status"),": ",y??p("latencyCalibrator.none","none")]}),n.jsxs("div",{children:[p("latencyCalibrator.measuredOffset","Measured offset"),":"," ",x!==null?n.jsxs("strong",{children:[x," ms"]}):"—"]})]}),n.jsxs("div",{style:{marginTop:12,display:"flex",gap:8},children:[r&&n.jsx("button",{type:"button",onClick:T,disabled:x===null||g,style:{...O,background:"var(--nice-success, #22c55e)",color:"var(--nice-text-on-primary, #fff)",opacity:x===null||g?.5:1},children:p("latencyCalibrator.save","Save")}),a&&n.jsx("button",{type:"button",onClick:a,style:{...O,background:"transparent",border:"1px solid var(--nice-border, #334155)",color:"var(--nice-text, #e2e8f0)"},children:p("latencyCalibrator.close","Close")})]})]})},Zh=[{value:"normal",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdMicrophone,{size:14})," Mic"]})},{value:"pad",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdGamepad,{size:14})," Pad"]})},{value:"demo",label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdStopwatch,{size:14})," Demo"]})}],Ko=({players:e,defaultPlayers:t,onPlayersChange:r,gameMode:a="normal",onGameModeChange:s,gameModes:i=Zh,difficulty:o="normal",onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,t:f,className:p,style:y,id:m,accessMode:x,"data-testid":v})=>{const{t:g}=Te(),S=f??g,[b,k]=Se.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:r,componentName:"NiceKaraokeSetupPanel"}),[j,N]=u.useState([]);u.useEffect(()=>{var E,V,ee;if(c||!((E=navigator.mediaDevices)!=null&&E.enumerateDevices))return;let T=!1;const O=()=>navigator.mediaDevices.enumerateDevices().then(z=>!T&&N(z.filter(q=>q.kind==="audioinput"))).catch(()=>{});return O(),(ee=(V=navigator.mediaDevices).addEventListener)==null||ee.call(V,"devicechange",O),()=>{var z,q;T=!0,(q=(z=navigator.mediaDevices).removeEventListener)==null||q.call(z,"devicechange",O)}},[c]);const R=c??j,w=u.useMemo(()=>[{value:"",label:S("karaokeSetup.noMic","No microphone")},...R.map((T,O)=>({value:T.deviceId,label:T.label||`${S("karaokeSetup.microphone","Microphone")} ${O+1}`}))],[R,S]),M=(T,O)=>k(b.map(E=>E.id===T?{...E,...O}:E)),I=()=>{if(b.length>=d)return;const T=b.reduce((O,E)=>Math.max(O,E.id),0)+1;k([...b,{id:T,name:`${S("karaokeSetup.player","Player")} ${b.length+1}`,color:et[b.length%et.length],micId:null}])},A=T=>k(b.filter(O=>O.id!==T));return x==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-setup${p?` ${p}`:""}`,style:{display:"flex",flexDirection:"column",gap:16,...y},id:m,"data-testid":v,children:[n.jsxs("div",{style:{display:"flex",gap:24,flexWrap:"wrap"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:S("karaokeSetup.mode","Game mode")}),n.jsx(Ce.NiceSegmentedControl,{options:i,value:a,onChange:T=>s==null?void 0:s(T)})]}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,marginBottom:6,color:"var(--nice-text-muted, #94a3b8)"},children:S("karaokeSetup.difficulty","Difficulty")}),n.jsx(Ce.NiceSegmentedControl,{options:[{value:"easy",label:S("karaokeSetup.easy","Easy")},{value:"normal",label:S("karaokeSetup.normal","Normal")},{value:"hard",label:S("karaokeSetup.hard","Hard")}],value:o,onChange:T=>l==null?void 0:l(T)})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[n.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:[S("karaokeSetup.players","Players")," (",b.length,"/",d,")"]}),b.map(T=>n.jsx(Ce.NiceCard,{children:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[n.jsx(Ce.NiceColorPicker,{value:T.color||et[0],onChange:O=>M(T.id,{color:O})}),n.jsx("div",{style:{flex:"1 1 160px",minWidth:140},children:n.jsx(Ce.NiceTextInput,{value:T.name,onChange:O=>M(T.id,{name:O}),placeholder:S("karaokeSetup.playerName","Player name"),size:"sm"})}),n.jsx("div",{style:{flex:"1 1 180px",minWidth:150},children:n.jsx(Ce.NiceSelect,{options:w,value:T.micId??"",onChange:O=>M(T.id,{micId:(typeof O=="string"?O:O[0])||null}),placeholder:S("karaokeSetup.selectMic","Microphone"),size:"sm"})}),h&&T.micId&&n.jsxs(Ce.NiceButton,{variant:"ghost",size:"sm",onClick:()=>h(T.micId),children:[n.jsx(W.NtdSettings,{size:14})," ",S("karaokeSetup.calibrate","Calibrate")]}),n.jsx(Ce.NiceButton,{variant:"danger",size:"sm",onClick:()=>A(T.id),"aria-label":S("karaokeSetup.remove","Remove"),children:n.jsx(W.NtdClose,{size:14})})]})},T.id)),n.jsx("div",{children:n.jsxs(Ce.NiceButton,{variant:"primary",onClick:I,disabled:b.length>=d,children:[n.jsx(W.NtdPlus,{size:14})," ",S("karaokeSetup.addPlayer","Add player")]})})]})]})},Qh=["freeForAll","roundRobin","hostOnly","firstCome"],Jh={freeForAll:W.NtdDice,roundRobin:W.NtdRepeat,hostOnly:W.NtdCrown,firstCome:W.NtdLightning},ep={freeForAll:"success",roundRobin:"warning",hostOnly:"info",firstCome:"danger"},Yo=({players:e,mode:t,defaultMode:r,onModeChange:a,turnTimeSec:s=30,hostIndex:i=0,onActivePlayerChange:o,myPlayerIndex:l,t:c,className:d,style:h,id:f,accessMode:p,"data-testid":y})=>{const{t:m}=Te(),x=c??m,[v,g]=Se.useControllableState({value:t,defaultValue:r,fallbackValue:"freeForAll",onChange:a,componentName:"NiceKaraokeSelectionMode"}),S={freeForAll:x("songSelection.freeForAll","Free for all"),roundRobin:x("songSelection.roundRobin","Round robin"),hostOnly:x("songSelection.hostOnly","Host only"),firstCome:x("songSelection.firstCome","First come")},[b,k]=u.useState(0),[j,N]=u.useState(s),R=u.useRef(null),[w,M]=u.useState(null),[I,A]=u.useState(!1),[T,O]=u.useState(null),E=u.useRef(null),V=u.useMemo(()=>v==="hostOnly"?i:v==="roundRobin"?b%Math.max(1,e.length):v==="firstCome"?I?-1:T??-1:-1,[v,b,e.length,i,I,T]);u.useEffect(()=>{o==null||o(V)},[V,o]),u.useEffect(()=>{if(v!=="roundRobin"||s<=0){R.current&&clearInterval(R.current);return}return N(s),R.current=setInterval(()=>{N(re=>re<=1?(k(_=>_+1),s):re-1)},1e3),()=>{R.current&&clearInterval(R.current)}},[v,s,b]);const ee=u.useCallback(()=>{O(null),A(!1),M(3),E.current&&clearInterval(E.current),E.current=setInterval(()=>{M(re=>re===null||re<=1?(E.current&&clearInterval(E.current),A(!0),null):re-1)},1e3)},[]);u.useEffect(()=>()=>{E.current&&clearInterval(E.current)},[]),u.useEffect(()=>{v!=="firstCome"&&(M(null),A(!1),O(null))},[v]);const z=u.useCallback(()=>{k(re=>re+1),N(s)},[s]),q=re=>{var _;return((_=e[re])==null?void 0:_.name)||`${x("songSelection.player","Player")} ${re+1}`},K=V>=0&&V<e.length?e[V]:null;return p==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-selection-mode${d?` ${d}`:""}`,style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,padding:"8px 12px",background:"var(--nice-bg-secondary)",borderRadius:10,border:"1px solid var(--nice-border, #333)",...h},id:f,"data-testid":y,children:[n.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:Qh.map(re=>n.jsxs(Ce.NiceButton,{size:"sm",variant:v===re?ep[re]:"outline",onClick:()=>g(re),children:[u.createElement(Jh[re],{size:14})," ",S[re]]},re))}),v!=="freeForAll"&&v!=="firstCome"&&K&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsxs(Ce.NiceBadge,{variant:V===l?"success":"secondary",children:[n.jsx(W.NtdMicrophone,{size:12})," ",q(V)]}),V===l&&n.jsx("span",{style:{color:"var(--nice-success, #4caf50)",fontSize:12,fontWeight:600},children:x("songSelection.yourTurn","Your turn!")})]}),v==="roundRobin"&&s>0&&n.jsx("div",{style:{flex:1,minWidth:120,maxWidth:200},children:n.jsx(Ce.NiceProgress,{value:j,max:s,variant:j<=5?"error":j<=10?"warning":"info",showLabel:!0,formatValue:re=>`${re}s`})}),v==="roundRobin"&&n.jsxs(Ce.NiceButton,{size:"sm",variant:"ghost",onClick:z,children:[x("songSelection.next","Next")," ",n.jsx(W.NtdPlay,{size:12})]}),v==="firstCome"&&n.jsxs(n.Fragment,{children:[w!==null&&n.jsx("div",{style:{fontSize:32,fontWeight:900,color:"var(--nice-error, #f44336)",minWidth:60,textAlign:"center"},children:w}),I&&T===null&&n.jsxs(Ce.NiceBadge,{variant:"danger",children:[n.jsx(W.NtdLightning,{size:12})," ",x("songSelection.raceGo","GO! Pick a song!")]}),T!==null&&T<e.length&&n.jsxs(Ce.NiceBadge,{variant:"success",children:[n.jsx(W.NtdTrophy,{size:12})," ",q(T)," ",x("songSelection.raceWon","picks!")]}),n.jsx(Ce.NiceButton,{size:"sm",variant:w!==null?"secondary":"danger",onClick:ee,disabled:w!==null,children:T!==null?n.jsxs(n.Fragment,{children:[n.jsx(W.NtdRepeat,{size:12})," ",x("songSelection.raceAgain","New race")]}):n.jsxs(n.Fragment,{children:[n.jsx(W.NtdLightning,{size:12})," ",x("songSelection.raceStart","Start race")]})})]})]})};function tp(e,t,r,a){return u.useMemo(()=>e==="freeForAll"?!0:e==="firstCome"?t===-1:e==="hostOnly"?a===r:e==="roundRobin"?a===t:!1,[e,t,r,a])}const np=({players:e,defaultPlayers:t,onPlayersChange:r,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:c,maxPlayers:d=4,onCalibrate:h,initialSelectionMode:f="freeForAll",turnTimeSec:p=30,hostIndex:y=0,myPlayerIndex:m,onChange:x,variant:v="bar",t:g,className:S,style:b,id:k,accessMode:j,"data-testid":N})=>{const{t:R}=Te(),w=g??R,[M,I]=Se.useControllableState({value:e,defaultValue:t,fallbackValue:[],onChange:r,componentName:"NiceKaraokeSessionJoin"}),[A,T]=u.useState([]);u.useEffect(()=>{var C,L,B;if(c||!((C=navigator.mediaDevices)!=null&&C.enumerateDevices))return;let F=!1;const D=()=>navigator.mediaDevices.enumerateDevices().then(G=>!F&&T(G.filter(H=>H.kind==="audioinput"))).catch(()=>{});return D(),(B=(L=navigator.mediaDevices).addEventListener)==null||B.call(L,"devicechange",D),()=>{var G,H;F=!0,(H=(G=navigator.mediaDevices).removeEventListener)==null||H.call(G,"devicechange",D)}},[c]);const O=c??A,E=O.length===0,V=M.some(F=>!F.micId),ee=!V,[z,q]=u.useState(f),[K,re]=u.useState(-1),_=u.useCallback((F,D)=>{x==null||x({selectionMode:F,activePickerIndex:D,allMicsAssigned:ee,noInputDevices:E})},[x,ee,E]),U=u.useCallback(F=>{q(F),_(F,K)},[_,K]),$=u.useCallback(F=>{re(F),_(z,F)},[_,z]),P=u.useMemo(()=>({padding:10,borderRadius:8,fontWeight:700,marginTop:8,textAlign:"center"}),[]);return j==="hidden"?null:n.jsxs("div",{className:`nice-karaoke-session-join${S?` ${S}`:""}`,style:v==="card"?{background:"var(--nice-bg-secondary)",borderRadius:12,padding:16,...b}:b,id:k,"data-testid":N,children:[n.jsx(Ko,{players:M,onPlayersChange:I,gameMode:a,onGameModeChange:s,gameModes:i,difficulty:o,onDifficultyChange:l,audioInputs:O,maxPlayers:d,onCalibrate:h,t:w}),E&&n.jsxs("div",{style:{...P,background:"var(--nice-error, #ef4444)",color:"#fff"},children:[w("karaokeSessionJoin.noInputDevices","No microphone detected"),n.jsx("br",{}),n.jsx("span",{style:{fontWeight:400,fontSize:13},children:w("karaokeSessionJoin.noInputDevicesHint","Connect a microphone to sing.")})]}),!E&&V&&n.jsx("div",{style:{...P,background:"var(--nice-warning, #f59e0b)",color:"var(--nice-text-on-primary, #222)",fontSize:14},children:w("karaokeSessionJoin.assignMicWarning","Assign a microphone to each player.")}),M.length>1&&n.jsx("div",{style:{marginTop:12},children:n.jsx(Yo,{players:M,mode:z,onModeChange:U,onActivePlayerChange:$,turnTimeSec:p,hostIndex:y,myPlayerIndex:m,t:w})})]})};function Ue(e,t){var s;const r=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"",a=r==="otf"?"opentype":r==="woff2"?"woff2":r==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:a}}const rp=[Ue("Belagak","BelagakRegular-dr1zE.otf"),Ue("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),Ue("Gerhaus","Gerhaus-PK69E.ttf"),Ue("Gerhaus Italic","GerhausItalic-d96l7.ttf"),Ue("Handone Medium","HandoneMedium-nAevO.otf"),Ue("Handson Bold","HandsonBold-9MnrL.otf"),Ue("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),Ue("Kineks Round Light","KineksRoundLight-m2r35.ttf"),Ue("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),Ue("Kineks Round","KineksRoundRegular-PVRl7.ttf"),Ue("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),Ue("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),Ue("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),Ue("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),Ue("Lemon Milk Light","LemonMilkLight-owxMq.otf"),Ue("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),Ue("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),Ue("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),Ue("Lemon Milk","LemonMilkRegular-X3XE2.otf"),Ue("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),Ue("Pemage","PemageRegular-YqrdO.otf"),Ue("Rosmatika","RosmatikaRegular-BWA45.ttf"),Ue("Scabber","Scabber-q2Mn0.ttf"),Ue("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),Ue("Super Adorable","SuperAdorable-MAvyp.ttf"),Ue("Super Chiby","SuperChiby-BL62V.ttf"),Ue("Super Joyful","SuperJoyful-lxwPq.ttf"),Ue("Super Kindly","SuperKindly-drE8E.ttf"),Ue("Super Meatball","SuperMeatball-Yq1Gy.ttf")],es="nice2dev-karaoke-display",ap=[{value:"Arial",label:"Arial (default)"},{value:"Georgia, serif",label:"Georgia"},{value:"'Courier New', monospace",label:"Courier New"},{value:"'Trebuchet MS', sans-serif",label:"Trebuchet MS"},{value:"Impact, sans-serif",label:"Impact"},...rp.map(e=>({value:e.family,label:e.family}))],Xo=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","var(--nice-primary, #3498db)"],goldGradient:["var(--nice-warning, #FFD700)","#FF69B4","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#FF6D00","var(--nice-warning, #FFD700)"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["var(--nice-warning, #FFD700)","#00BCD4","var(--nice-warning, #FFD700)"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["var(--nice-warning, #FFD700)","#76ff03","var(--nice-warning, #FFD700)"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","var(--nice-color-accent-pink, #e91e63)","#7b1fa2"],goldGradient:["var(--nice-warning, #FFD700)","var(--nice-color-accent-pink, #e91e63)","var(--nice-warning, #FFD700)"],glowColor:"rgba(233,30,99,0.6)"}],mn={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["var(--nice-warning, #FFD700)","#FFA000","var(--nice-warning, #FFD700)"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let Zs=!1;function Zo(){try{const e=localStorage.getItem(es);if(e){const t=JSON.parse(e);return{...mn,...t}}}catch{}return{...mn}}async function sp(e){if(Zs||(Zs=!0,!e))return;const t=await e();if(t)try{const r=JSON.parse(t),a={...mn,...r};localStorage.setItem(es,JSON.stringify(a))}catch{}}function ip(e){const t=JSON.stringify(e);localStorage.setItem(es,t),ts(e)}function Qo(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=Xo.find(r=>r.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:mn.customSungGradient,goldGradient:mn.customGoldGradient,glowColor:mn.customGlowColor}}function ts(e){const{sungGradient:t,goldGradient:r,glowColor:a}=Qo(e),s=document.documentElement;s.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),s.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${r[0]}, ${r[1]}, ${r[2]})`),s.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${r[0]}`),s.style.setProperty("--karaoke-active-glow",`0 0 10px ${a}, 0 0 4px ${t[1]}80`),s.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${a}`),s.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),s.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function op(){const e=Zo();ts(e)}function lp(e){const t=(e||"").split(/\r?\n/),r=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(s&&/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10),l=parseInt(i[1]||"0",10),c=isNaN(o)?0:o/10,d=isNaN(l)?0:l/10;r.push({lineIndex:a,start:c,duration:d,raw:t[a]})}}return r}const cp=({index:e,style:t,data:r})=>{const{lines:a,notes:s,currentIndex:i,animationConfig:o}=r,l=a[e]??"",c=s.findIndex(S=>S.lineIndex===e),d=c>=0&&c===i,h=(o==null?void 0:o.enabled)??!0,f=(o==null?void 0:o.durationMs)??300,p=(o==null?void 0:o.translateX)??8,y=(o==null?void 0:o.scale)??1.01,m=(o==null?void 0:o.easing)??"cubic-bezier(.22,1,.36,1)",x=(o==null?void 0:o.opacityInactive)??.9,v=(o==null?void 0:o.boxShadow)??"0 6px 18px var(--nice-primary-tint-8, rgba(3,102,214,0.08))",g={transition:h?`transform ${f}ms ${m}, opacity ${f}ms ${m}`:"none",transform:d?`translateX(${p}px) scale(${y})`:"translateX(0px) scale(1)",opacity:d?1:x,boxShadow:d?v:"none"};return n.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":c>=0?c:void 0,children:n.jsx("div",{style:{...g,background:d?"var(--nice-primary-tint-12, rgba(0,130,200,0.12))":"transparent",padding:"4px 6px",borderRadius:4},children:n.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:l})})})},Jo=({ultrastarText:e,audioUrl:t,audioRef:r,animationConfig:a})=>{const{t:s}=Te(),i=u.useRef(null),o=r??i,[l,c]=u.useState(!1),d=u.useMemo(()=>lp(e),[e]),h=u.useRef(null),f=u.useRef(null),p=u.useRef(null),y=u.useRef(0),m=u.useRef(0),[x,v]=u.useState(-1),g=u.useMemo(()=>(e||"").split(/\r?\n/),[e]),S=28,b=g.length*S,k=u.useMemo(()=>({lines:g,notes:d,currentIndex:x,animationConfig:a}),[g,d,x,a]);return u.useEffect(()=>{const j=o.current;j&&(l?j.play().catch(()=>c(!1)):j.pause())},[l,o]),u.useEffect(()=>{const j=o.current;if(!j)return;let N=-1;const R=a??null,w=R&&typeof R.scrollSmooth=="number"?R.scrollSmooth:.18;let M=performance.now();const I=()=>{var _,U;const A=performance.now(),T=Math.max(0,Math.min(.2,(A-M)/1e3));M=A;const O=j.currentTime||0;y.current=O;let E=-1;for(let $=0;$<d.length;$++){const P=d[$];if(O>=P.start&&O<P.start+Math.max(.001,P.duration)){E=$;break}}E!==N&&(N=E,v(E));let V=0;if(N>=0){const $=((_=d[N])==null?void 0:_.lineIndex)??0,P=((U=f.current)==null?void 0:U.clientHeight)??220;V=$*S-P/2+S/2;const F=Math.max(0,b-P);(isNaN(V)||!isFinite(V))&&(V=0),V=Math.max(0,Math.min(V,F))}const ee=1-Math.pow(Math.max(0,1-w),Math.min(4,T*60)),re=(((a==null?void 0:a.scrollEasing)||"easeOutCubic")==="linear"?$=>$:$=>1-Math.pow(1-$,3))(ee);m.current=m.current+(V-m.current)*re;try{const $=f.current;$&&typeof $.scrollTop=="number"&&($.scrollTop=Math.round(m.current))}catch{}p.current=requestAnimationFrame(I)};return p.current=requestAnimationFrame(I),()=>{p.current&&cancelAnimationFrame(p.current)}},[o,d,b,a]),n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[n.jsx("button",{onClick:()=>c(j=>!j),disabled:!t,children:l?"Pause":"Play"}),n.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-secondary, #666)"},children:[(y.current||0).toFixed(2),"s"]}),n.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"var(--nice-text-secondary, #666)"},children:["Notes: ",d.length]})]}),n.jsx("div",{style:{border:"1px solid var(--nice-border, #ddd)",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?n.jsx(Xc.FixedSizeList,{height:220,width:"100%",itemCount:g.length,itemSize:S,ref:h,outerRef:f,itemData:k,children:cp}):n.jsx("div",{style:{color:"var(--nice-text-secondary, #888)"},children:s("karaokeEditor.noText","No text")})}),!r&&n.jsx("audio",{ref:i,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function dp(e){const t=(e||"").split(/\r?\n/).map(a=>a.replace(/\s+$/,"")),r=[];for(let a=0;a<t.length;a++){const s=t[a].trim();if(/^[:*F]\s/.test(s)){const i=s.slice(1).trim().split(/\s+/),o=parseInt(i[0]||"0",10)/10||0,l=parseInt(i[1]||"0",10)/10||.1;r.push({lineIndex:a,start:o,duration:l})}}return{lines:t,notes:r}}function el({ultrastarText:e,audioUrl:t,audioRef:r,ytRef:a}){const s=u.useRef(null),i=u.useRef(null),o=u.useRef([]),l=u.useRef([]),c=u.useRef(null),d=u.useRef(t);return d.current=t,u.useEffect(()=>{const{lines:h,notes:f}=dp(e);o.current=h,l.current=f;const p=c.current;p&&"rebuildTexts"in p&&typeof p.rebuildTexts=="function"&&p.rebuildTexts()},[e]),u.useEffect(()=>{let h=!0;return(async()=>{var N;if(!h||!s.current)return;const f=await import("phaser"),p="default"in f?f.default:f;if(!s.current||!h)return;const y=o,m=l,x=c,v=r,g=a,S=d;class b extends p.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null,this.textColor=Se.resolveCssColor("var(--nice-bg, #fff)"),this.activeColor=Se.resolveCssColor("var(--nice-info, #00aaff)")}create(){if(x.current=this,this.rebuildTexts(),g!=null&&g.current)this.audioEl=null;else if(v!=null&&v.current)this.audioEl=v.current;else{const w=document.querySelector("audio");w instanceof HTMLAudioElement?this.audioEl=w:S.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=S.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const T of this.texts)T.destroy();this.texts=[];const w={font:"18px monospace",color:this.textColor},M=22;let I=20;const A=y.current;for(let T=0;T<A.length;T++){const O=this.add.text(10,I,A[T]||" ",w).setOrigin(0,0);this.texts.push(O),I+=M}}update(){let w=0;if(g!=null&&g.current&&typeof g.current.getCurrentTime=="function")try{w=g.current.getCurrentTime()||0}catch{w=0}else w=this.audioEl&&this.audioEl.currentTime||0;for(let I=0;I<this.texts.length;I++)this.texts[I].setStyle({backgroundColor:void 0,color:this.textColor});const M=m.current;for(const I of M)if(w>=I.start&&w<I.start+Math.max(.001,I.duration)){const A=this.texts[I.lineIndex];A&&A.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:this.activeColor})}}}const k=((N=s.current)==null?void 0:N.clientWidth)??640,j={type:p.AUTO,parent:s.current,width:k,height:Math.round(k/2),backgroundColor:"#101010",scene:[b]};i.current=new p.Game(j)})(),()=>{h=!1,c.current=null;try{const f=i.current;f&&typeof f.destroy=="function"&&f.destroy(!0)}catch{}}},[]),n.jsx("div",{ref:s,style:{width:"100%",height:340}})}const up=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Qs=e=>{(!isFinite(e)||e<0)&&(e=0);const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`},Qr={border:"1px solid var(--nice-border-color)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg-secondary)",color:"var(--nice-text-primary)",cursor:"pointer"},hp=({isPlaying:e,index:t,count:r,currentTime:a,duration:s,volume:i,onPrev:o,onNext:l,onToggle:c,onSeek:d,onVolume:h})=>{const{t:f}=Te();return n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[n.jsx("div",{}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-secondary)"},children:[Qs(a)," / ",Qs(s)]})]}),n.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("button",{onClick:o,disabled:t<=0,title:f("playerControls.prev","Prev"),"aria-label":f("playerControls.previousTrack","Previous track"),style:Qr,children:n.jsx(W.NtdSkipBack,{size:16})}),n.jsx("button",{onClick:c,title:e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),"aria-label":e?f("playerControls.pause","Pause"):f("playerControls.play","Play"),style:Qr,children:e?n.jsx(W.NtdPause,{size:16}):n.jsx(W.NtdPlay,{size:16})}),n.jsx("button",{onClick:l,disabled:t>=r-1,title:f("playerControls.next","Next"),"aria-label":f("playerControls.nextTrack","Next track"),style:Qr,children:n.jsx(W.NtdSkipForward,{size:16})})]}),n.jsx("input",{type:"range",min:0,max:Math.max(1,s),step:.1,value:a,"aria-label":f("playerControls.seekPosition","Seek position"),onChange:p=>d(parseFloat(p.target.value))}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdVolume,{size:16}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:i,"aria-label":f("playerControls.volume","Volume"),onChange:p=>h(parseFloat(p.target.value))})]})]})]})},tl=u.memo(hp);function pp(e,t,r,a,s){const o=Math.max(1,Math.floor(a.length/48)),l=t/48;for(let c=0;c<48;c++){const d=a[c*o]/255,h=d*(r-6),f=c*l,p=r-h,y=c/48*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,l-2,h)}}function fp(e,t,r,a,s,i){if(!i.current){const f=[];for(let y=0;y<24;y++)f.push({ang:y/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,r)*.22+Math.random()*30});i.current={nodes:f}}const o=i.current,l=t/2,c=r/2,d=26+a*80,h=[];for(const f of o.nodes){f.phase+=.02+a*.06;const p=f.baseR+Math.sin(f.phase)*d,y=l+Math.cos(f.ang)*p,m=c+Math.sin(f.ang)*p;h.push([y,m])}e.fillStyle=`hsla(${s}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(s+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let f=0;f<h.length;f++){const[p,y]=h[f],[m,x]=h[(f+1)%h.length],v=(p+m)/2,g=(y+x)/2;f===0?e.moveTo(v,g):e.quadraticCurveTo(p,y,v,g)}e.closePath(),e.fill(),e.stroke()}function mp(e,t,r,a,s,i){i.current||(i.current={items:[]});const o=i.current;Math.random()<.06+a*.25&&o.items.push({x:Math.random()*t,y:Math.random()*r,r:8+Math.random()*24,life:1,hue:(s+Math.random()*120)%360});const l=[];for(const c of o.items){c.r+=2+a*14,c.life*=.975-a*.02,c.life>.04&&l.push(c);const d=e.createRadialGradient(c.x,c.y,1,c.x,c.y,c.r);d.addColorStop(0,`hsla(${c.hue}, 90%, 60%, ${.35*c.life})`),d.addColorStop(.6,`hsla(${(c.hue+40)%360}, 80%, 55%, ${.18*c.life})`),d.addColorStop(1,`hsla(${(c.hue+80)%360}, 70%, 50%, 0)`),e.fillStyle=d,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}o.items=l}const gp="var(--nice-text-muted, #94a3b8)",yp=({height:e,coverUrl:t,title:r,subtitle:a,label:s})=>n.jsx("div",{style:{textAlign:"center",color:"var(--nice-text-secondary, #e2e8f0)"},children:t?n.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsx("div",{style:{fontSize:18,fontWeight:600},children:r??"—"}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:gp},children:s??a??"—"})]})});function Jt(e,t){return e+Math.random()*(t-e)}function bp(e,t,r,a,s,i,o){o.current||(o.current={embers:[],t:0});const l=o.current,c=e.createLinearGradient(0,r,0,r*.4);c.addColorStop(0,`hsla(${(i+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(i+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,r);const d=6;for(let f=0;f<d;f++){const p=(f+.5)/d*t,y=(a[Math.floor((f+1)/(d+1)*a.length)]||0)/255,m=r*.18+(.25+s*.6+y*.7)*r*.55,x=e.createLinearGradient(p,r,p,r-m);x.addColorStop(0,`hsla(${(i+40)%360},100%,55%,.9)`),x.addColorStop(.5,`hsla(${(i+10)%360},100%,60%,.75)`),x.addColorStop(1,`hsla(${(i-20)%360},100%,80%,.05)`);const v=Math.sin(l.t*1.2+f*.8)*(15+s*30);e.fillStyle=x,e.beginPath(),e.moveTo(p-20,r),e.bezierCurveTo(p-35,r-m*.45,p-25+v,r-m*.75,p+v,r-m),e.bezierCurveTo(p+25+v*.3,r-m*.65,p+35,r-m*.35,p+20,r),e.closePath(),e.fill()}const h=Math.floor(1+s*6);for(let f=0;f<h;f++)l.embers.push({x:Jt(t*.25,t*.75),y:r-Jt(4,14),r:Jt(1,3),vx:Jt(-.15,.15),vy:-Jt(.6,1.8)-s*1.2,life:Jt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let f=l.embers.length-1;f>=0;f--){const p=l.embers[f];if(p.x+=p.vx,p.y+=p.vy,p.vy-=.01,p.life-=.015+s*.02,p.life<=0||p.y<-10){l.embers.splice(f,1);continue}const y=e.createRadialGradient(p.x,p.y,0,p.x,p.y,p.r*3);y.addColorStop(0,`hsla(${(i+25)%360},100%,65%,.9)`),y.addColorStop(1,`hsla(${(i+25)%360},100%,65%,0)`),e.fillStyle=y,e.beginPath(),e.arc(p.x,p.y,p.r*3,0,Math.PI*2),e.fill()}e.restore(),e.fillStyle="rgba(60,36,22,.9)",e.fillRect(t*.2,r-10,t*.6,6),l.t+=.02+s*.08}function vp(e,t,r,a,s){const i=t/2,o=r/2,l=Math.min(t,r)*.28,c=96,d=Math.max(1,Math.floor(a.length/c));for(let h=0;h<c;h++){const f=(a[h*d]??0)/255,p=h/c*Math.PI*2,y=f*(Math.min(t,r)*.22)+6,m=i+Math.cos(p)*l,x=o+Math.sin(p)*l,v=i+Math.cos(p)*(l+y),g=o+Math.sin(p)*(l+y);e.strokeStyle=`hsl(${(s+h*3)%360}, 90%, ${40+f*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(m,x),e.lineTo(v,g),e.stroke()}e.fillStyle=`hsla(${(s+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(i,o,l-8,0,Math.PI*2),e.fill()}function xp(e,t,r,a,s){const l=t/14,c=r/8;for(let d=0;d<8;d++)for(let h=0;h<14;h++){const f=Math.min(a.length-1,d*14+h),p=a[f]/255,y=(s+h/14*210+d/8*90)%360,m=65+p*30,x=20+p*40,v=(1-p)*4;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l+v,d*c+v,Math.max(1,l-2*v),Math.max(1,c-2*v))}}function Sp(e){const r=Array.from(new Set(e.filter(Boolean))).map(a=>new Promise(s=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>s(i),i.onerror=()=>s(i),i.src=a}));return Promise.all(r)}async function kp(e,t,r,a,s){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const i=e.current,o=t.join("|")!==i.loadedUrls.join("|");if(!i.ready||o){const l=await Sp(t.length?t:[]);i.loadedUrls=t,i.sprites=[],i.ready=!0;const c=d=>l[d%Math.max(1,l.length)]??new Image;for(let d=0;d<r;d++){const h=Math.random()*Math.min(a,s)*.38+40;i.sprites.push({img:c(d),x:(Math.random()-.5)*h*.4,y:(Math.random()-.5)*h*.4,z:Math.random()*600+100,ang:Math.random()*Math.PI*2,spin:(Math.random()*.03+.01)*(Math.random()<.5?-1:1),vz:Math.random()*1.2+.2,size:Math.random()*.35+.65})}}}function wp(e,t,r,a,s,i,o,l){const c=i.current;if(!(c!=null&&c.ready))return;const d=t/2,h=r/2,f=900,p=1+a*2;for(const m of c.sprites){m.ang+=m.spin*p,m.z-=m.vz*(.8+a*2.4),m.z<40&&(m.z=f);const x=Math.min(t,r)*.32+Math.sin(m.ang*.8)*18;m.x=Math.cos(m.ang)*x,m.y=Math.sin(m.ang*1.1)*x*.6}const y=[...c.sprites].sort((m,x)=>x.z-m.z);for(const m of y){const x=f/(f-m.z)*.6*m.size,v=d+m.x*x,g=h+m.y*x,S=64*x,b=64*x;e.save(),e.globalAlpha=.12+(1-m.z/f)*.2,e.fillStyle=`hsl(${(s+(1-m.z/f)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(v,g,S*.7,b*.7,0,0,Math.PI*2),e.fill(),e.restore(),m.img&&m.img.width?e.drawImage(m.img,v-S/2,g-b/2,S,b):(e.save(),e.fillStyle=`hsl(${(s+180)%360}, 40%, 55%)`,e.fillRect(v-S/2,g-b/2,S,b),e.restore())}}function wn(e,t){return e+Math.random()*(t-e)}function Cp(e,t,r,a,s,i){i.current||(i.current={blobs:Array.from({length:7},(d,h)=>({x:wn(t*.2,t*.8),y:wn(r*.2,r*.8),r:wn(Math.min(t,r)*.05,Math.min(t,r)*.12),vx:wn(-.6,.6),vy:wn(-.6,.6),hue:(s+h*10)%360}))});const o=i.current,l=.6+a*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of o.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-a*.015,c.x<c.r&&(c.x=c.r,c.vx=Math.abs(c.vx)),c.x>t-c.r&&(c.x=t-c.r,c.vx=-Math.abs(c.vx)),c.y<c.r&&(c.y=c.r,c.vy=Math.abs(c.vy)),c.y>r-c.r&&(c.y=r-c.r,c.vy=-Math.abs(c.vy));const d=(c.hue+a*120)%360,h=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);h.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),h.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=h,e.shadowBlur=18,e.shadowColor=`hsl(${d}, 100%, 60%)`,e.beginPath(),e.arc(c.x,c.y,c.r,0,Math.PI*2),e.fill()}e.restore(),e.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-6, rgba(255, 255, 255, 0.06))",e.canvas),e.lineWidth=2,e.strokeRect(1,1,t-2,r-2)}function jp(e,t,r,a,s,i){i.current||(i.current={tris:[]});const o=i.current,l=6;for(;o.tris.length<l;)o.tris.push({a:Math.random()*Math.PI*2,r:30+Math.random()*Math.min(t,r)*.35,dr:(Math.random()*.6+.2)*(Math.random()<.5?-1:1)});const c=t/2,d=r/2;for(const h of o.tris){h.a+=.002+a*.02*(h.dr>0?1:-1),h.r+=Math.sin(h.a*2)*(.3+a*1.4);const f=Math.max(40,Math.min(h.r,Math.min(t,r)*.48));e.save(),e.translate(c,d),e.rotate(h.a),e.strokeStyle=`hsla(${(s+f*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(f,0);for(let p=1;p<3;p++){const y=p*Math.PI*2/3;e.lineTo(Math.cos(y)*f,Math.sin(y)*f)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function Mp(e,t,r,a,s,i){const o=t/2,l=r/2,c=5,d=Math.min(t,r)*.42;i.current+=.01;for(let h=0;h<c;h++){const f=(h+1)/(c+1),p=f*d;e.strokeStyle=`hsla(${(s+h*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(o,l,p,0,Math.PI*2),e.stroke();const y=Math.floor(a.length*f|0),m=(a[y]??0)/255,x=6+h*2;for(let v=0;v<x;v++){const g=i.current*(1+h*.15)+v/x*Math.PI*2,S=p+Math.sin(g*2)*6*m,b=o+Math.cos(g)*S,k=l+Math.sin(g)*S;e.fillStyle=`hsla(${(s+h*30+v*6)%360}, 90%, ${55+m*30}%, ${.6+m*.3})`,e.beginPath(),e.arc(b,k,2+m*4,0,Math.PI*2),e.fill()}}}function Rp(e,t,r,a,s){const l=t/12,c=r/6;for(let d=0;d<6;d++)for(let h=0;h<12;h++){const f=(d*12+h)%a.length,p=a[f]/255,y=(s+h/12*180+d/6*90)%360,m=70+p*25,x=25+p*35;e.fillStyle=`hsl(${y}, ${m}%, ${x}%)`,e.fillRect(h*l,d*c,Math.ceil(l),Math.ceil(c))}}function Np(e,t,r,a,s,i){const o=t/2,l=r/2,c=2+Math.floor(a*14);for(let h=0;h<c;h++){const f=Math.random()*Math.PI*2,p=.5+Math.random()*(2.5+a*4);i.current.push({x:o,y:l,vx:Math.cos(f)*p,vy:Math.sin(f)*p,life:0,max:40+Math.random()*60,hue:(s+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,r);const d=i.current;for(let h=d.length-1;h>=0;h--){const f=d[h];f.x+=f.vx,f.y+=f.vy,f.life+=1;const p=1-f.life/f.max;e.fillStyle=`hsla(${f.hue},85%,60%,${Math.max(0,p)})`,e.beginPath(),e.arc(f.x,f.y,2+p*3,0,Math.PI*2),e.fill(),(f.life>=f.max||f.x<-20||f.y<-20||f.x>t+20||f.y>r+20)&&d.splice(h,1)}d.length>1200&&d.splice(0,d.length-1200)}function Tp(e,t,r,a,s,i){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,r);const o=t/2,l=r/2,c=Math.min(t,r)*(.38+s*.12),d=e.createRadialGradient(o,l,c*.1,o,l,c);d.addColorStop(0,`hsla(${(i+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(i+260)%360},80%,55%,0.6)`),d.addColorStop(1,"transparent"),e.fillStyle=d,e.beginPath(),e.arc(o,l,c,0,Math.PI*2),e.fill();const h=18+Math.floor(s*50);for(let f=0;f<h;f++){const p=f/h*Math.PI*2+a*(.6+s*1.4),y=(Math.sin(a*2+f*1.7)+Math.cos(a*1.3+f*2.1))*.15,m=c*(.4+.55*Math.abs(Math.sin(a*1.2+f))),x=6;e.save(),e.translate(o,l),e.rotate(p+y),e.beginPath(),e.moveTo(0,0);for(let g=1;g<=x;g++){const S=m/x*g,b=(Math.sin(a*3+f*.8+g)*.6+Math.cos(a*2+f+g*.7))*(8+24*s),k=S,j=b;e.lineTo(j,k)}e.globalCompositeOperation="lighter";const v=(i+f*(240/h))%360;e.strokeStyle=`hsla(${v}, 90%, ${60+s*20}%, ${.35+s*.4})`,e.lineWidth=2+s*2,e.stroke(),e.restore()}e.beginPath(),e.arc(o,l,c*(.98+.02*Math.sin(a*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(i+40)%360},90%,70%,${.25+s*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function $p(e,t,r,a,s){const o=Math.max(1,Math.floor(a.length/96)),l=t/2,c=r/2,d=Math.min(t,r)*.22,h=Math.min(t,r)*.48;for(let f=0;f<96;f++){const p=a[f*o]/255,y=f/96*Math.PI*2,m=d,x=d+p*(h-d),v=l+Math.cos(y)*m,g=c+Math.sin(y)*m,S=l+Math.cos(y)*x,b=c+Math.sin(y)*x;e.strokeStyle=`hsl(${f/96*360+s},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(v,g),e.lineTo(S,b),e.stroke()}e.fillStyle=Se.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Pp(e,t,r,a,s,i){const o=t/2,l=r/2,c=Math.min(t,r)*.5,d=Js(a,0,Math.floor(a.length*.1))/255,h=Js(a,Math.floor(a.length*.6),a.length)/255;i.current+=.01+h*.03;const f=24;for(let p=0;p<f;p++){const y=i.current+p/f*Math.PI*2,m=(.35+d*.55)*c,x=o+Math.cos(y)*m,v=l+Math.sin(y)*m,g=e.createRadialGradient(o,l,0,o,l,m),S=p/f*360+s;g.addColorStop(0,`hsla(${S},85%,65%,0.0)`),g.addColorStop(1,`hsla(${S},85%,65%,0.9)`),e.strokeStyle=g,e.lineWidth=6+h*8,e.beginPath(),e.moveTo(o,l),e.lineTo(x,v),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,r)}function Js(e,t,r){let a=0,s=0;for(let i=t;i<r;i++)a+=e[i],s++;return s?a/s:0}function Ap(e,t,r,a,s,i){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,r);const o=r/2,l=Math.max(8,18-s*10),c=r*.35*(.6+s*.7),d=a.length,h=t/(d-1);e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.sin(i*1.5+y*.03)*.12,v=y*h,g=o-l-(m+x)*c;y===0?e.moveTo(v,g):e.lineTo(v,g)}const f=e.createLinearGradient(0,0,0,o-l);f.addColorStop(0,"hsla(260,90%,75%,0.9)"),f.addColorStop(1,"hsla(220,85%,60%,0.4)"),e.strokeStyle=f,e.lineWidth=2,e.stroke(),e.beginPath();for(let y=0;y<d;y++){const m=(a[y]-128)/128,x=Math.cos(i*1.3+y*.035)*.12,v=y*h,g=o+l+(m+x)*c;y===0?e.moveTo(v,g):e.lineTo(v,g)}const p=e.createLinearGradient(0,o+l,0,r);p.addColorStop(0,"hsla(190,90%,65%,0.9)"),p.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=p,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle=Se.resolveCssColor("var(--nice-overlay-light-8, rgba(255, 255, 255, 0.08))",e.canvas),e.lineWidth=6,e.beginPath(),e.moveTo(0,o-l),e.lineTo(t,o-l),e.stroke(),e.beginPath(),e.moveTo(0,o+l),e.lineTo(t,o+l),e.stroke(),e.globalCompositeOperation="source-over"}function Ep(e,t,r,a,s,i){const o=t/2,l=r/2,c=5,d=Math.min(t,r)*.12;for(let h=0;h<c;h++){const f=Math.floor(h/c*a.length),p=a[f]/255,y=d+h*d*.55+p*d*.5,m=(i+h*40)%360;e.lineWidth=3+p*6,e.strokeStyle=`hsla(${m},80%,60%,${.5+.5*s})`,e.beginPath(),e.arc(o,l,y,0,Math.PI*2),e.stroke()}}function Ip(e,t,r,a,s){const i=Math.min(a.length,256),o=Math.max(1,Math.floor(a.length/i)),l=t/i;for(let c=0;c<i;c++){const d=a[c*o]/255,h=d*(r-6),f=c*l,p=r-h,y=c/i*240+s;e.fillStyle=`hsl(${y%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(f+1,p,l-2,h)}}function Lp(e,t,r,a){e.current||(e.current={stars:[],ready:!1});const s=e.current;if(!s.ready||s.stars.length!==t){const i=[];for(let o=0;o<t;o++){const l={x:(Math.random()-.5)*r,y:(Math.random()-.5)*a,z:Math.random()*800+100,pz:0};i.push(l)}s.stars=i,s.ready=!0}}function Dp(e,t,r,a,s,i){const o=i.current,l=t/2,c=r/2,d=4+a*18;e.save(),e.translate(l,c);for(const h of o.stars){h.z-=d,h.z<20&&(h.x=(Math.random()-.5)*t,h.y=(Math.random()-.5)*r,h.z=900,h.pz=h.z);const f=h.x/h.z*600,p=h.y/h.z*600,y=h.x/h.pz*600,m=h.y/h.pz*600;h.pz=h.z,e.strokeStyle=`hsla(${(s+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-h.z/900)*2),e.beginPath(),e.moveTo(y,m),e.lineTo(f,p),e.stroke()}e.restore()}function zp(e,t,r,a){e.lineWidth=2,e.strokeStyle=Se.resolveCssColor("var(--nice-primary-light, #c7d2fe)",e.canvas),e.beginPath();const s=t/a.length;for(let i=0;i<a.length;i++){const o=(a[i]-128)/128,l=i*s,c=r/2+o*(r*.45);i===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}const _p=({active:e,onClick:t,title:r,children:a})=>n.jsx("button",{type:"button",onClick:t,title:r,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-info, #6366f1)":"var(--nice-border-color, #334155)"}`,background:e?"rgba(99,102,241,.12)":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-text-on-primary, #e2e8f0)":"var(--nice-text-on-primary, #cbd5e1)",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:a}),ns=({modes:e=[],active:t,setActive:r,rows:a=2})=>{const{t:s}=Te(),i=Math.max(1,a);return!e||e.length===0?null:n.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:n.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${i}, auto)`,gridAutoColumns:"max-content",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:6,borderRadius:10,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(o=>n.jsx(_p,{active:t===o,onClick:()=>r(o),title:`${s("visualizer.mode","Mode")}: ${o}`,children:o},o))})})};function Fp(e,t){const[r,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(r))}catch{}},[e,r]),[r,a]}const Op=({vu:e,hide:t})=>{if(t)return null;const r=12,a=Math.round(e*r);return n.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:r}).map((s,i)=>{const o=120*(i/r);return n.jsx("div",{style:{width:6,height:18,borderRadius:2,background:i<a?`hsl(${o}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},i)})})},Bp="var(--player-bg, #0f172a)";function Gp(e,t){const r=e.length;for(let a=0;a<r;a++){const s=a/r,i=.55*Math.exp(-Math.pow((s-(.12+.08*Math.sin(t*.7)))*7,2))+.45*Math.exp(-Math.pow((s-(.4+.15*Math.sin(t*1.1+1)))*9,2))+.3*(1-s)*(.55+.45*Math.sin(t*2+a*.06));e[a]=Math.max(0,Math.min(255,Math.floor(i*255)))}}function Wp(e,t){const r=e.length;for(let a=0;a<r;a++){const s=a/r*Math.PI*2,i=Math.sin(s*3+t*3)*.5+Math.sin(s*7+t*2)*.28;e[a]=Math.max(0,Math.min(255,Math.floor(128+i*110)))}}const rs=({kind:e,audioRef:t,width:r="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,imageUrls:f,imageCount:p=14,autoAnimate:y=!1})=>{const m=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette","radial","rays","particles","rings","grid","imageTornado","colorRipples","starfield","orbitals","eqcircle","triangles","blob","plasma","lavaLamp","cozyFire","rift"],[e,h]),x=u.useMemo(()=>{const _=m.includes(c)?c:m[0];try{const U=localStorage.getItem(d);if(!U)return _;const $=JSON.parse(U);return m.includes($)?$:_}catch{return _}},[m,c,d]),[v,g]=Fp(d,x),S=u.useRef(null),b=u.useRef(null),k=u.useRef(null),j=u.useRef(null),N=u.useRef(null),R=u.useRef(null),w=u.useRef(0),M=u.useRef(0),I=u.useRef([]),[A,T]=u.useState(0),O=u.useRef(null),E=u.useRef(null),V=u.useRef(null),ee=u.useRef(null),z=u.useRef(null),q=u.useRef(null),K=u.useRef(null),re=v!=="cover"&&v!=="video";return u.useEffect(()=>{var C;if(e==="youtube"||(b.current&&(cancelAnimationFrame(b.current),b.current=null),!re))return;Gt();const _=yn(),U=t.current;if(!U&&!y)return;if(U&&!k.current)try{k.current=_.createMediaElementSource(U)}catch{}if(U&&!j.current){const L=_.createAnalyser();L.fftSize=2048,L.smoothingTimeConstant=.85,j.current=L;try{(C=k.current)==null||C.connect(L)}catch{}try{L.connect(_.destination)}catch{}}const $=j.current;N.current=new Uint8Array($?$.frequencyBinCount:1024),R.current=new Uint8Array($?$.fftSize:2048);const P=()=>{const L=S.current,B=Math.max(1,Math.floor(window.devicePixelRatio||1));L.width=Math.floor(L.clientWidth*B),L.height=Math.floor(L.clientHeight*B);const G=L.getContext("2d");G==null||G.setTransform(1,0,0,1,0,0),G==null||G.scale(B,B)};P();const F=()=>P();window.addEventListener("resize",F),Lp(V,220,S.current.width,S.current.height);const D=async()=>{const L=S.current;if(!L)return;const B=L.getContext("2d");if(!B)return;const G=Math.max(1,Math.floor(window.devicePixelRatio||1)),H=L.width/G,X=L.height/G,oe=performance.now()*.001,le=v==="waveform"||v==="rift";$&&(le?$.getByteTimeDomainData(R.current):$.getByteFrequencyData(N.current)),y&&(Gp(N.current,oe),Wp(R.current,oe));let ne=0;const Z=le?R.current:N.current;for(let Y=0;Y<Z.length;Y++){const se=le?(Z[Y]-128)/128:Z[Y]/255;ne+=se*se}if(ne=Math.sqrt(ne/Z.length),T(Math.min(1,ne)),B.clearRect(0,0,H,X),v==="spectrum")Ip(B,H,X,N.current,w.current);else if(v==="bars")pp(B,H,X,N.current,w.current);else if(v==="waveform")zp(B,H,X,R.current);else if(v==="palette"){const Y=(w.current+ne*120)%360;Rp(B,H,X,N.current,Y)}else if(v==="radial")$p(B,H,X,N.current,w.current);else if(v==="rays")Pp(B,H,X,N.current,w.current,M);else if(v==="particles")Np(B,H,X,ne,w.current,I);else if(v==="rings")Ep(B,H,X,N.current,ne,w.current);else if(v==="grid"){const Y=(w.current+ne*160)%360;xp(B,H,X,N.current,Y)}else if(v==="imageTornado"){const Y=f!=null&&f.length?f:s?[s]:[];await kp(O,Y,p,H,X);const se=(w.current+ne*100)%360;wp(B,H,X,ne,se,O)}else if(v==="colorRipples"){const Y=(w.current+ne*120)%360;mp(B,H,X,ne,Y,E)}else if(v==="starfield"){const Y=(w.current+60)%360;Dp(B,H,X,ne,Y,V)}else if(v==="orbitals"){const Y=(w.current+ne*180)%360;Mp(B,H,X,N.current,Y,M)}else if(v==="eqcircle"){const Y=(w.current+120)%360;vp(B,H,X,N.current,Y)}else if(v==="triangles"){const Y=(w.current+40)%360;jp(B,H,X,ne,Y,ee)}else if(v==="blob"){const Y=(w.current+90)%360;fp(B,H,X,ne,Y,z)}else if(v==="plasma"){const Y=(w.current+ne*200)%360;Tp(B,H,X,oe,ne,Y)}else if(v==="rift")Ap(B,H,X,R.current,ne,oe);else if(v==="lavaLamp"){const Y=(w.current+ne*80)%360;Cp(B,H,X,ne,Y,q)}else if(v==="cozyFire"){const Y=(w.current+ne*140)%360;bp(B,H,X,N.current,ne,Y,K)}w.current=(w.current+.4)%360,b.current=requestAnimationFrame(D)};return b.current=requestAnimationFrame(D),()=>{window.removeEventListener("resize",F),b.current&&cancelAnimationFrame(b.current)}},[re,e,t,v,f,p,s,y]),n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:v==="cover"?"transparent":Bp},children:v==="cover"?n.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:n.jsx(yp,{height:a,coverUrl:s,title:i,subtitle:o,label:l})}):n.jsx("canvas",{ref:S,style:{width:typeof r=="number"?`${r}px`:r,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),n.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[n.jsx(ns,{modes:m,active:v,setActive:g,rows:2}),n.jsx(Op,{vu:A,hide:e==="youtube"})]})]})},nl=({height:e,autoPlay:t,track:r,source:a,ytRef:s,audioRef:i,hlsRef:o,setVol:l,onEnd:c,volume:d,extractVideoId:h})=>{u.useEffect(()=>{const m=i.current;if(m){if(m.volume=d,m.crossOrigin=a!=null&&a.withCredentials?"use-credentials":"anonymous",(a==null?void 0:a.kind)==="hls"&&up(a.url)){const x=()=>{m.src=a.url,m.load(),t&&m.play().catch(()=>{})};if(m.canPlayType("application/vnd.apple.mpegurl")){x();return}(async()=>{const g=(await import("hls.js")).default;if(g.isSupported()){const S=new g({xhrSetup:b=>{if(a!=null&&a.withCredentials&&(b.withCredentials=!0),a!=null&&a.headers)for(const[k,j]of Object.entries(a.headers))b.setRequestHeader(k,String(j))}});o.current=S,S.loadSource(a.url),S.attachMedia(m),S.on(g.Events.MANIFEST_PARSED,()=>t&&m.play().catch(()=>{}))}else x()})()}(a==null?void 0:a.kind)==="audio"&&a.url&&(m.src=a.url,m.load(),t&&m.play().catch(()=>{}))}},[a==null?void 0:a.url,a==null?void 0:a.kind,a==null?void 0:a.withCredentials,d,t]);const f=(a==null?void 0:a.kind)==="youtube",p=f?"video":"cover",y=`gp-stage:mode:${(a==null?void 0:a.kind)??"none"}`;return n.jsxs("div",{className:"gp-stage",style:{width:"100%",height:e,background:f?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(a==null?void 0:a.kind)==="youtube"&&n.jsx(Na,{videoId:a.videoId??h(a.url),onReady:m=>{s.current=m.target,l(d),t&&m.target.playVideo()},onEnd:c,opts:{width:"100%",height:"100%",playerVars:{autoplay:t?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3}},style:{width:"100%",height:"100%"}}),((a==null?void 0:a.kind)==="audio"||(a==null?void 0:a.kind)==="hls")&&n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, #e2e8f0)"},children:r!=null&&r.coverUrl?n.jsx("img",{alt:"cover",src:r.coverUrl,style:{height:e-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[r==null?void 0:r.artist," — ",r==null?void 0:r.title]}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--nice-text-dim, #94a3b8)"},children:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim()})]})}),n.jsx("audio",{ref:i,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:a!=null&&a.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),n.jsx(rs,{kind:(a==null?void 0:a.kind)==="hls"?"hls":(a==null?void 0:a.kind)??"audio",audioRef:i,hlsRef:o,height:e,coverUrl:r==null?void 0:r.coverUrl,title:r==null?void 0:r.title,subtitle:r==null?void 0:r.artist,label:(a==null?void 0:a.label)??`${(a==null?void 0:a.codec)??""} ${(a==null?void 0:a.quality)??""}`.trim(),defaultMode:p,storageKey:y},`vis-${y}`)]})};function Up(e,t){const[r,a]=u.useState(()=>{try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}});return u.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(r))}catch{}},[e,r]),[r,a]}const qp="var(--nice-text-dim, #94a3b8)",Vp=({active:e,onClick:t,title:r,children:a})=>n.jsx("button",{type:"button",onClick:t,title:r,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"var(--nice-color-accent, #6366f1)":"var(--nice-border-muted, #334155)"}`,background:e?"var(--nice-accent-tint-10, rgba(99,102,241,.12))":"var(--nice-overlay-60, rgba(15,23,42,.6))",color:e?"var(--nice-text-on-primary, #e2e8f0)":"var(--nice-overlay-light-80, rgba(255, 255, 255, 0.8))",cursor:"pointer"},children:a}),rl=({kind:e,audioRef:t,width:r="100%",height:a=360,coverUrl:s,title:i,subtitle:o,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:h,overlayOnly:f=!1})=>{const p=u.useMemo(()=>h!=null&&h.length?h:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,h]),y=u.useMemo(()=>{const T=p.includes(c)?c:p[0];try{const O=localStorage.getItem(d);if(!O)return T;const E=JSON.parse(O);return p.includes(E)?E:T}catch{return T}},[p,c,d]),[m,x]=Up(d,y),v=u.useRef(null),[g,S]=u.useState(0),b=u.useRef(null),k=u.useRef(null),j=u.useRef(null),N=u.useRef(null),R=u.useRef(null),w=u.useRef(0),M=m==="spectrum"||m==="bars"||m==="waveform"||m==="palette";u.useEffect(()=>{var z;if(e==="youtube")return;if(!M){b.current&&cancelAnimationFrame(b.current);return}Gt();const T=yn(),O=t.current;if(!O)return;if(!k.current)try{k.current=T.createMediaElementSource(O)}catch{}if(!j.current){const q=T.createAnalyser();q.fftSize=2048,q.smoothingTimeConstant=.85,j.current=q;try{(z=k.current)==null||z.connect(q)}catch{}try{q.connect(T.destination)}catch{}}const E=j.current;N.current=new Uint8Array(E.frequencyBinCount),R.current=new Uint8Array(E.fftSize);const V=()=>{if(!v.current)return;const q=v.current,K=q.getContext("2d");if(!K)return;const re=q.width,_=q.height;K.clearRect(0,0,re,_),m==="waveform"?E.getByteTimeDomainData(R.current):E.getByteFrequencyData(N.current);let U=0;const $=m==="waveform"?R.current:N.current;for(let P=0;P<$.length;P++){const F=m==="waveform"?($[P]-128)/128:$[P]/255;U+=F*F}if(U=Math.sqrt(U/$.length),S(Math.min(1,U)),m==="spectrum"||m==="bars"){const P=N.current,F=m==="bars"?48:Math.min(P.length,256),D=Math.floor(P.length/F),C=re/F;for(let L=0;L<F;L++){const B=P[L*D]/255,G=B*(_-6),H=L*C,X=_-G,oe=L/F*240+w.current;K.fillStyle=`hsl(${oe%360}, 80%, ${Math.max(30,40+B*30)}%)`,K.fillRect(H+1,X,C-2,G)}}else if(m==="waveform"){const P=R.current;K.lineWidth=2,K.strokeStyle=Se.resolveCssColor("var(--nice-primary-light, #c7d2fe)",K.canvas),K.beginPath();const F=re/P.length;for(let D=0;D<P.length;D++){const C=(P[D]-128)/128,L=D*F,B=_/2+C*(_*.45);D===0?K.moveTo(L,B):K.lineTo(L,B)}K.stroke()}else if(m==="palette"){const D=re/12,C=_/6,L=(w.current+U*120)%360;for(let B=0;B<6;B++)for(let G=0;G<12;G++){const H=(B*12+G)%N.current.length,X=N.current[H]/255,oe=(L+G/12*180+B/6*90)%360,le=70+X*25,ne=25+X*35;K.fillStyle=`hsl(${oe}, ${le}%, ${ne}%)`,K.fillRect(G*D,B*C,Math.ceil(D),Math.ceil(C))}}K.strokeStyle=Se.resolveCssColor(getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"var(--nice-primary-light, #c7d2fe)",K.canvas),b.current=requestAnimationFrame(V)},ee=()=>{var re;const q=v.current,K=Math.max(1,Math.floor(window.devicePixelRatio||1));q.width=Math.floor(q.clientWidth*K),q.height=Math.floor(q.clientHeight*K),(re=q.getContext("2d"))==null||re.scale(K,K)};return ee(),window.addEventListener("resize",ee),b.current=requestAnimationFrame(V),()=>{window.removeEventListener("resize",ee),b.current&&cancelAnimationFrame(b.current)}},[M,e,t,m]);const I=()=>{if(e==="youtube")return null;const T=12,O=Math.round(g*T);return n.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px 8px",borderRadius:8,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)"},children:Array.from({length:T}).map((E,V)=>{const ee=120*(V/T);return n.jsx("div",{style:{width:6,height:18,borderRadius:2,background:V<O?`hsl(${ee}, 80%, 50%)`:"var(--nice-text, #1f2937)"}},V)})})},A=()=>n.jsx("div",{style:{textAlign:"center",color:"var(--nice-overlay-light-90, #e2e8f0)"},children:s?n.jsx("img",{alt:"cover",src:s,style:{height:a-24,objectFit:"contain"}}):n.jsxs("div",{style:{opacity:.8},children:[n.jsx("div",{style:{fontSize:18,fontWeight:600},children:i??""}),n.jsx("div",{style:{marginTop:8,fontSize:12,color:qp},children:l??o??""})]})});return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:m==="cover"?n.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:A()}):n.jsx("canvas",{ref:v,style:{width:typeof r=="number"?`${r}px`:r,height:a,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),n.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[n.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"var(--nice-overlay-50, rgba(2, 6, 23, 0.5))",padding:"6px",borderRadius:10,border:"1px solid var(--nice-border-color, #334155)",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:p.map(T=>n.jsx(Vp,{active:m===T,onClick:()=>x(T),title:`Tryb: ${T}`,children:T},T))}),n.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:n.jsx(I,{})})]})]})},al=({artist:e,title:t,hideControls:r=!0,isPlaying:a,onTimeUpdate:s,searchYouTubeByArtistTitle:i})=>{const{t:o}=Te(),[l,c]=u.useState(e||""),[d,h]=u.useState(t||""),[f,p]=u.useState(null),[y,m]=u.useState(null),x=u.useRef(null),[v,g]=u.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});u.useEffect(()=>{e&&t&&i&&i(e,t).then(p)},[e,t,i]),u.useEffect(()=>{y&&(a?y.playVideo():y.pauseVideo())},[a,y]),u.useEffect(()=>{if(y&&s){const b=setInterval(()=>{const k=y.getCurrentTime();s(k)},100);return()=>clearInterval(b)}},[y,s]),u.useEffect(()=>{const b=()=>{if(x.current){const k=x.current.clientWidth,j=Math.round(k*(9/16));g({width:k,height:j})}};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]);const S=async()=>{if(!i)return;const b=await i(l,d);p(b)};return n.jsxs("div",{ref:x,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!f)&&n.jsxs("div",{children:[n.jsx("input",{value:l,onChange:b=>c(b.target.value),placeholder:o("youtubePlayer.artist","Artist"),"aria-label":o("youtubePlayer.artist","Artist")}),n.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:o("youtubePlayer.title","Title"),"aria-label":o("youtubePlayer.title","Title")}),n.jsx("button",{onClick:S,children:o("youtubePlayer.search","Search")})]}),f&&n.jsxs("div",{children:[n.jsx(Na,{videoId:f,opts:{width:v.width.toString(),height:v.height.toString(),playerVars:{autoplay:1,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,annotations:0}},onReady:b=>m(b.target)}),!r&&n.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[n.jsxs("button",{onClick:()=>y==null?void 0:y.playVideo(),children:[n.jsx(W.NtdPlay,{size:14})," ",o("youtubePlayer.play","Play")]}),n.jsxs("button",{onClick:()=>y==null?void 0:y.pauseVideo(),children:[n.jsx(W.NtdPause,{size:14})," ",o("youtubePlayer.pause","Pause")]})]})]})]})},ei=e=>({name:e,dirs:new Map,files:[]}),Hp=e=>(e??[]).map(t=>t instanceof File?{file:t}:t),Kp=e=>e.replace(/\\/g,"/"),Yp=e=>{const t=ei("/");for(const r of e){const a=Kp(r.path??r.file.name).split("/").filter(Boolean);if(a.length<=1){t.files.push({file:r.file,path:a[0]??r.file.name});continue}let s=t;for(let i=0;i<a.length-1;i++){const o=a[i];s.dirs.has(o)||s.dirs.set(o,ei(o)),s=s.dirs.get(o)}s.files.push({file:r.file,path:a[a.length-1]??r.file.name})}return t},fa=e=>e.slice().sort((t,r)=>(t.path??t.file.name).localeCompare(r.path??r.file.name)),Xp={tidal:W.NtdWave,spotify:W.NtdMusic,youtube:W.NtdPlay},ma=({q:e,setQ:t,t:r})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[n.jsx("div",{style:{flex:1},children:n.jsx(Ce.NiceTextInput,{value:e,onChange:t,placeholder:r("libraryExplorer.searchPlaceholder","Search…"),size:"sm"})}),e&&n.jsx(Ce.NiceButton,{variant:"ghost",size:"sm",onClick:()=>t(""),children:n.jsx(W.NtdClose,{size:14})})]}),ga=({files:e,t,onOpenInEditor:r,onPlayFile:a})=>e.length?n.jsx("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{color:"var(--nice-text-muted, #94a3b8)",textAlign:"left"},children:[n.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colFile","File")}),n.jsx("th",{style:{padding:"8px 12px",fontWeight:600},children:t("libraryExplorer.colType","Type")}),n.jsx("th",{style:{padding:"8px 12px",fontWeight:600,width:200},children:t("libraryExplorer.colActions","Actions")})]})}),n.jsx("tbody",{children:e.map(s=>{const i=s.path??s.file.name;return n.jsxs("tr",{style:{borderTop:"1px solid var(--nice-border, #1e293b)"},children:[n.jsx("td",{style:{padding:"6px 12px",maxWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),n.jsx("td",{style:{padding:"6px 12px",color:"var(--nice-text-muted, #94a3b8)"},children:s.file.type||"—"}),n.jsxs("td",{style:{padding:"6px 12px",display:"flex",gap:6},children:[r&&n.jsxs(Ce.NiceButton,{variant:"outline",size:"sm",onClick:()=>r(s.file),children:[n.jsx(W.NtdEdit,{size:13})," ",t("libraryExplorer.openInEditor","Edit")]}),a&&n.jsxs(Ce.NiceButton,{variant:"primary",size:"sm",onClick:()=>a(s.file),children:[n.jsx(W.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]})]},i)})})]})}):n.jsx("div",{style:{fontSize:13,color:"var(--nice-text-muted, #94a3b8)",padding:12},children:t("libraryExplorer.noFiles","No files")}),sl=({streams:e,t,onPlayStream:r})=>e.length?n.jsxs("div",{style:{borderRadius:12,border:"1px solid var(--nice-border, #334155)",overflow:"hidden"},children:[n.jsx("div",{style:{padding:"8px 12px",fontSize:13,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:t("libraryExplorer.streaming","Streaming")}),n.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.map(a=>n.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderTop:"1px solid var(--nice-border, #1e293b)",padding:"8px 12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-muted, #94a3b8)",display:"flex",alignItems:"center",gap:4},children:[u.createElement(Xp[a.provider],{size:12})," ",a.provider.toUpperCase(),a.artist?` • ${a.artist}`:""]})]}),r&&n.jsxs(Ce.NiceButton,{variant:"primary",size:"sm",onClick:()=>r(a),children:[n.jsx(W.NtdPlay,{size:13})," ",t("libraryExplorer.play","Play")]})]},`${a.provider}:${a.id}`))})]}):null,Jr=({name:e,enabled:t})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",fontSize:13},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:t?"var(--nice-success, #10b981)":"var(--nice-border, #d1d5db)"}}),n.jsx("span",{style:{color:t?"inherit":"var(--nice-text-muted, #94a3b8)"},children:e})]}),Zp=({variant:e="full",files:t=[],streams:r=[],enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,t:c,style:d,id:h,accessMode:f,"data-testid":p})=>{const{t:y}=Te(),m=c??y,[x,v]=u.useState(""),g=u.useMemo(()=>Hp(t),[t]),S=u.useCallback(j=>{const N=x.trim().toLowerCase();return!N||j.toLowerCase().includes(N)},[x]),b=u.useMemo(()=>fa(g).filter(j=>S(`${j.path??j.file.name} ${j.file.type||""}`)),[g,S]),k=u.useMemo(()=>r.filter(j=>S(`${j.title} ${j.artist??""} ${j.provider}`)),[r,S]);return f==="hidden"?null:e==="minimal"?n.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[n.jsx(ma,{q:x,setQ:v,t:m}),n.jsx(ga,{files:b,t:m,onOpenInEditor:s,onPlayFile:i}),n.jsx(sl,{streams:k,t:m,onPlayStream:o})]}):e==="onlyFiles"?n.jsxs("div",{className:l,style:{display:"flex",flexDirection:"column",gap:12,...d},id:h,"data-testid":p,children:[n.jsx(ma,{q:x,setQ:v,t:m}),n.jsx(ga,{files:b,t:m,onOpenInEditor:s,onPlayFile:i})]}):n.jsx(Qp,{q:x,setQ:v,normFiles:g,filteredStreams:k,enableProviders:a,onOpenInEditor:s,onPlayFile:i,onPlayStream:o,className:l,style:d,id:h,"data-testid":p,t:m})},Qp=({q:e,setQ:t,normFiles:r,filteredStreams:a,enableProviders:s,onOpenInEditor:i,onPlayFile:o,onPlayStream:l,className:c,style:d,id:h,"data-testid":f,t:p})=>{const y=u.useMemo(()=>Yp(r),[r]),[m,x]=u.useState({}),[v,g]=u.useState("/"),S=N=>x(R=>({...R,[N]:!R[N]})),b=(N,R)=>{const w=R==="/"?`/${N.name}`:`${R}${N.name}/`,M=R==="/"&&N.name==="/",I=m[w]??M,A=Array.from(N.dirs.keys()).sort();return n.jsxs("div",{children:[!M&&n.jsxs("button",{type:"button",onClick:()=>{S(w),g(w)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 8px",border:"none",borderRadius:6,cursor:"pointer",textAlign:"left",background:v===w?"var(--nice-accent-tint-20, rgba(99,102,241,0.2))":"transparent",color:"var(--nice-text, inherit)"},children:[n.jsx("span",{style:{display:"inline-flex"},children:I?n.jsx(W.NtdFolderOpen,{size:14}):n.jsx(W.NtdFolder,{size:14})}),n.jsx("span",{style:{fontSize:13},children:N.name})]}),(M||I)&&n.jsx("div",{style:{paddingLeft:M?0:16},children:A.map(T=>b(N.dirs.get(T),w))})]},w)},k=u.useMemo(()=>{let N;if(v==="/")N=fa(r);else{const R=v.replace(/^\//,"").split("/").filter(Boolean);let w=y;for(const M of R){const I=w.dirs.get(M);if(!I)return[];w=I}N=fa(w.files)}return e?N.filter(R=>(R.path??R.file.name).toLowerCase().includes(e.toLowerCase())):N},[v,y,r,e]),j={tidal:(s==null?void 0:s.tidal)??!0,spotify:(s==null?void 0:s.spotify)??!0,youtube:(s==null?void 0:s.youtube)??!0};return n.jsxs("div",{className:c,style:{display:"flex",gap:12,color:"var(--nice-text, #e2e8f0)",...d},id:h,"data-testid":f,children:[n.jsxs("div",{style:{flex:"0 0 220px",border:"1px solid var(--nice-border, #334155)",borderRadius:12,padding:8},children:[n.jsx("div",{style:{padding:"0 8px 8px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:p("libraryExplorer.library","Library")}),b(y,"/"),n.jsxs("div",{style:{marginTop:16,borderTop:"1px solid var(--nice-border, #1e293b)",paddingTop:8},children:[n.jsx("div",{style:{padding:"0 8px 4px",fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)"},children:p("libraryExplorer.streaming","Streaming")}),n.jsx(Jr,{name:"Tidal",enabled:j.tidal}),n.jsx(Jr,{name:"Spotify",enabled:j.spotify}),n.jsx(Jr,{name:"YouTube",enabled:j.youtube})]})]}),n.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[n.jsx(ma,{q:e,setQ:t,t:p}),n.jsx(ga,{files:k,t:p,onOpenInEditor:i,onPlayFile:o}),(j.tidal||j.spotify||j.youtube)&&n.jsx(sl,{streams:a.filter(N=>j[N.provider]),t:p,onPlayStream:l})]})]})},Jp=({kind:e,color:t})=>{const r={width:14,height:14,viewBox:"0 0 24 24",fill:t,"aria-hidden":!0};switch(e){case"youtube":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M23 7.2s-.2-1.6-.9-2.3c-.8-.9-1.7-.9-2.1-1C16.9 3.5 12 3.5 12 3.5s-4.9 0-8 .4c-.4.1-1.3.1-2.1 1C1.2 5.6 1 7.2 1 7.2S.8 9.1.8 11v1.8c0 1.9.2 3.8.2 3.8s.2 1.6.9 2.3c.8.9 1.9.9 2.4 1 1.7.2 7.7.4 7.7.4s4.9 0 8-.4c.4-.1 1.3-.1 2.1-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.8V11c0-1.9-.2-3.8-.2-3.8zM9.7 14.6V8.2l6.3 3.2-6.3 3.2z"})});case"spotify":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.59 14.42c-.18.3-.57.4-.87.21-2.39-1.46-5.4-1.79-8.95-.98-.34.08-.68-.13-.76-.47-.08-.34.13-.68.47-.76 3.88-.89 7.21-.5 9.89 1.13.31.19.4.58.22.87zm1.23-2.72c-.23.37-.71.49-1.08.26-2.74-1.69-6.92-2.18-10.16-1.19-.41.13-.85-.11-.97-.52-.13-.41.11-.85.52-.97 3.7-1.12 8.31-.58 11.45 1.34.37.23.49.71.24 1.08zm.11-2.84C14.55 8.84 9.5 8.66 6.43 9.6c-.49.15-1.01-.13-1.16-.62-.15-.49.13-1.01.62-1.16 3.52-1.07 9.1-.86 12.69 1.27.43.26.57.82.31 1.25-.26.43-.82.57-1.25.31z"})});case"tidal":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 2L8 6l4 4 4-4-4-4zM4 6L0 10l4 4 4-4-4-4zm16 0l-4 4 4 4 4-4-4-4zm-8 8l-4 4 4 4 4-4-4-4z"})});case"hls":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M2 12h2v6H2v-6zm4-4h2v10H6V8zm4-4h2v14h-2V4zm4 4h2v10h-2V8zm4 4h2v6h-2v-6z"})});case"audio":default:return n.jsx("svg",{...r,children:n.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"})})}},as=({data:e,display:t,callbacks:r,state:a})=>{const{id:s,index:i,artist:o,title:l,version:c,lp:d,sourcesAvailable:h=[]}=e,{allowVersion:f=!0,dragHandleProps:p}=t,{onChange:y,onRemove:m,onMoveUp:x,onMoveDown:v,onChangeLp:g,onSelectSource:S}=r,{readOnly:b=!1,canMoveUp:k=!0,canMoveDown:j=!0,activeSource:N}=a,{t:R}=Te(),w=u.useRef(null);u.useEffect(()=>{!o&&w.current&&w.current.focus()},[o]);const M=O=>{if(!b&&O.key==="Enter"){const E=O.target.closest("div.gpi-row"),V=E==null?void 0:E.querySelectorAll("input[data-role='field']");if(!V||V.length===0)return;const ee=Array.from(V).indexOf(O.target),z=V[ee+1]??V[0];z==null||z.focus()}},I=O=>{const E=h.includes(O),V=N===O,ee={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid var(--nice-border, #e5e7eb)",background:V?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)",opacity:E?1:.35,cursor:E&&S&&!b?"pointer":"default",transition:"transform .05s ease"},z=O==="youtube"?"var(--nice-danger, #ff0000)":O==="spotify"?"var(--nice-success, #1db954)":O==="tidal"?"var(--nice-text, #111827)":O==="hls"?"var(--nice-accent, #7c3aed)":"var(--nice-text, #374151)",q=O==="youtube"?"YouTube":O==="spotify"?"Spotify":O==="tidal"?"TIDAL":O==="hls"?"HLS":"Audio",K=R("playlistItem.sourceLabel","Source")+": "+q+(V?` ${R("playlistItem.sourceSelected","(selected)")}`:""),re=()=>{!E||!S||b||S(O)};return n.jsx("button",{type:"button",title:q,onClick:re,disabled:!E||b,style:ee,"aria-pressed":V,"aria-label":K,children:n.jsx(Jp,{kind:O,color:z})},O)},A=["youtube","tidal","spotify","hls","audio"],T=typeof d=="number"?d:i+1;return n.jsxs("div",{className:"gpi-row",role:"group","aria-label":R("playlistItem.trackNumber","Track")+" "+(i+1),style:{display:"grid",gridTemplateColumns:f?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[n.jsx("input",{type:"number",min:1,value:T,onChange:O=>g==null?void 0:g(Number(O.target.value)),disabled:b||!g,"aria-label":"Lp",title:R("playlistItem.positionOnList","Position in the list"),style:ef}),n.jsx("input",{ref:w,"data-role":"field",type:"text",value:o,onChange:O=>y({artist:O.target.value}),placeholder:"Artist",onKeyDown:M,disabled:b,"aria-label":"Artist",className:"gpi-input",style:ea}),n.jsx("input",{"data-role":"field",type:"text",value:l,onChange:O=>y({title:O.target.value}),placeholder:"Title",onKeyDown:M,disabled:b,"aria-label":"Title",className:"gpi-input",style:ea}),f&&n.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:O=>y({version:O.target.value||void 0}),placeholder:R("playlistItem.versionOptional","Version (optional)"),onKeyDown:M,disabled:b,"aria-label":"Version",className:"gpi-input",style:ea}),n.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":R("playlistItem.availableSources","Available sources"),children:A.map(I)}),n.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[p&&n.jsx("button",{type:"button",...p,draggable:!0,"aria-label":R("playlistItem.dragReorder","Drag to reorder"),title:R("playlistItem.dragReorder","Drag to reorder"),style:tr,children:n.jsx(W.NtdMenu,{size:14})}),n.jsx("button",{type:"button",onClick:x,disabled:!k||b,"aria-label":R("playlistItem.moveUp","Move up"),title:R("playlistItem.moveUp","Move up"),style:tr,children:n.jsx(W.NtdArrowUp,{size:14})}),n.jsx("button",{type:"button",onClick:v,disabled:!j||b,"aria-label":R("playlistItem.moveDown","Move down"),title:R("playlistItem.moveDown","Move down"),style:tr,children:n.jsx(W.NtdArrowDown,{size:14})}),n.jsx("button",{type:"button",onClick:m,disabled:b,"aria-label":R("common.delete","Delete"),title:R("common.delete","Delete"),style:{...tr,color:"var(--nice-color-danger, #b91c1c)"},children:n.jsx(W.NtdClose,{size:14})})]})]})},ef={width:48,border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},ea={width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:"8px 10px",fontSize:14},tr={border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},ya=()=>Math.random().toString(36).slice(2,10),nr=e=>(e??[]).map(t=>({id:ya(),...t})),tf=e=>e.map(({id:t,...r})=>r),nf=null,rf=e=>{const t=e.trim();if(!t)return null;const r=t.split(/\s[-–—]\s/);if(r.length<2){const o=t.split(/[;|]/).map(l=>l.trim());return o.length>=2?{artist:o[0],title:o[1],version:o[2]||void 0}:null}const a=r[0].trim(),s=r.slice(1).join(" - ").trim(),i=s.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(i){const o=i[1].trim(),l=i[2].trim();return{artist:a,title:o,version:l||void 0}}return{artist:a,title:s,version:void 0}},il=({value:e,defaultValue:t,onChange:r,allowVersion:a=!0,maxItems:s,addButtonLabel:i,emptyState:o=nf,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:h}=Te(),f=e!==void 0,[p,y]=u.useState(()=>nr(e||t)),[m,x]=u.useState(""),v=u.useRef(null),[g,S]=u.useState(null);u.useEffect(()=>{f&&y(nr(e))},[f,JSON.stringify(e)]);const b=u.useCallback(K=>{r==null||r(tf(K))},[r]),k=u.useCallback(K=>{if(f){const re=K(nr(e));b(re)}else y(re=>{const _=K(re);return b(_),_})},[b,f,e]),j=s?p.length<s:!0,N=u.useCallback(()=>{!j||l||k(K=>[...K,{id:ya(),artist:"",title:"",version:void 0}])},[j,l,k]),R=u.useCallback((K,re)=>{k(_=>_.map(U=>U.id===K?{...U,...re}:U))},[k]),w=u.useCallback(K=>{l||k(re=>re.filter(_=>_.id!==K))},[l,k]),M=u.useCallback((K,re)=>{k(_=>{const U=_.findIndex(D=>D.id===K);if(U<0)return _;const $=U+re;if($<0||$>=_.length)return _;const P=[..._],[F]=P.splice(U,1);return P.splice($,0,F),P})},[k]),I=u.useCallback((K,re)=>{k(_=>{const U=_.findIndex(D=>D.id===K);if(U<0)return _;const $=Math.max(0,Math.min(_.length-1,re-1));if(U===$)return _;const P=[..._],[F]=P.splice(U,1);return P.splice($,0,F),P})},[k]),A=K=>re=>{l||(v.current=K,re.dataTransfer.effectAllowed="move",re.dataTransfer.setData("text/plain",K))},T=K=>re=>{l||(re.preventDefault(),re.dataTransfer.dropEffect="move",S(K))},O=K=>()=>S(re=>re===K?null:re),E=K=>re=>{if(l)return;re.preventDefault();const _=v.current??re.dataTransfer.getData("text/plain");S(null),v.current=null,!(!_||_===K)&&k(U=>{const $=U.findIndex(C=>C.id===_),P=U.findIndex(C=>C.id===K);if($<0||P<0||$===P)return U;const F=[...U],[D]=F.splice($,1);return F.splice(P,0,D),F})},V=()=>{v.current=null,S(null)},ee=u.useCallback(()=>{if(!d||l)return;const re=m.split(/\r?\n/).map(_=>_.trim()).filter(Boolean).map(rf).filter(_=>!!_);re.length!==0&&(k(_=>{const U=(s??1/0)-_.length,$=re.slice(0,Math.max(0,U)).map(P=>({id:ya(),...P}));return[..._,...$]}),x(""))},[d,l,m,s,k]);u.useEffect(()=>{},[p.length,c]);const z=o??n.jsx("div",{style:{padding:"0.75rem",color:"var(--nice-text-secondary, #777)",fontStyle:"italic"},children:h("genericPlaylist.emptyState","No songs. Add the first one below.")}),q=i??h("genericPlaylist.addSong","Add song");return n.jsxs("div",{className:"gp-container",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[n.jsx("h3",{style:{margin:0,fontSize:16},children:h("genericPlaylist.playlist","Playlist")}),n.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:n.jsxs("button",{type:"button",onClick:N,disabled:!j||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},"aria-label":q,children:["+ ",q]})})]}),p.length===0?n.jsx("div",{className:"gp-empty",children:z}):n.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:p.map((K,re)=>{const _=g===K.id;return n.jsx("li",{draggable:!l,onDragStart:A(K.id),onDragOver:T(K.id),onDragLeave:O(K.id),onDrop:E(K.id),onDragEnd:V,style:{border:_?"2px dashed var(--nice-info, #6366f1)":"2px solid transparent",borderRadius:8,padding:_?4:0},children:n.jsx(as,{data:{id:K.id,index:re,lp:re+1,artist:K.artist,title:K.title,version:a?K.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:a,dragHandleProps:{onDragStart:A(K.id)}},callbacks:{onChange:U=>R(K.id,U),onRemove:()=>w(K.id),onMoveUp:()=>M(K.id,-1),onMoveDown:()=>M(K.id,1),onChangeLp:U=>I(K.id,U)},state:{readOnly:l,canMoveUp:re>0,canMoveDown:re<p.length-1}})},K.id)})}),d&&!l&&n.jsx("div",{style:{marginTop:12},children:n.jsxs("details",{children:[n.jsx("summary",{style:{cursor:"pointer",color:"var(--nice-text, #374151)"},children:h("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),n.jsxs("div",{style:{marginTop:6},children:[n.jsx("textarea",{value:m,onChange:K=>x(K.target.value),placeholder:h("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
65
65
  Artist - Title (Version)
66
- Artist � Title [Remastered 2011]
67
- OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[r.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),r.jsx("button",{type:"button",onClick:Z,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},Js=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],tr=["??","??","??","??","??","??","??","??","??","?","??","??","??","??","??","??"],il=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=Te(),[c,u]=d.useState(null),[h,p]=d.useState(""),[f,y]=d.useState(Js[8]),[m,v]=d.useState(tr[0]),[x,g]=d.useState(!1),[k,b]=d.useState(null),[S,M]=d.useState(""),[R,N]=d.useState(""),[C,w]=d.useState(""),O=d.useCallback(A=>{u(A.id),M(A.name),N(A.color),w(A.icon||tr[0])},[]),$=d.useCallback(()=>{c&&S.trim()&&(n(c,S.trim(),R,C),u(null))},[c,S,R,C,n]),E=d.useCallback(()=>{h.trim()&&(t(h.trim(),f,m),p(""),g(!1))},[h,f,m,t]),_=d.useCallback(A=>{k===A?(a(A),b(null)):(b(A),setTimeout(()=>b(null),3e3))},[k,a]),L=s&&s.length>0,U=A=>!s||s.length===0?!1:s.every(q=>q.tags.includes(A)),Z=A=>!s||s.length===0?!1:s.some(q=>q.tags.includes(A))&&!U(A);return r.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--surface-bg, #f9fafb)"},children:[r.jsx("span",{style:{fontSize:"1rem"},children:"???"}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager")}),r.jsx("div",{style:{flex:1}}),r.jsxs("button",{onClick:()=>g(!x),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag")]})]}),r.jsxs("div",{style:{padding:12},children:[x&&r.jsxs("div",{style:{border:"1px solid var(--border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--surface-bg, #f9fafb)"},children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:h,onChange:A=>p(A.target.value),placeholder:l("playlistManager.tagName"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)"},onKeyDown:A=>A.key==="Enter"&&E()}),r.jsx("button",{onClick:E,disabled:!h.trim(),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},children:"?"})]}),r.jsxs("div",{style:{marginBottom:6},children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:Js.map(A=>r.jsx("div",{onClick:()=>y(A),style:{width:20,height:20,borderRadius:"50%",background:A,cursor:"pointer",border:f===A?"3px solid var(--accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},A))})]}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon")}),r.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:tr.map(A=>r.jsx("div",{onClick:()=>v(A),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===A?"var(--accent-bg, #eff6ff)":"transparent",border:m===A?"1px solid var(--accent, #3b82f6)":"1px solid transparent"},children:A},A))})]})]}),L&&r.jsx("div",{style:{padding:"6px 10px",background:"var(--accent-bg, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--accent, #3b82f6)"},children:l("playlistManager.bulkTagHint")+": "+s.length}),e.length===0?r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags")}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(A=>r.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border-color, #e5e7eb)",background:c===A.id?"var(--surface-bg, #f9fafb)":"transparent"},children:c===A.id?r.jsxs(r.Fragment,{children:[r.jsx("select",{value:C,onChange:q=>w(q.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:tr.map(q=>r.jsx("option",{value:q,children:q},q))}),r.jsx("input",{type:"color",value:R,onChange:q=>N(q.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),r.jsx("input",{type:"text",value:S,onChange:q=>M(q.target.value),style:{flex:1,padding:"3px 8px",borderRadius:4,border:"1px solid var(--border-color, #d1d5db)",fontSize:"0.78rem",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)"},onKeyDown:q=>q.key==="Enter"&&$()}),r.jsx("button",{onClick:$,style:nr("var(--accent, #3b82f6)"),children:"?"}),r.jsx("button",{onClick:()=>u(null),style:nr("var(--text-secondary, #9ca3af)"),children:"?"})]}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${A.color}18`,color:A.color,fontWeight:600,fontSize:"0.78rem"},children:[A.icon&&r.jsx("span",{children:A.icon}),A.name]}),L&&i&&o&&r.jsx("input",{type:"checkbox",checked:U(A.id),ref:q=>{q&&(q.indeterminate=Z(A.id))},onChange:()=>{const q=s.map(H=>H.id);U(A.id)?o(q,A.id):i(q,A.id)},style:{cursor:"pointer"}}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{onClick:()=>O(A),style:nr("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"?"}),r.jsx("button",{onClick:()=>_(A.id),style:nr(k===A.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:k===A.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:k===A.id?"?":"??"})]})},A.id))})]})]})},nr=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var rs=(e=>(e.Static="static",e.Dynamic="dynamic",e))(rs||{}),ol=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(ol||{}),ll=(e=>(e.Left="left",e.Right="right",e))(ll||{}),ot=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(ot||{}),lt=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(lt||{}),cl=(e=>(e.Title="title",e.Artist="artist",e.Album="album",e.Duration="duration",e.AddedDate="addedDate",e.Year="year",e.Rating="rating",e.Custom="custom",e))(cl||{}),sn=(e=>(e.Asc="asc",e.Desc="desc",e))(sn||{}),kt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(kt||{});const Jp=[{value:ot.Artist,label:"Artist"},{value:ot.Title,label:"Title"},{value:ot.Album,label:"Album"},{value:ot.Genre,label:"Genre"},{value:ot.Year,label:"Year"},{value:ot.Duration,label:"Duration (s)"},{value:ot.Rating,label:"Rating"},{value:ot.PlayCount,label:"Play Count"},{value:ot.Tag,label:"Tag"},{value:ot.Source,label:"Source"},{value:ot.AddedDate,label:"Added Date"}],ef=[{value:lt.Equals,label:"="},{value:lt.NotEquals,label:"≠"},{value:lt.Contains,label:"contains"},{value:lt.NotContains,label:"not contains"},{value:lt.StartsWith,label:"starts with"},{value:lt.GreaterThan,label:">"},{value:lt.LessThan,label:"<"},{value:lt.Between,label:"between"},{value:lt.In,label:"in"},{value:lt.NotIn,label:"not in"}];function tf(e){return"logic"in e&&"rules"in e}function ya(){return{id:crypto.randomUUID(),field:ot.Artist,operator:lt.Contains,value:""}}function dl(){return{id:crypto.randomUUID(),logic:"and",rules:[ya()]}}const nf=({rule:e,onChange:t,onRemove:n})=>r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:a=>t({...e,field:a.target.value}),children:Jp.map(a=>r.jsx("option",{value:a.value,children:a.label},a.value))}),r.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:a=>t({...e,operator:a.target.value}),children:ef.map(a=>r.jsx("option",{value:a.value,children:a.label},a.value))}),r.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:a=>t({...e,value:a.target.value})}),e.operator===lt.Between&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-muted",children:"–"}),r.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:a=>t({...e,value2:a.target.value})})]}),r.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove rule","aria-label":"Remove rule",children:r.jsx(se.NtdClose,{size:14})})]}),ul=({group:e,onChange:t,onRemove:n,depth:a=0})=>{const{t:s}=Te(),i=d.useCallback((p,f)=>{const y=[...e.rules];y[p]=f,t({...e,rules:y})},[e,t]),o=d.useCallback(p=>{const f=e.rules.filter((y,m)=>m!==p);t({...e,rules:f.length>0?f:[ya()]})},[e,t]),l=d.useCallback(()=>{t({...e,rules:[...e.rules,ya()]})},[e,t]),c=d.useCallback(()=>{t({...e,rules:[...e.rules,dl()]})},[e,t]),u=d.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return r.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,backgroundColor:a%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[r.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[r.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:u,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),r.jsx("span",{className:"text-muted small",children:s("playlistManager.matchAll","Match all / any of these rules")}),r.jsxs("div",{className:"ms-auto d-flex gap-1",children:[r.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),a<3&&r.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),n&&r.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove group","aria-label":"Remove group",children:r.jsx(se.NtdClose,{size:14})})]})]}),e.rules.map((p,f)=>tf(p)?r.jsx(ul,{group:p,onChange:y=>i(f,y),onRemove:()=>o(f),depth:a+1},p.id):r.jsx(nf,{rule:p,onChange:y=>i(f,y),onRemove:()=>o(f)},p.id))]})},hl=({rules:e,onChange:t,limit:n,onLimitChange:a})=>{const{t:s}=Te(),i=e??dl();return r.jsxs("div",{className:"border rounded p-3",children:[r.jsxs("h6",{className:"mb-3",children:[r.jsx(se.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),r.jsx("p",{className:"text-muted small mb-3",children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),r.jsx(ul,{group:i,onChange:t}),a&&r.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[r.jsx("label",{className:"form-label mb-0 small",children:s("playlistManager.maxTracks","Max tracks:")}),r.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:n??"",placeholder:"∞",onChange:o=>{const l=parseInt(o.target.value,10);a(isNaN(l)||l<=0?void 0:l)}}),r.jsx("span",{className:"text-muted small",children:s("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},ei=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},rf={library:"??",spotify:"??",tidal:"?",youtube:"??",musicbrainz:"??",import:"??",manual:"?"},as=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:u,sortDir:h,onSortChange:p,filterText:f,onFilterChange:y,compact:m=!1,draggable:v=!1,onDragStart:x,dropTarget:g=!1,onDrop:k})=>{const{t:b}=Te(),[S,M]=d.useState(null),[R,N]=d.useState(null),C=d.useRef(null),w=d.useMemo(()=>{let j=e??[];if(f.trim()){const F=f.toLowerCase();j=j.filter(I=>{var P,T;return I.title.toLowerCase().includes(F)||I.artist.toLowerCase().includes(F)||((P=I.album)==null?void 0:P.toLowerCase().includes(F))||((T=I.genre)==null?void 0:T.toLowerCase().includes(F))})}return[...j].sort((F,I)=>{const P=h==="asc"?1:-1;switch(u){case"title":return P*F.title.localeCompare(I.title);case"artist":return P*F.artist.localeCompare(I.artist);case"album":return P*(F.album??"").localeCompare(I.album??"");case"duration":return P*((F.duration??0)-(I.duration??0));case"year":return P*((F.year??0)-(I.year??0));case"rating":return P*((F.rating??0)-(I.rating??0));case"addedDate":return P*(F.addedAt??"").localeCompare(I.addedAt??"");case"custom":return P*((F.customOrder??0)-(I.customOrder??0));default:return 0}})},[e,f,u,h]),O=d.useCallback((j,F)=>{const I=w[j];if(I){if(F.ctrlKey||F.metaKey){const P=new Set(n);P.has(I.id)?P.delete(I.id):P.add(I.id),a(P)}else if(F.shiftKey&&C.current!==null){const P=Math.min(C.current,j),T=Math.max(C.current,j),z=new Set(n);for(let B=P;B<=T;B++)z.add(w[B].id);a(z)}else a(new Set([I.id]));C.current=j}},[w,n,a]),$=d.useCallback(()=>{n.size===w.length?a(new Set):a(new Set(w.map(j=>j.id)))},[w,n,a]),E=({field:j,label:F,width:I})=>{const P=u===j;return r.jsxs("div",{style:{width:I,flex:I?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:P?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:P?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{P?p(j,h===sn.Asc?sn.Desc:sn.Asc):p(j,sn.Asc)},children:[F,P&&r.jsx("span",{children:"?"})]})},_=d.useCallback((j,F)=>{const I=n.has(j.id)?Array.from(n):[j.id];F.dataTransfer.setData("trackIds",JSON.stringify(I)),F.dataTransfer.effectAllowed="move",x==null||x(I,F)},[n,x]),L=d.useCallback((j,F)=>{F.preventDefault(),F.dataTransfer.dropEffect="move",M(j)},[]),U=d.useCallback((j,F)=>{F.preventDefault(),M(null);try{const I=F.dataTransfer.getData("trackIds");if(I&&o){const P=JSON.parse(I),T=w.filter(G=>!P.includes(G.id)),z=w.filter(G=>P.includes(G.id)),B=Math.min(j,T.length);T.splice(B,0,...z),o(T.map(G=>G.id))}}catch{}},[w,o]),Z=d.useCallback(j=>{j.preventDefault(),M(null),k==null||k(j)},[k]),A=d.useMemo(()=>new Map(t.map(j=>[j.id,j])),[t]),q=j=>j.replace(/[^a-z0-9_-]/gi,"-"),H=m?36:48,re={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},D=(j,F)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:H,cursor:"pointer",background:F?"var(--accent-light, #dbeafe)":j?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),W=w.length>0&&n.size===w.length;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:g?j=>{j.preventDefault(),j.dataTransfer.dropEffect="copy"}:void 0,onDrop:g?Z:void 0,children:[r.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[r.jsx("input",{type:"text",value:f,onChange:j=>y(j.target.value),placeholder:"?? "+b("playlistManager.filterTracks"),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #f9fafb)",color:"var(--text-primary, #1f2937)"}}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[w.length,"/",(e??[]).length]}),n.size>0&&i&&r.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--error, #ef4444)",background:"transparent",color:"var(--error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(n)),children:["?? ",n.size]})]}),r.jsxs("div",{style:re,children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:W,onChange:$,style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20},children:"#"}),!m&&r.jsx("div",{style:{width:44}}),r.jsx(E,{field:"title",label:b("playlistManager.colTitle")}),r.jsx(E,{field:"artist",label:b("playlistManager.colArtist")}),!m&&r.jsx(E,{field:"album",label:b("playlistManager.colAlbum")}),r.jsx(E,{field:"duration",label:b("playlistManager.colDuration"),width:60}),!m&&r.jsx(E,{field:"year",label:b("playlistManager.colYear"),width:50}),r.jsx("div",{style:{width:30}})," ",!m&&r.jsx("div",{style:{width:60}})," ",r.jsx("div",{style:{width:24}})," "]}),r.jsxs("div",{style:{flex:1,overflow:"auto"},children:[w.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist"):b("playlistManager.noMatchingTracks")}),w.map((j,F)=>{const I=n.has(j.id),P=S===F;return r.jsxs("div",{style:D(I,P),onClick:T=>O(F,T),onDoubleClick:()=>s==null?void 0:s(j),draggable:v,onDragStart:T=>_(j,T),onDragOver:T=>L(F,T),onDrop:T=>U(F,T),onDragLeave:()=>M(null),children:[r.jsx("div",{style:{width:28},children:r.jsx("input",{type:"checkbox",checked:I,onChange:()=>{const T=new Set(n);I?T.delete(j.id):T.add(j.id),a(T)},onClick:T=>T.stopPropagation(),style:{cursor:"pointer"}})}),r.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:F+1}),!m&&r.jsx("div",{style:{width:44,height:36,flexShrink:0},children:j.coverUrl?r.jsx("img",{src:j.coverUrl,alt:j.title||b("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):r.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--surface-bg, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:"??"})}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:j.title}),r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:j.artist}),!m&&r.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:j.album}),r.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ei(j.duration)}),!m&&r.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:j.year||""}),r.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:j.source,children:rf[j.source]??"?"}),!m&&r.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[j.tags.slice(0,2).map(T=>{const z=A.get(T);if(!z)return null;const B=`--tag-${q(T)}`;return r.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${B}-bg, ${z.color}22)`,color:`var(${B}, ${z.color})`,whiteSpace:"nowrap"},children:z.name},T)}),j.tags.length>2&&r.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",j.tags.length-2]})]}),r.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:T=>{T.stopPropagation(),N(R===j.id?null:j.id)},title:b("playlistManager.morActions"),children:"?"}),R===j.id&&t.length>0&&r.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--card-bg, #fff)",border:"1px solid var(--border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.assignTag")}),t.map(T=>{const z=j.tags.includes(T.id);return r.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:z?`var(--tag-${q(T.id)}-bg, ${T.color}22)`:"transparent"},onClick:B=>{B.stopPropagation();const G=n.size>0?Array.from(n):[j.id];z||l==null||l(G,[T.id]),N(null)},children:[r.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${q(T.id)}, ${T.color})`,flexShrink:0}}),r.jsx("span",{children:T.name}),z&&r.jsx("span",{style:{marginLeft:"auto"},children:"?"})]},T.id)})]})]})]},j.id)})]}),r.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[r.jsxs("span",{children:[w.length," ",b("playlistManager.tracks")]}),r.jsx("span",{children:ei(w.reduce((j,F)=>j+(F.duration??0),0))}),n.size>0&&r.jsxs("span",{children:[n.size," ",b("playlistManager.selected")]})]})]})},ti=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),pl=({playlists:e=[],tags:t=[],onCopyTracks:n=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:u,library:h,queue:p,onAddToQueue:f,onRemoveFromQueue:y})=>{const{t:m}=Te(),[v,x]=d.useState(()=>ti(c??null)),[g,k]=d.useState(()=>ti(u??null)),[b,S]=d.useState("left"),[M,R]=d.useState(null),[N,C]=d.useState(50),[w,O]=d.useState(!1),$=d.useMemo(()=>e.find(P=>P.id===v.playlistId),[e,v.playlistId]),E=d.useMemo(()=>e.find(P=>P.id===g.playlistId),[e,g.playlistId]),_=d.useCallback((P,T)=>{P==="left"?x(z=>({...z,...T})):k(z=>({...z,...T}))},[]),L=d.useCallback(P=>P==="left"?v:g,[v,g]),U=P=>P==="left"?"right":"left",Z=d.useCallback(P=>{const T=L(P),z=L(U(P));!T.playlistId||!z.playlistId||T.selectedTrackIds.size===0||(n(T.playlistId,z.playlistId,Array.from(T.selectedTrackIds)),_(P,{selectedTrackIds:new Set}))},[L,n,_]),A=d.useCallback(P=>{const T=L(P),z=L(U(P));!T.playlistId||!z.playlistId||T.selectedTrackIds.size===0||(a(T.playlistId,z.playlistId,Array.from(T.selectedTrackIds)),_(P,{selectedTrackIds:new Set}))},[L,a,_]),q=d.useCallback(P=>{const T=L(P);!T.playlistId||T.selectedTrackIds.size===0||R({operation:"copy",sourcePlaylistId:T.playlistId,trackIds:Array.from(T.selectedTrackIds)})},[L]),H=d.useCallback(P=>{const T=L(P);!T.playlistId||T.selectedTrackIds.size===0||R({operation:"cut",sourcePlaylistId:T.playlistId,trackIds:Array.from(T.selectedTrackIds)})},[L]),re=d.useCallback(P=>{const T=L(P);!M||!T.playlistId||(M.operation==="copy"?n(M.sourcePlaylistId,T.playlistId,M.trackIds):a(M.sourcePlaylistId,T.playlistId,M.trackIds),R(null))},[M,L,n,a]),D=d.useCallback(P=>{P.key==="Tab"&&!P.shiftKey&&(P.preventDefault(),S(T=>U(T))),(P.ctrlKey||P.metaKey)&&P.key==="c"&&q(b),(P.ctrlKey||P.metaKey)&&P.key==="x"&&H(b),(P.ctrlKey||P.metaKey)&&P.key==="v"&&re(b)},[b,q,H,re]),W=d.useCallback(()=>O(!0),[]),j=d.useCallback(P=>{if(!w)return;const T=P.currentTarget.getBoundingClientRect(),z=(P.clientX-T.left)/T.width*100;C(Math.max(20,Math.min(80,z)))},[w]),F=d.useCallback(()=>O(!1),[]),I=P=>{const T=L(P),z=P==="left"?$:E,B=b===P,Y=!!L(U(P)).playlistId;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:B?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>S(P),children:[r.jsx("div",{style:{padding:"8px 12px",background:B?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:B?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:r.jsxs("select",{value:T.playlistId??"",onChange:X=>_(P,{playlistId:X.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:B?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:B?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[r.jsx("option",{value:"",children:m("playlistManager.selectPlaylist")}),e.map(X=>r.jsxs("option",{value:X.id,children:[X.name," (",X.trackCount,")"]},X.id))]})}),r.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border-color, #e5e7eb)",flexWrap:"wrap"},children:[r.jsxs("button",{style:Qr(!1),onClick:()=>Z(P),disabled:!T.playlistId||!Y||T.selectedTrackIds.size===0,title:m("playlistManager.copyToOther"),children:["???"," ",m("playlistManager.copy")]}),r.jsxs("button",{style:Qr(!1),onClick:()=>A(P),disabled:!T.playlistId||!Y||T.selectedTrackIds.size===0,title:m("playlistManager.moveToOther"),children:["??"," ",m("playlistManager.move")]}),r.jsx("div",{style:{flex:1}}),M&&r.jsxs("button",{style:Qr(!0),onClick:()=>re(P),disabled:!T.playlistId,children:["?? ",m("playlistManager.paste")," (",M.trackIds.length,")"]})]}),z?r.jsx(as,{tracks:z.tracks,tags:t,selectedTrackIds:T.selectedTrackIds,onSelectionChange:X=>_(P,{selectedTrackIds:X}),onPlay:o,onRemove:X=>s(z.id,X),onReorder:X=>i(z.id,X),onTagTracks:l,sortField:T.sortField,sortDir:T.sortDir,onSortChange:(X,ie)=>_(P,{sortField:X,sortDir:ie}),filterText:T.filterText,onFilterChange:X=>_(P,{filterText:X}),compact:!0,draggable:!0}):r.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:m("playlistManager.selectPlaylistPrompt")})]})};return r.jsxs("div",{style:{display:"flex",height:"100%",userSelect:w?"none":"auto"},onKeyDown:D,onMouseMove:j,onMouseUp:F,tabIndex:0,children:[r.jsx("div",{style:{width:`${N}%`,minWidth:200},children:I("left")}),r.jsx("div",{style:{width:6,cursor:"col-resize",background:w?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:w?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:W,children:r.jsx("div",{style:{width:2,height:40,borderRadius:1,background:w?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),r.jsx("div",{style:{flex:1,minWidth:200},children:I("right")})]})},Qr=e=>({background:e?"var(--accent, #3b82f6)":"transparent",color:e?"var(--btn-text, #fff)":"var(--text-secondary, #6b7280)",border:e?"none":"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),fl="av:local-playlists";function af(){try{const e=localStorage.getItem(fl);return e?JSON.parse(e):[]}catch{return[]}}function sf(e){const t=JSON.stringify(e);try{localStorage.setItem(fl,t)}catch{}}function ss(){const[e,t]=d.useState(()=>af()),n=d.useRef(!1);return d.useEffect(()=>{n.current=!0},[]),d.useEffect(()=>{sf(e)},[e]),d.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:crypto.randomUUID(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const of=it.scoped("PlaylistList"),lf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},cf={...lf,padding:"8px 10px",cursor:"pointer"},ml={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},df={...ml,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},is=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:a}=Te(),s=ss(),[i,o]=d.useState(""),l=d.useMemo(()=>s.list(),[s]);return r.jsxs("div",{style:{display:"grid",gap:10},children:[r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),r.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?df:{...ml,cursor:"not-allowed",color:"var(--muted, #9ca3af)",background:"var(--bg-muted, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(u){of.error("Remote playlist create failed:",u)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),r.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const u=c.id===e;return r.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...cf,background:u?"var(--active-bg, #eef2ff)":"var(--bg, #fff)"},children:[r.jsx("div",{style:{fontWeight:600},children:c.name}),r.jsxs("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," \\u2022"," ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&r.jsx("div",{style:{color:"var(--muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},uf=it.scoped("PlaylistBrowser"),ni={display:"grid",gap:12},ri=e=>({artist:(e.artists??[]).join(", "),title:e.title}),gl=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n,tracks:a,view:s,onSelect:i,onPlay:o})=>{var x;const{t:l}=Te(),c=ss(),[u,h]=d.useState(null),[p,f]=d.useState(""),[,y]=d.useState([]),m=u==null?void 0:u.id,v=(g,k)=>{if("addItems"in c){c.addItems(g.id,k);const S=c.list().find(M=>M.id===g.id)||g;h(S);return}const b=c;if("update"in c&&typeof b.update=="function"){const S=Array.from([...g.items||[],...k]);b.update({...g,items:S});const M=c.list().find(R=>R.id===g.id)||{...g,items:S};h(M);return}uf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return r.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[r.jsxs("div",{style:ni,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists")}),r.jsx(is,{selectedId:m,onSelect:h}),u&&r.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",r.jsx("strong",{children:u.name})," �"," ",((x=u.items)==null?void 0:x.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),r.jsxs("div",{style:ni,children:[r.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library")}),r.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:g=>{u&&v(u,[ri(g)])}}),r.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:p,onChange:g=>f(g.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:p,onSelect:g=>{u&&v(u,[ri(g)])}}),n==null?void 0:n({onPlayNow:g=>y(g),onAddToQueue:g=>y(k=>[...k,...g]),onAddDescriptors:g=>u&&v(u,g)})]})]})};var qt=(e=>(e[e.None=0]="None",e[e.Spotify=1]="Spotify",e[e.Tidal=2]="Tidal",e[e.YouTube=4]="YouTube",e[e.All=7]="All",e))(qt||{});const yl=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,a)=>n.sortOrder-a.sortOrder).map(n=>({...n,children:yl(e,n.id)})),hf={[qt.Spotify]:{icon:"??",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[qt.Tidal]:{icon:"?",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[qt.YouTube]:{icon:"??",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},bl=({folders:e,playlists:t,tags:n,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:u,onDeleteFolder:h,onCreatePlaylist:p,onConnectService:f,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:v=!1,onToggleCollapse:x})=>{const{t:g}=Te(),[k,b]=d.useState(new Set),[S,M]=d.useState(!1),[R,N]=d.useState(""),[C,w]=d.useState(null),[O,$]=d.useState(!1),[E,_]=d.useState(""),[L,U]=d.useState("static"),[Z,A]=d.useState(null),[q,H]=d.useState(""),[re,D]=d.useState(null),[W,j]=d.useState(!1),F=d.useMemo(()=>yl(e),[e]),I=d.useCallback(J=>{b(de=>{const me=new Set(de);return me.has(J)?me.delete(J):me.add(J),me})},[]),P=d.useCallback(()=>{R.trim()&&(c(R.trim(),C),N(""),M(!1))},[R,C,c]),T=d.useCallback(()=>{E.trim()&&(p(E.trim(),L,s),_(""),$(!1))},[E,L,s,p]),z=d.useCallback(J=>{q.trim()&&(u(J,q.trim()),A(null),H(""))},[q,u]),B=d.useCallback((J,de)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",D(de)},[]),G=d.useCallback((J,de)=>{J.preventDefault();const me=J.dataTransfer.getData("playlistId");me&&m&&m(me,de),D(null)},[m]),Y=d.useCallback(()=>D(null),[]),X=d.useCallback(J=>t.filter(de=>(de.folderId??null)===J),[t]),ie={width:v?48:280,minWidth:v?48:280,background:"var(--sidebar-bg, #f8f9fa)",borderRight:"1px solid var(--border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},le={padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)"},te=(J,de=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:de?"var(--accent-light, #dbeafe)":J?"var(--accent, #3b82f6)":"transparent",color:J?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),V={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},K={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",width:"100%"},oe=(J,de)=>{var Se,ae;const me=k.has(J.id),xe=s===J.id,ce=re===J.id,ye=X(J.id);return r.jsxs("div",{children:[r.jsxs("div",{style:{...te(xe,ce),paddingLeft:12+de*16},onClick:()=>{o(J.id),J.children&&J.children.length>0&&I(J.id)},onDragOver:ue=>B(ue,J.id),onDrop:ue=>G(ue,J.id),onDragLeave:Y,children:[r.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Se=J.children)==null?void 0:Se.length)||0)>0||ye.length>0?"?":"�"}),Z===J.id?r.jsx("input",{value:q,onChange:ue=>H(ue.target.value),onKeyDown:ue=>{ue.key==="Enter"&&z(J.id),ue.key==="Escape"&&A(null)},onBlur:()=>z(J.id),autoFocus:!0,style:{...K,flex:1},onClick:ue=>ue.stopPropagation()}):r.jsxs(r.Fragment,{children:[r.jsx("span",{children:J.icon??"??"}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ye.length}),r.jsx("button",{style:V,onClick:ue=>{ue.stopPropagation(),A(J.id),H(J.name)},title:g("common.rename"),children:"?"}),r.jsx("button",{style:{...V,color:"var(--error, #ef4444)"},onClick:ue=>{ue.stopPropagation(),h(J.id)},title:g("common.delete"),children:"?"})]})]}),me&&r.jsxs(r.Fragment,{children:[ye.map(ue=>ne(ue,de+1)),(ae=J.children)==null?void 0:ae.map(ue=>oe(ue,de+1))]})]},J.id)},ne=(J,de)=>{const me=i===J.id;return r.jsxs("div",{style:{...te(me),paddingLeft:12+de*16+22},onClick:()=>l(J.id),draggable:!0,onDragStart:xe=>{xe.dataTransfer.setData("playlistId",J.id),xe.dataTransfer.effectAllowed="move"},children:[r.jsx("span",{style:{fontSize:"0.7rem"},children:J.type==="dynamic"?"?":"??"}),r.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:J.trackCount})]},J.id)};if(v)return r.jsx("div",{style:ie,children:r.jsx("button",{style:{...V,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:x,title:g("playlistManager.expandSidebar"),children:"?"})});const he=X(null);return r.jsxs("div",{style:ie,children:[r.jsxs("div",{style:{...le,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem"},children:["?? ",g("playlistManager.title")]}),r.jsx("button",{style:V,onClick:x,title:g("playlistManager.collapseSidebar"),children:"?"})]}),r.jsxs("div",{style:{...le,display:"flex",gap:4,flexWrap:"wrap"},children:[r.jsxs("button",{style:{...V,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>$(!0),children:["+ ",g("playlistManager.newPlaylist")]}),r.jsxs("button",{style:{...V,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{M(!0),w(s)},children:["?? ",g("playlistManager.newFolder")]})]}),O&&r.jsxs("div",{style:{...le,display:"flex",flexDirection:"column",gap:6},children:[r.jsx("input",{value:E,onChange:J=>_(J.target.value),placeholder:g("playlistManager.playlistName"),style:K,autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&T(),J.key==="Escape"&&$(!1)}}),r.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:L==="static",onChange:()=>U("static")}),g("playlistManager.static")]}),r.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[r.jsx("input",{type:"radio",checked:L==="dynamic",onChange:()=>U("dynamic")}),"? ",g("playlistManager.dynamic")]}),r.jsx("div",{style:{flex:1}}),r.jsx("button",{style:{...V,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:T,"aria-label":"Confirm create playlist",children:"?"}),r.jsx("button",{style:V,onClick:()=>$(!1),"aria-label":"Cancel create playlist",children:"?"})]})]}),S&&r.jsxs("div",{style:{...le,display:"flex",gap:6},children:[r.jsx("input",{value:R,onChange:J=>N(J.target.value),placeholder:g("playlistManager.folderName"),style:{...K,flex:1},autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&P(),J.key==="Escape"&&M(!1)}}),r.jsx("button",{style:{...V,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:P,"aria-label":"Confirm create folder",children:"?"}),r.jsx("button",{style:V,onClick:()=>M(!1),"aria-label":"Cancel create folder",children:"?"})]}),r.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[r.jsxs("div",{style:te(s===null&&i===null,re==="__root__"),onClick:()=>o(null),onDragOver:J=>B(J,null),onDrop:J=>G(J,null),onDragLeave:Y,children:[r.jsx("span",{children:"??"}),r.jsx("span",{style:{flex:1},children:g("playlistManager.allPlaylists")}),r.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),he.map(J=>ne(J,0)),F.map(J=>oe(J,0))]}),n.length>0&&r.jsxs("div",{style:le,children:[r.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:g("playlistManager.tags")}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(J=>r.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:J.color+"22",color:J.color,border:`1px solid ${J.color}44`,cursor:"pointer"},children:[J.icon&&`${J.icon} `,J.name]},J.id))})]}),r.jsxs("div",{style:le,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>j(!W),children:[r.jsxs("span",{children:["?? ",g("playlistManager.services")]}),r.jsx("span",{children:"?"})]}),W&&r.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[qt.Spotify,qt.Tidal,qt.YouTube].map(J=>{const de=hf[J],me=a.find(xe=>xe.platform===J);return r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.78rem"},children:[r.jsx("span",{children:de.icon}),r.jsx("span",{style:{flex:1},children:de.label}),me!=null&&me.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:me.username??g("playlistManager.connected")}),r.jsx("button",{style:{...V,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(J),children:"?"})]}):r.jsx("button",{style:{...V,background:de.color,color:"var(--nice-bg, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>f(J),children:g("playlistManager.connect")})]},J)})})]})]})},pf=({playlist:e,tags:t,onPlay:n,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=Te(),o=d.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[r.jsx("span",{style:{fontSize:"2rem",marginBottom:8},children:"??"}),r.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return r.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>n(l),style:{border:c?"2px solid var(--accent, #3b82f6)":"1px solid var(--border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--accent-bg, #eff6ff)":"var(--card-bg, #fff)",transition:"all 0.12s"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:"?"}),r.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),r.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},xl=d.memo(pf),ai=e=>e.replace(/[^a-z0-9_-]/gi,"-"),si={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},ff=({playlists:e,folders:t,tags:n,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=Te(),c=d.useMemo(()=>a?e.filter(u=>u.folderId===a):e,[e,a]);return c.length===0?r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[r.jsx("span",{style:{fontSize:"2.5rem",marginBottom:12},children:"??"}),r.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState")})]}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(u=>{var p;const h=t.find(f=>f.id===u.folderId);return r.jsxs("div",{onClick:()=>s(u.id),style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--card-bg, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:f=>{f.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",f.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:f=>{f.currentTarget.style.boxShadow="none",f.currentTarget.style.transform="none"},children:[r.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:u.type===rs.Dynamic?"?":"??"}),r.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:u.name}),r.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[u.trackCount," ",l("playlistManager.tracks"),h&&` � ?? ${h.name}`]}),((p=u.tags)==null?void 0:p.length)>0&&r.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:u.tags.slice(0,3).map(f=>{const y=n.find(m=>m.id===f);return y?r.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ai(f)}-bg, ${y.color}18)`,color:`var(--tag-${ai(f)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},f):null})}),r.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[r.jsx("button",{onClick:f=>{f.stopPropagation(),o(u.id)},style:si,title:l("playlistManager.duplicate"),children:"??"}),r.jsx("button",{onClick:f=>{f.stopPropagation(),i(u.id)},style:si,title:l("playlistManager.delete"),children:"??"})]})]},u.id)})})},vl=d.memo(ff),ii=[{value:kt.Library,label:"Library",icon:"??",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:kt.Spotify,label:"Spotify",icon:"??",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:kt.Tidal,label:"Tidal",icon:"?",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:kt.YouTube,label:"YouTube",icon:"??",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:kt.MusicBrainz,label:"MusicBrainz",icon:"??",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],Sl=({onSearch:e,results:t,isSearching:n,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=Te(),[o,l]=d.useState(""),[c,u]=d.useState(new Set([kt.Library,kt.Spotify,kt.Tidal,kt.YouTube])),[h,p]=d.useState(new Set),[f,y]=d.useState(!1),m=d.useRef(null),v=d.useCallback(N=>{u(C=>{const w=new Set(C);return w.has(N)?w.delete(N):w.add(N),w})},[]),x=d.useCallback(N=>{l(N),m.current&&clearTimeout(m.current),N.trim().length>=2&&(m.current=setTimeout(()=>{e(N.trim(),Array.from(c))},350))},[c,e]),g=d.useCallback(N=>{N.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),k=d.useCallback(N=>{p(C=>{const w=new Set(C);return w.has(N)?w.delete(N):w.add(N),w})},[]),b=d.useCallback(()=>{h.size===t.length?p(new Set):p(new Set(t.map(N=>N.id)))},[h,t]),S=d.useCallback(()=>{const N=t.filter(C=>h.has(C.id));N.length>0&&(a(N),p(new Set))},[t,h,a]),M=N=>{if(!N)return"--:--";const C=Math.floor(N/60),w=N%60;return`${C}:${w.toString().padStart(2,"0")}`},R=N=>{const C=ii.find(w=>w.value===N);return C?C.icon:"?"};return r.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--surface-bg, #f9fafb)"},onClick:()=>y(!f),children:[r.jsx("span",{style:{fontSize:"1rem"},children:"??"}),r.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:i("playlistManager.search")}),r.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:"?"})]}),f&&r.jsxs("div",{style:{padding:"0 12px 12px"},children:[r.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:ii.map(N=>{const C=c.has(N.value);return r.jsxs("button",{onClick:()=>v(N.value),style:{padding:"4px 10px",borderRadius:20,border:C?`2px solid ${N.css}`:"1px solid var(--border-color, #d1d5db)",background:C?N.cssBg:"transparent",color:C?N.css:"var(--text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:C?600:400,transition:"all 0.15s"},children:[N.icon," ",N.label]},N.value)})}),r.jsxs("form",{onSubmit:g,style:{display:"flex",gap:6,marginBottom:8},children:[r.jsx("input",{type:"text",value:o,onChange:N=>x(N.target.value),placeholder:i("playlistManager.searchPlaceholder"),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--border-color, #d1d5db)",background:"var(--input-bg, #fff)",color:"var(--text-primary, #1f2937)",fontSize:"0.82rem"}}),r.jsx("button",{type:"submit",disabled:o.trim().length<2||n,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:o.trim().length<2?.5:1},children:n?"?":"??"})]}),t.length>0&&r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[r.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:b}),i("playlistManager.selectAll")]}),r.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results")]}),r.jsx("div",{style:{flex:1}}),h.size>0&&r.jsxs("button",{onClick:S,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:["? ",i("playlistManager.addSelected")," (",h.size,")"]})]}),r.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--border-color, #e5e7eb)"},children:t.map(N=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--border-color, #f3f4f6)",background:h.has(N.id)?"var(--accent-bg, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>k(N.id),children:[r.jsx("input",{type:"checkbox",checked:h.has(N.id),readOnly:!0}),r.jsx("span",{children:R(N.source)}),N.imageUrl&&r.jsx("img",{src:N.imageUrl,alt:N.title||i("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:N.title}),r.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[N.artist,N.album?` � ${N.album}`:""]})]}),r.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:M(N.duration)}),s&&r.jsx("button",{onClick:C=>{C.stopPropagation(),s(N)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview"),children:"?"})]},N.id))})]}),n&&r.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:["? ",i("playlistManager.searching"),"..."]}),!n&&o.trim().length>=2&&t.length===0&&r.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults")})]})]})},mf=[{value:1,label:"Spotify",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:r.jsx(se.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],gf={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--panel-bg, #ffffff)",border:"1px solid var(--border, #e2e8f0)",maxWidth:640,minHeight:400},yf={display:"flex",justifyContent:"space-between",alignItems:"center"},bf={display:"flex",gap:4,marginBottom:8},En={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--accent, #6366f1)",color:"var(--nice-bg, #fff)",cursor:"pointer",fontWeight:600},rr={...En,background:"transparent",color:"var(--text, #334155)",border:"1px solid var(--border, #e2e8f0)"},oi={padding:12,borderRadius:8,border:"1px solid var(--border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},kl=["connect","browse","tracks","options","importing","done"];function xf(e){return kl.indexOf(e)}function vf(e){if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${n.toString().padStart(2,"0")}`}const wl=({connections:e=[],onConnect:t=()=>{},onDisconnect:n=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:u}=Te(),[h,p]=d.useState("connect"),[f,y]=d.useState(null),[m,v]=d.useState([]),[x,g]=d.useState(null),[k,b]=d.useState([]),[S,M]=d.useState(new Set),[R,N]=d.useState(!1),[C,w]=d.useState(null),[O,$]=d.useState(null),[E,_]=d.useState(null),[L,U]=d.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[Z,A]=d.useState(""),q=d.useMemo(()=>new Set(e.filter(V=>V.connected).map(V=>V.platform)),[e]),H=d.useCallback(V=>e.find(K=>K.platform===V),[e]),re=d.useCallback(V=>{if(y(V),V===99){p("tracks"),A(""),b([]),N(!1);return}q.has(V)?(p("browse"),N(!0),_(null),a(V).then(K=>{v(K),N(!1)}).catch(K=>{_(String(K)),N(!1)})):t(V)},[q,t,a]),D=d.useCallback(V=>{g(V),p("tracks"),N(!0),_(null),s(V).then(K=>{b(K),M(new Set(K.map(oe=>oe.externalId))),N(!1)}).catch(K=>{_(String(K)),N(!1)})},[s]),W=d.useCallback(V=>{M(K=>{const oe=new Set(K);return oe.has(V)?oe.delete(V):oe.add(V),oe})},[]),j=d.useCallback(()=>{M(V=>V.size===k.length?new Set:new Set(k.map(K=>K.externalId)))},[k]),F=d.useCallback(async()=>{if(!x)return;const V=k.filter(K=>S.has(K.externalId));if(V.length!==0){p("importing"),w({total:V.length,imported:0,skipped:0,failed:0}),_(null);try{const K=await i(x,V,L),oe=K&&typeof K=="object"&&"imported"in K?K:{playlistName:x.name,imported:V.length,skipped:0,failed:0,failedTracks:[]};$(oe),p("done")}catch(K){_(String(K)),p("options")}}},[x,k,S,L,i]),I=h!=="connect"&&h!=="importing"&&h!=="done",P=d.useCallback(()=>{switch(h){case"browse":p("connect");break;case"tracks":p("browse");break;case"options":p("tracks");break}},[h]),T=()=>r.jsx("div",{style:bf,children:kl.map((V,K)=>r.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:K<=xf(h)?"var(--accent, #6366f1)":"var(--border, #e2e8f0)",transition:"background 0.2s"}},V))}),z=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.selectPlatform","Select a music platform to import from")}),mf.map(V=>{const K=H(V.value),oe=q.has(V.value);return r.jsxs("div",{style:{...oi,display:"flex",alignItems:"center",gap:12,borderColor:oe?V.color:void 0},onClick:()=>re(V.value),role:"button",tabIndex:0,onKeyDown:ne=>ne.key==="Enter"&&re(V.value),children:[r.jsx("span",{style:{color:V.color,display:"inline-flex"},"aria-hidden":"true",children:V.icon}),r.jsxs("div",{style:{flex:1},children:[r.jsx("strong",{children:V.label}),(K==null?void 0:K.username)&&r.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:K.username})]}),oe?r.jsxs("span",{style:{color:V.color,fontSize:12,fontWeight:600},children:[u("importWizard.connected","Connected")," ",r.jsx(se.NtdCheck,{size:12})]}):r.jsx("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:u("importWizard.clickToConnect","Click to connect")})]},V.value)})]}),B=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.selectPlaylist","Select a playlist to import")}),R?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:u("importWizard.loading","Loading playlists…")}):r.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(V=>r.jsxs("div",{style:{...oi,display:"flex",alignItems:"center",gap:12},onClick:()=>D(V),role:"button",tabIndex:0,onKeyDown:K=>K.key==="Enter"&&D(V),children:[V.coverUrl&&r.jsx("img",{src:V.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V.name}),V.description&&r.jsx("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V.description})]}),r.jsxs("span",{style:{fontSize:12,color:"var(--text-dim, #64748b)",whiteSpace:"nowrap"},children:[V.trackCount," ",u("importWizard.tracks","tracks")]})]},V.id)),m.length===0&&r.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--text-dim, #64748b)"},children:u("importWizard.noPlaylists","No playlists found")})]})]}),G=d.useCallback(V=>{const oe=V.split(`
68
- `).map(ne=>ne.trim()).filter(Boolean).map((ne,he)=>{const J=ne.match(/^(.+?)\s*[-–—]\s*(.+)$/);return J?{externalId:`paste-${he}`,title:J[2].trim(),artist:J[1].trim(),album:void 0,duration:0}:{externalId:`paste-${he}`,title:ne,artist:"",album:void 0,duration:0}});b(oe),M(new Set(oe.map(ne=>ne.externalId)))},[]),Y=()=>r.jsxs("div",{style:{display:"grid",gap:12},children:[f===99&&k.length===0&&r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,color:"var(--text-dim, #64748b)"},children:u("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),r.jsx("textarea",{value:Z,onChange:V=>A(V.target.value),placeholder:`Daft Punk - Get Lucky
66
+ Artist — Title [Remastered 2011]
67
+ OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:6,padding:8,fontFamily:"inherit"}}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[n.jsx("div",{style:{color:"var(--nice-text-secondary, #6b7280)",fontSize:12},children:h("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),n.jsx("button",{type:"button",onClick:ee,disabled:!m.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)"},children:h("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},ol={music:W.NtdMusic,microphone:W.NtdMicrophone,volume:W.NtdVolume,wave:W.NtdWave,megaphone:W.NtdMegaphone,star:W.NtdStar,heart:W.NtdHeart,lightning:W.NtdLightning,sparkle:W.NtdSparkle,moon:W.NtdMoon,sun:W.NtdSun,mountain:W.NtdMountain,trophy:W.NtdTrophy,crown:W.NtdCrown,target:W.NtdTarget,pin:W.NtdPin},af=Object.keys(ol),ba=({icon:e,size:t=14})=>{if(!e)return null;const r=ol[e];return r?n.jsx(r,{size:t}):n.jsx("span",{children:e})},ti=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-warning, #eab308)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)","var(--nice-text-muted, #78716c)","var(--nice-text-secondary, #64748b)","var(--nice-text, #000000)"],rr=af,ll=({tags:e,onCreateTag:t,onUpdateTag:r,onDeleteTag:a,selectedTracks:s,onAssignTag:i,onUnassignTag:o})=>{const{t:l}=Te(),[c,d]=u.useState(null),[h,f]=u.useState(""),[p,y]=u.useState(ti[8]),[m,x]=u.useState(rr[0]),[v,g]=u.useState(!1),[S,b]=u.useState(null),[k,j]=u.useState(""),[N,R]=u.useState(""),[w,M]=u.useState(""),I=u.useCallback(z=>{d(z.id),j(z.name),R(z.color),M(z.icon||rr[0])},[]),A=u.useCallback(()=>{c&&k.trim()&&(r(c,k.trim(),N,w),d(null))},[c,k,N,w,r]),T=u.useCallback(()=>{h.trim()&&(t(h.trim(),p,m),f(""),g(!1))},[h,p,m,t]),O=u.useCallback(z=>{S===z?(a(z),b(null)):(b(z),setTimeout(()=>b(null),3e3))},[S,a]),E=s&&s.length>0,V=z=>!s||s.length===0?!1:s.every(q=>q.tags.includes(z)),ee=z=>!s||s.length===0?!1:s.some(q=>q.tags.includes(z))&&!V(z);return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",alignItems:"center",gap:8,background:"var(--nice-color-surface, #f9fafb)"},children:[n.jsx(W.NtdTag,{size:16}),n.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager","Tag manager")}),n.jsx("div",{style:{flex:1}}),n.jsxs("button",{onClick:()=>g(!v),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"4px 10px",fontSize:"0.72rem",cursor:"pointer"},children:["+ ",l("playlistManager.newTag","New tag")]})]}),n.jsxs("div",{style:{padding:12},children:[v&&n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--nice-color-surface, #f9fafb)"},children:[n.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[n.jsx("input",{type:"text",value:h,onChange:z=>f(z.target.value),placeholder:l("playlistManager.tagName","Tag name"),style:{flex:1,padding:"5px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.8rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:z=>z.key==="Enter"&&T()}),n.jsx("button",{onClick:T,disabled:!h.trim(),style:{background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:h.trim()?1:.5},"aria-label":l("playlistManager.createTag","Create tag"),children:n.jsx(W.NtdCheck,{size:14})})]}),n.jsxs("div",{style:{marginBottom:6},children:[n.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color","Color")}),n.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:ti.map(z=>n.jsx("div",{onClick:()=>y(z),style:{width:20,height:20,borderRadius:"50%",background:z,cursor:"pointer",border:p===z?"3px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},z))})]}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon","Icon")}),n.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:rr.map(z=>n.jsx("div",{onClick:()=>x(z),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:m===z?"var(--nice-accent-tint-10, #eff6ff)":"transparent",border:m===z?"1px solid var(--nice-color-accent, #3b82f6)":"1px solid transparent"},children:n.jsx(ba,{icon:z,size:16})},z))})]})]}),E&&n.jsx("div",{style:{padding:"6px 10px",background:"var(--nice-accent-tint-10, #eff6ff)",borderRadius:6,marginBottom:8,fontSize:"0.72rem",color:"var(--nice-color-accent, #3b82f6)"},children:l("playlistManager.bulkTagHint","Click a tag to apply it to the selected tracks")+": "+s.length}),e.length===0?n.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags","No tags yet")}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(z=>n.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--nice-border-color, #e5e7eb)",background:c===z.id?"var(--nice-color-surface, #f9fafb)":"transparent"},children:c===z.id?n.jsxs(n.Fragment,{children:[n.jsx("select",{value:w,onChange:q=>M(q.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:rr.map(q=>n.jsx("option",{value:q,children:q},q))}),n.jsx("input",{type:"color",value:N,onChange:q=>R(q.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),n.jsx("input",{type:"text",value:k,onChange:q=>j(q.target.value),style:{flex:1,padding:"3px 8px",borderRadius:4,border:"1px solid var(--nice-border-color, #d1d5db)",fontSize:"0.78rem",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)"},onKeyDown:q=>q.key==="Enter"&&A()}),n.jsx("button",{onClick:A,style:ar("var(--nice-color-accent, #3b82f6)"),"aria-label":l("common.save","Save"),children:n.jsx(W.NtdCheck,{size:14})}),n.jsx("button",{onClick:()=>d(null),style:ar("var(--nice-text-secondary, #9ca3af)"),"aria-label":l("common.cancel","Cancel"),children:n.jsx(W.NtdClose,{size:14})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${z.color}18`,color:z.color,fontWeight:600,fontSize:"0.78rem"},children:[n.jsx(ba,{icon:z.icon,size:12}),z.name]}),E&&i&&o&&n.jsx("input",{type:"checkbox",checked:V(z.id),ref:q=>{q&&(q.indeterminate=ee(z.id))},onChange:()=>{const q=s.map(K=>K.id);V(z.id)?o(q,z.id):i(q,z.id)},style:{cursor:"pointer"}}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{onClick:()=>I(z),style:ar("var(--nice-text-secondary, #9ca3af)"),title:l("playlistManager.editTag","Edit tag"),"aria-label":l("playlistManager.editTag","Edit tag"),children:n.jsx(W.NtdEdit,{size:14})}),n.jsx("button",{onClick:()=>O(z.id),style:ar(S===z.id?"var(--nice-color-error, #ef4444)":"var(--nice-text-secondary, #9ca3af)"),title:S===z.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),"aria-label":S===z.id?l("playlistManager.confirmDelete","Click again to delete"):l("playlistManager.deleteTag","Delete tag"),children:n.jsx(W.NtdTrash,{size:14})})]})},z.id))})]})]})},ar=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var ss=(e=>(e.Static="static",e.Dynamic="dynamic",e))(ss||{}),cl=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(cl||{}),dl=(e=>(e.Left="left",e.Right="right",e))(dl||{}),lt=(e=>(e.Artist="artist",e.Title="title",e.Album="album",e.Genre="genre",e.Year="year",e.Duration="duration",e.Rating="rating",e.PlayCount="playCount",e.Tag="tag",e.Source="source",e.AddedDate="addedDate",e))(lt||{}),ct=(e=>(e.Equals="eq",e.NotEquals="neq",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.GreaterThan="gt",e.LessThan="lt",e.Between="between",e.In="in",e.NotIn="notIn",e))(ct||{}),ul=(e=>(e.Title="title",e.Artist="artist",e.Album="album",e.Duration="duration",e.AddedDate="addedDate",e.Year="year",e.Rating="rating",e.Custom="custom",e))(ul||{}),ln=(e=>(e.Asc="asc",e.Desc="desc",e))(ln||{}),wt=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(wt||{});const sf=[{value:lt.Artist,label:"Artist"},{value:lt.Title,label:"Title"},{value:lt.Album,label:"Album"},{value:lt.Genre,label:"Genre"},{value:lt.Year,label:"Year"},{value:lt.Duration,label:"Duration (s)"},{value:lt.Rating,label:"Rating"},{value:lt.PlayCount,label:"Play Count"},{value:lt.Tag,label:"Tag"},{value:lt.Source,label:"Source"},{value:lt.AddedDate,label:"Added Date"}],of=[{value:ct.Equals,label:"="},{value:ct.NotEquals,label:"≠"},{value:ct.Contains,label:"contains"},{value:ct.NotContains,label:"not contains"},{value:ct.StartsWith,label:"starts with"},{value:ct.GreaterThan,label:">"},{value:ct.LessThan,label:"<"},{value:ct.Between,label:"between"},{value:ct.In,label:"in"},{value:ct.NotIn,label:"not in"}];function lf(e){return"logic"in e&&"rules"in e}function va(){return{id:crypto.randomUUID(),field:lt.Artist,operator:ct.Contains,value:""}}function hl(){return{id:crypto.randomUUID(),logic:"and",rules:[va()]}}const cf=({rule:e,onChange:t,onRemove:r})=>n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:a=>t({...e,field:a.target.value}),children:sf.map(a=>n.jsx("option",{value:a.value,children:a.label},a.value))}),n.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:a=>t({...e,operator:a.target.value}),children:of.map(a=>n.jsx("option",{value:a.value,children:a.label},a.value))}),n.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:a=>t({...e,value:a.target.value})}),e.operator===ct.Between&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-muted",children:"–"}),n.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:a=>t({...e,value2:a.target.value})})]}),n.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:r,title:"Remove rule","aria-label":"Remove rule",children:n.jsx(W.NtdClose,{size:14})})]}),pl=({group:e,onChange:t,onRemove:r,depth:a=0})=>{const{t:s}=Te(),i=u.useCallback((f,p)=>{const y=[...e.rules];y[f]=p,t({...e,rules:y})},[e,t]),o=u.useCallback(f=>{const p=e.rules.filter((y,m)=>m!==f);t({...e,rules:p.length>0?p:[va()]})},[e,t]),l=u.useCallback(()=>{t({...e,rules:[...e.rules,va()]})},[e,t]),c=u.useCallback(()=>{t({...e,rules:[...e.rules,hl()]})},[e,t]),d=u.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),h=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return n.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${h}`,backgroundColor:a%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[n.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[n.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:d,title:s("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),n.jsx("span",{className:"text-muted small",children:s("playlistManager.matchAll","Match all / any of these rules")}),n.jsxs("div",{className:"ms-auto d-flex gap-1",children:[n.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),a<3&&n.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),r&&n.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:r,title:"Remove group","aria-label":"Remove group",children:n.jsx(W.NtdClose,{size:14})})]})]}),e.rules.map((f,p)=>lf(f)?n.jsx(pl,{group:f,onChange:y=>i(p,y),onRemove:()=>o(p),depth:a+1},f.id):n.jsx(cf,{rule:f,onChange:y=>i(p,y),onRemove:()=>o(p)},f.id))]})},fl=({rules:e,onChange:t,limit:r,onLimitChange:a})=>{const{t:s}=Te(),i=e??hl();return n.jsxs("div",{className:"border rounded p-3",children:[n.jsxs("h6",{className:"mb-3",children:[n.jsx(W.NtdRepeat,{size:14})," ",s("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),n.jsx("p",{className:"text-muted small mb-3",children:s("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),n.jsx(pl,{group:i,onChange:t}),a&&n.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[n.jsx("label",{className:"form-label mb-0 small",children:s("playlistManager.maxTracks","Max tracks:")}),n.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:r??"",placeholder:"∞",onChange:o=>{const l=parseInt(o.target.value,10);a(isNaN(l)||l<=0?void 0:l)}}),n.jsx("span",{className:"text-muted small",children:s("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},ni=e=>{if(!e)return"--:--";const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${String(r).padStart(2,"0")}`},df={spotify:"var(--source-spotify, #1db954)",tidal:"var(--source-tidal, #000000)",youtube:"var(--source-youtube, #ff0000)",musicbrainz:"var(--source-musicbrainz, #ba478f)"},uf=({source:e})=>{if(e==="import")return n.jsx(W.NtdDownload,{size:12});if(e==="manual")return n.jsx(W.NtdEdit,{size:12});const t=df[e];return t?n.jsx(W.NtdCircle,{size:10,style:{color:t}}):n.jsx(W.NtdMusic,{size:12})},is=({tracks:e,tags:t,selectedTrackIds:r,onSelectionChange:a,onPlay:s,onRemove:i,onReorder:o,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:h,onSortChange:f,filterText:p,onFilterChange:y,compact:m=!1,draggable:x=!1,onDragStart:v,dropTarget:g=!1,onDrop:S})=>{const{t:b}=Te(),[k,j]=u.useState(null),[N,R]=u.useState(null),w=u.useRef(null),M=u.useMemo(()=>{let $=e??[];if(p.trim()){const P=p.toLowerCase();$=$.filter(F=>{var D,C;return F.title.toLowerCase().includes(P)||F.artist.toLowerCase().includes(P)||((D=F.album)==null?void 0:D.toLowerCase().includes(P))||((C=F.genre)==null?void 0:C.toLowerCase().includes(P))})}return[...$].sort((P,F)=>{const D=h==="asc"?1:-1;switch(d){case"title":return D*P.title.localeCompare(F.title);case"artist":return D*P.artist.localeCompare(F.artist);case"album":return D*(P.album??"").localeCompare(F.album??"");case"duration":return D*((P.duration??0)-(F.duration??0));case"year":return D*((P.year??0)-(F.year??0));case"rating":return D*((P.rating??0)-(F.rating??0));case"addedDate":return D*(P.addedAt??"").localeCompare(F.addedAt??"");case"custom":return D*((P.customOrder??0)-(F.customOrder??0));default:return 0}})},[e,p,d,h]),I=u.useCallback(($,P)=>{const F=M[$];if(F){if(P.ctrlKey||P.metaKey){const D=new Set(r);D.has(F.id)?D.delete(F.id):D.add(F.id),a(D)}else if(P.shiftKey&&w.current!==null){const D=Math.min(w.current,$),C=Math.max(w.current,$),L=new Set(r);for(let B=D;B<=C;B++)L.add(M[B].id);a(L)}else a(new Set([F.id]));w.current=$}},[M,r,a]),A=u.useCallback(()=>{r.size===M.length?a(new Set):a(new Set(M.map($=>$.id)))},[M,r,a]),T=({field:$,label:P,width:F})=>{const D=d===$;return n.jsxs("div",{style:{width:F,flex:F?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:D?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:D?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{D?f($,h===ln.Asc?ln.Desc:ln.Asc):f($,ln.Asc)},children:[P,D&&(h==="asc"?n.jsx(W.NtdArrowUp,{size:10}):n.jsx(W.NtdArrowDown,{size:10}))]})},O=u.useCallback(($,P)=>{const F=r.has($.id)?Array.from(r):[$.id];P.dataTransfer.setData("trackIds",JSON.stringify(F)),P.dataTransfer.effectAllowed="move",v==null||v(F,P)},[r,v]),E=u.useCallback(($,P)=>{P.preventDefault(),P.dataTransfer.dropEffect="move",j($)},[]),V=u.useCallback(($,P)=>{P.preventDefault(),j(null);try{const F=P.dataTransfer.getData("trackIds");if(F&&o){const D=JSON.parse(F),C=M.filter(G=>!D.includes(G.id)),L=M.filter(G=>D.includes(G.id)),B=Math.min($,C.length);C.splice(B,0,...L),o(C.map(G=>G.id))}}catch{}},[M,o]),ee=u.useCallback($=>{$.preventDefault(),j(null),S==null||S($)},[S]),z=u.useMemo(()=>new Map(t.map($=>[$.id,$])),[t]),q=$=>$.replace(/[^a-z0-9_-]/gi,"-"),K=m?36:48,re={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",color:"var(--nice-text-secondary, #6b7280)"},_=($,P)=>({display:"flex",alignItems:"center",gap:8,padding:m?"4px 12px":"6px 12px",height:K,cursor:"pointer",background:P?"var(--nice-color-accent-light, #dbeafe)":$?"var(--nice-selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--nice-border-light, #f3f4f6)",transition:"background 0.1s"}),U=M.length>0&&r.size===M.length;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:g?$=>{$.preventDefault(),$.dataTransfer.dropEffect="copy"}:void 0,onDrop:g?ee:void 0,children:[n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[n.jsx("input",{type:"text",value:p,onChange:$=>y($.target.value),placeholder:b("playlistManager.filterTracks","Filter tracks..."),style:{flex:1,fontSize:"0.82rem",padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #f9fafb)",color:"var(--nice-text-primary, #1f2937)"}}),n.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[M.length,"/",(e??[]).length]}),r.size>0&&i&&n.jsxs("button",{style:{fontSize:"0.72rem",padding:"4px 8px",borderRadius:4,border:"1px solid var(--nice-color-error, #ef4444)",background:"transparent",color:"var(--nice-color-error, #ef4444)",cursor:"pointer"},onClick:()=>i(Array.from(r)),"aria-label":b("playlistManager.removeSelected","Remove selected"),children:[n.jsx(W.NtdTrash,{size:12})," ",r.size]})]}),n.jsxs("div",{style:re,children:[n.jsx("div",{style:{width:28},children:n.jsx("input",{type:"checkbox",checked:U,onChange:A,style:{cursor:"pointer"}})}),n.jsx("div",{style:{width:20},children:"#"}),!m&&n.jsx("div",{style:{width:44}}),n.jsx(T,{field:"title",label:b("playlistManager.colTitle","Title")}),n.jsx(T,{field:"artist",label:b("playlistManager.colArtist","Artist")}),!m&&n.jsx(T,{field:"album",label:b("playlistManager.colAlbum","Album")}),n.jsx(T,{field:"duration",label:b("playlistManager.colDuration","Duration"),width:60}),!m&&n.jsx(T,{field:"year",label:b("playlistManager.colYear","Year"),width:50}),n.jsx("div",{style:{width:30}})," ",!m&&n.jsx("div",{style:{width:60}})," ",n.jsx("div",{style:{width:24}})," "]}),n.jsxs("div",{style:{flex:1,overflow:"auto"},children:[M.length===0&&n.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?b("playlistManager.emptyPlaylist","This playlist is empty"):b("playlistManager.noMatchingTracks","No tracks match the filter")}),M.map(($,P)=>{const F=r.has($.id),D=k===P;return n.jsxs("div",{style:_(F,D),onClick:C=>I(P,C),onDoubleClick:()=>s==null?void 0:s($),draggable:x,onDragStart:C=>O($,C),onDragOver:C=>E(P,C),onDrop:C=>V(P,C),onDragLeave:()=>j(null),children:[n.jsx("div",{style:{width:28},children:n.jsx("input",{type:"checkbox",checked:F,onChange:()=>{const C=new Set(r);F?C.delete($.id):C.add($.id),a(C)},onClick:C=>C.stopPropagation(),style:{cursor:"pointer"}})}),n.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:P+1}),!m&&n.jsx("div",{style:{width:44,height:36,flexShrink:0},children:$.coverUrl?n.jsx("img",{src:$.coverUrl,alt:$.title||b("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):n.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--nice-color-surface, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:n.jsx(W.NtdMusic,{size:16})})}),n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:$.title}),n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:$.artist}),!m&&n.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:$.album}),n.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:ni($.duration)}),!m&&n.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:$.year||""}),n.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:$.source,children:n.jsx(uf,{source:$.source})}),!m&&n.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[$.tags.slice(0,2).map(C=>{const L=z.get(C);if(!L)return null;const B=`--tag-${q(C)}`;return n.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${B}-bg, ${L.color}22)`,color:`var(${B}, ${L.color})`,whiteSpace:"nowrap"},children:L.name},C)}),$.tags.length>2&&n.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",$.tags.length-2]})]}),n.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[n.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:C=>{C.stopPropagation(),R(N===$.id?null:$.id)},title:b("playlistManager.morActions","More actions"),"aria-label":b("playlistManager.morActions","More actions"),children:n.jsx(W.NtdTag,{size:12})}),N===$.id&&t.length>0&&n.jsxs("div",{style:{position:"absolute",right:12,marginTop:4,background:"var(--nice-bg-elevated, #fff)",border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:8,padding:8,zIndex:100,boxShadow:"0 4px 12px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",minWidth:140},children:[n.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:b("playlistManager.assignTag","Assign tag")}),t.map(C=>{const L=$.tags.includes(C.id);return n.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:L?`var(--tag-${q(C.id)}-bg, ${C.color}22)`:"transparent"},onClick:B=>{B.stopPropagation();const G=r.size>0?Array.from(r):[$.id];L||l==null||l(G,[C.id]),R(null)},children:[n.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${q(C.id)}, ${C.color})`,flexShrink:0}}),n.jsx("span",{children:C.name}),L&&n.jsx(W.NtdCheck,{size:12,style:{marginLeft:"auto"}})]},C.id)})]})]})]},$.id)})]}),n.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[n.jsxs("span",{children:[M.length," ",b("playlistManager.tracks","tracks")]}),n.jsx("span",{children:ni(M.reduce(($,P)=>$+(P.duration??0),0))}),r.size>0&&n.jsxs("span",{children:[r.size," ",b("playlistManager.selected","selected")]})]})]})},ri=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),ml=({playlists:e=[],tags:t=[],onCopyTracks:r=()=>{},onMoveTracks:a=()=>{},onRemoveTracks:s=()=>{},onReorderTracks:i=()=>{},onPlay:o=()=>{},onTagTracks:l=()=>{},initialLeftId:c,initialRightId:d,library:h,queue:f,onAddToQueue:p,onRemoveFromQueue:y})=>{const{t:m}=Te(),[x,v]=u.useState(()=>ri(c??null)),[g,S]=u.useState(()=>ri(d??null)),[b,k]=u.useState("left"),[j,N]=u.useState(null),[R,w]=u.useState(50),[M,I]=u.useState(!1),A=u.useMemo(()=>e.find(D=>D.id===x.playlistId),[e,x.playlistId]),T=u.useMemo(()=>e.find(D=>D.id===g.playlistId),[e,g.playlistId]),O=u.useCallback((D,C)=>{D==="left"?v(L=>({...L,...C})):S(L=>({...L,...C}))},[]),E=u.useCallback(D=>D==="left"?x:g,[x,g]),V=D=>D==="left"?"right":"left",ee=u.useCallback(D=>{const C=E(D),L=E(V(D));!C.playlistId||!L.playlistId||C.selectedTrackIds.size===0||(r(C.playlistId,L.playlistId,Array.from(C.selectedTrackIds)),O(D,{selectedTrackIds:new Set}))},[E,r,O]),z=u.useCallback(D=>{const C=E(D),L=E(V(D));!C.playlistId||!L.playlistId||C.selectedTrackIds.size===0||(a(C.playlistId,L.playlistId,Array.from(C.selectedTrackIds)),O(D,{selectedTrackIds:new Set}))},[E,a,O]),q=u.useCallback(D=>{const C=E(D);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"copy",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[E]),K=u.useCallback(D=>{const C=E(D);!C.playlistId||C.selectedTrackIds.size===0||N({operation:"cut",sourcePlaylistId:C.playlistId,trackIds:Array.from(C.selectedTrackIds)})},[E]),re=u.useCallback(D=>{const C=E(D);!j||!C.playlistId||(j.operation==="copy"?r(j.sourcePlaylistId,C.playlistId,j.trackIds):a(j.sourcePlaylistId,C.playlistId,j.trackIds),N(null))},[j,E,r,a]),_=u.useCallback(D=>{D.key==="Tab"&&!D.shiftKey&&(D.preventDefault(),k(C=>V(C))),(D.ctrlKey||D.metaKey)&&D.key==="c"&&q(b),(D.ctrlKey||D.metaKey)&&D.key==="x"&&K(b),(D.ctrlKey||D.metaKey)&&D.key==="v"&&re(b)},[b,q,K,re]),U=u.useCallback(()=>I(!0),[]),$=u.useCallback(D=>{if(!M)return;const C=D.currentTarget.getBoundingClientRect(),L=(D.clientX-C.left)/C.width*100;w(Math.max(20,Math.min(80,L)))},[M]),P=u.useCallback(()=>I(!1),[]),F=D=>{const C=E(D),L=D==="left"?A:T,B=b===D,H=!!E(V(D)).playlistId;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:B?"2px solid var(--nice-color-accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--nice-bg-elevated, #fff)"},onClick:()=>k(D),children:[n.jsx("div",{style:{padding:"8px 12px",background:B?"var(--nice-color-accent, #3b82f6)":"var(--nice-color-surface, #f3f4f6)",color:B?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:n.jsxs("select",{value:C.playlistId??"",onChange:X=>O(D,{playlistId:X.target.value||null,selectedTrackIds:new Set}),style:{flex:1,fontSize:"0.82rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:B?"var(--nice-overlay-light-20, #ffffff30)":"var(--nice-input-bg, #fff)",color:B?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)"},children:[n.jsx("option",{value:"",children:m("playlistManager.selectPlaylist","Select a playlist")}),e.map(X=>n.jsxs("option",{value:X.id,children:[X.name," (",X.trackCount,")"]},X.id))]})}),n.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)",flexWrap:"wrap"},children:[n.jsxs("button",{style:ta(!1),onClick:()=>ee(D),disabled:!C.playlistId||!H||C.selectedTrackIds.size===0,title:m("playlistManager.copyToOther","Copy to the other playlist"),children:[D==="left"?n.jsxs(n.Fragment,{children:[n.jsx(W.NtdCopy,{size:12}),n.jsx(W.NtdChevronRight,{size:12})]}):n.jsxs(n.Fragment,{children:[n.jsx(W.NtdChevronLeft,{size:12}),n.jsx(W.NtdCopy,{size:12})]})," ",m("playlistManager.copy","Copy")]}),n.jsxs("button",{style:ta(!1),onClick:()=>z(D),disabled:!C.playlistId||!H||C.selectedTrackIds.size===0,title:m("playlistManager.moveToOther","Move to the other playlist"),children:[D==="left"?n.jsxs(n.Fragment,{children:[n.jsx(W.NtdMove,{size:12}),n.jsx(W.NtdChevronRight,{size:12})]}):n.jsxs(n.Fragment,{children:[n.jsx(W.NtdChevronLeft,{size:12}),n.jsx(W.NtdMove,{size:12})]})," ",m("playlistManager.move","Move")]}),n.jsx("div",{style:{flex:1}}),j&&n.jsxs("button",{style:ta(!0),onClick:()=>re(D),disabled:!C.playlistId,children:[n.jsx(W.NtdClipboard,{size:12})," ",m("playlistManager.paste","Paste")," (",j.trackIds.length,")"]})]}),L?n.jsx(is,{tracks:L.tracks,tags:t,selectedTrackIds:C.selectedTrackIds,onSelectionChange:X=>O(D,{selectedTrackIds:X}),onPlay:o,onRemove:X=>s(L.id,X),onReorder:X=>i(L.id,X),onTagTracks:l,sortField:C.sortField,sortDir:C.sortDir,onSortChange:(X,oe)=>O(D,{sortField:X,sortDir:oe}),filterText:C.filterText,onFilterChange:X=>O(D,{filterText:X}),compact:!0,draggable:!0}):n.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:m("playlistManager.selectPlaylistPrompt","Select a playlist to see its tracks")})]})};return n.jsxs("div",{style:{display:"flex",height:"100%",userSelect:M?"none":"auto"},onKeyDown:_,onMouseMove:$,onMouseUp:P,tabIndex:0,children:[n.jsx("div",{style:{width:`${R}%`,minWidth:200},children:F("left")}),n.jsx("div",{style:{width:6,cursor:"col-resize",background:M?"var(--nice-color-accent, #3b82f6)":"var(--nice-border-color, #e5e7eb)",transition:M?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:U,children:n.jsx("div",{style:{width:2,height:40,borderRadius:1,background:M?"var(--btn-text, #fff)":"var(--nice-bg-tertiary, #9ca3af)"}})}),n.jsx("div",{style:{flex:1,minWidth:200},children:F("right")})]})},ta=e=>({background:e?"var(--nice-color-accent, #3b82f6)":"transparent",color:e?"var(--btn-text, #fff)":"var(--nice-text-secondary, #6b7280)",border:e?"none":"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"3px 8px",fontSize:"0.72rem",cursor:"pointer",whiteSpace:"nowrap"}),gl="av:local-playlists";function hf(){try{const e=localStorage.getItem(gl);return e?JSON.parse(e):[]}catch{return[]}}function pf(e){const t=JSON.stringify(e);try{localStorage.setItem(gl,t)}catch{}}function os(){const[e,t]=u.useState(()=>hf()),r=u.useRef(!1);return u.useEffect(()=>{r.current=!0},[]),u.useEffect(()=>{pf(e)},[e]),u.useMemo(()=>({list:()=>e,get:s=>e.find(i=>i.id===s),create:s=>{const i=new Date().toISOString(),o={id:crypto.randomUUID(),name:s,items:[],updatedAt:i};return t(l=>[o,...l]),o},rename:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,name:i,updatedAt:new Date().toISOString()}:l)),remove:s=>t(i=>i.filter(o=>o.id!==s)),replaceItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:i,updatedAt:new Date().toISOString()}:l)),addItems:(s,i)=>t(o=>o.map(l=>l.id===s?{...l,items:[...l.items,...i],updatedAt:new Date().toISOString()}:l))}),[e])}const ff=ot.scoped("PlaylistList"),mf={border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,background:"var(--nice-bg, #fff)"},gf={...mf,padding:"8px 10px",cursor:"pointer"},yl={border:"1px solid var(--nice-border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--nice-bg, #fff)",cursor:"pointer"},yf={...yl,background:"var(--nice-color-primary, #4f46e5)",borderColor:"var(--nice-color-primary, #4f46e5)",color:"var(--nice-text-on-primary, #fff)"},ls=({selectedId:e,onSelect:t,onCreateRemote:r})=>{const{t:a}=Te(),s=os(),[i,o]=u.useState(""),l=u.useMemo(()=>s.list(),[s]);return n.jsxs("div",{style:{display:"grid",gap:10},children:[n.jsxs("div",{style:{display:"flex",gap:8},children:[n.jsx("input",{placeholder:a("playlistList.playlistName","Playlist name..."),value:i,onChange:c=>o(c.target.value),style:{flex:1,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),n.jsxs("button",{type:"button",disabled:!i.trim(),style:i.trim()?yf:{...yl,cursor:"not-allowed",color:"var(--nice-text-muted, #9ca3af)",background:"var(--nice-bg-tertiary, #f3f4f6)"},onClick:async()=>{const c=s.create(i.trim());if(o(""),r)try{await r({platform:"tidal",name:c.name,songs:c.items})}catch(d){ff.error("Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",a("common.add","Add")]})]}),n.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return n.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...gf,background:d?"var(--nice-selected-bg, #eef2ff)":"var(--nice-bg, #fff)"},children:[n.jsx("div",{style:{fontWeight:600},children:c.name}),n.jsxs("div",{style:{color:"var(--nice-text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+a("playlistList.songs","songs")," ","• ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&n.jsx("div",{style:{color:"var(--nice-text-muted, #6b7280)"},children:a("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},bf=ot.scoped("PlaylistBrowser"),ai={display:"grid",gap:12},si=e=>({artist:(e.artists??[]).join(", "),title:e.title}),bl=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:r,tracks:a,view:s,onSelect:i,onPlay:o})=>{var v;const{t:l}=Te(),c=os(),[d,h]=u.useState(null),[f,p]=u.useState(""),[,y]=u.useState([]),m=d==null?void 0:d.id,x=(g,S)=>{if("addItems"in c){c.addItems(g.id,S);const k=c.list().find(j=>j.id===g.id)||g;h(k);return}const b=c;if("update"in c&&typeof b.update=="function"){const k=Array.from([...g.items||[],...S]);b.update({...g,items:k});const j=c.list().find(N=>N.id===g.id)||{...g,items:k};h(j);return}bf.warn("useLocalPlaylists: missing addItems/update method — update hook implementation.")};return n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[n.jsxs("div",{style:ai,children:[n.jsx("h3",{style:{margin:0},children:l("playlistBrowser.playlists","Playlists")}),n.jsx(ls,{selectedId:m,onSelect:h}),d&&n.jsxs("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[l("playlistBrowser.selected","Selected"),": ",n.jsx("strong",{children:d.name})," ·"," ",((v=d.items)==null?void 0:v.length)??0," ",l("playlistBrowser.tracks","tracks")]})]}),n.jsxs("div",{style:ai,children:[n.jsx("h3",{style:{margin:0},children:l("playlistBrowser.library","Library")}),n.jsxs("div",{children:[e==null?void 0:e({placeholder:l("playlistBrowser.searchAndAdd","Search and add to playlist..."),onSelect:g=>{d&&x(d,[si(g)])}}),n.jsx("input",{placeholder:l("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:f,onChange:g=>p(g.target.value),style:{width:"100%",border:"1px solid var(--nice-border, #d1d5db)",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:f,onSelect:g=>{d&&x(d,[si(g)])}}),r==null?void 0:r({onPlayNow:g=>y(g),onAddToQueue:g=>y(S=>[...S,...g]),onAddDescriptors:g=>d&&x(d,g)})]})]})};var Ht=(e=>(e[e.None=0]="None",e[e.Spotify=1]="Spotify",e[e.Tidal=2]="Tidal",e[e.YouTube=4]="YouTube",e[e.All=7]="All",e))(Ht||{});const vl=(e,t=null)=>e.filter(r=>r.parentId===t).sort((r,a)=>r.sortOrder-a.sortOrder).map(r=>({...r,children:vl(e,r.id)})),vf={[Ht.Spotify]:{label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[Ht.Tidal]:{label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[Ht.YouTube]:{label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},xl=({folders:e,playlists:t,tags:r,services:a,activeFolderId:s,activePlaylistId:i,onSelectFolder:o,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:h,onCreatePlaylist:f,onConnectService:p,onDisconnectService:y,onDragPlaylistToFolder:m,collapsed:x=!1,onToggleCollapse:v})=>{const{t:g}=Te(),[S,b]=u.useState(new Set),[k,j]=u.useState(!1),[N,R]=u.useState(""),[w,M]=u.useState(null),[I,A]=u.useState(!1),[T,O]=u.useState(""),[E,V]=u.useState("static"),[ee,z]=u.useState(null),[q,K]=u.useState(""),[re,_]=u.useState(null),[U,$]=u.useState(!1),P=u.useMemo(()=>vl(e),[e]),F=u.useCallback(J=>{b(de=>{const me=new Set(de);return me.has(J)?me.delete(J):me.add(J),me})},[]),D=u.useCallback(()=>{N.trim()&&(c(N.trim(),w),R(""),j(!1))},[N,w,c]),C=u.useCallback(()=>{T.trim()&&(f(T.trim(),E,s),O(""),A(!1))},[T,E,s,f]),L=u.useCallback(J=>{q.trim()&&(d(J,q.trim()),z(null),K(""))},[q,d]),B=u.useCallback((J,de)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",_(de)},[]),G=u.useCallback((J,de)=>{J.preventDefault();const me=J.dataTransfer.getData("playlistId");me&&m&&m(me,de),_(null)},[m]),H=u.useCallback(()=>_(null),[]),X=u.useCallback(J=>t.filter(de=>(de.folderId??null)===J),[t]),oe={width:x?48:280,minWidth:x?48:280,background:"var(--nice-bg-secondary, #f8f9fa)",borderRight:"1px solid var(--nice-border-color, #e5e7eb)",display:"flex",flexDirection:"column",transition:"width 0.2s, min-width 0.2s",overflow:"hidden",height:"100%"},le={padding:"8px 12px",borderBottom:"1px solid var(--nice-border-color, #e5e7eb)"},ne=(J,de=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:de?"var(--nice-color-accent-light, #dbeafe)":J?"var(--nice-color-accent, #3b82f6)":"transparent",color:J?"var(--btn-text, #fff)":"var(--nice-text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),Z={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--nice-text-secondary, #6b7280)"},Y={fontSize:"0.8rem",padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",width:"100%"},se=(J,de)=>{var ke,ie;const me=S.has(J.id),ve=s===J.id,ce=re===J.id,ye=X(J.id);return n.jsxs("div",{children:[n.jsxs("div",{style:{...ne(ve,ce),paddingLeft:12+de*16},onClick:()=>{o(J.id),J.children&&J.children.length>0&&F(J.id)},onDragOver:he=>B(he,J.id),onDrop:he=>G(he,J.id),onDragLeave:H,children:[n.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((ke=J.children)==null?void 0:ke.length)||0)>0||ye.length>0?me?n.jsx(W.NtdChevronDown,{size:10}):n.jsx(W.NtdChevronRight,{size:10}):null}),ee===J.id?n.jsx("input",{value:q,onChange:he=>K(he.target.value),onKeyDown:he=>{he.key==="Enter"&&L(J.id),he.key==="Escape"&&z(null)},onBlur:()=>L(J.id),autoFocus:!0,style:{...Y,flex:1},onClick:he=>he.stopPropagation()}):n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{display:"inline-flex"},children:J.icon??n.jsx(W.NtdFolder,{size:14})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:ye.length}),n.jsx("button",{style:Z,onClick:he=>{he.stopPropagation(),z(J.id),K(J.name)},title:g("common.rename","Rename"),"aria-label":g("common.rename","Rename"),children:n.jsx(W.NtdEdit,{size:12})}),n.jsx("button",{style:{...Z,color:"var(--nice-color-error, #ef4444)"},onClick:he=>{he.stopPropagation(),h(J.id)},title:g("common.delete","Delete"),"aria-label":g("common.delete","Delete"),children:n.jsx(W.NtdTrash,{size:12})})]})]}),me&&n.jsxs(n.Fragment,{children:[ye.map(he=>ae(he,de+1)),(ie=J.children)==null?void 0:ie.map(he=>se(he,de+1))]})]},J.id)},ae=(J,de)=>{const me=i===J.id;return n.jsxs("div",{style:{...ne(me),paddingLeft:12+de*16+22},onClick:()=>l(J.id),draggable:!0,onDragStart:ve=>{ve.dataTransfer.setData("playlistId",J.id),ve.dataTransfer.effectAllowed="move"},children:[n.jsx("span",{style:{display:"inline-flex"},children:J.type==="dynamic"?n.jsx(W.NtdLightning,{size:12}):n.jsx(W.NtdMusic,{size:12})}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:J.name}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:J.trackCount})]},J.id)};if(x)return n.jsx("div",{style:oe,children:n.jsx("button",{style:{...Z,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:v,title:g("playlistManager.expandSidebar","Expand sidebar"),"aria-label":g("playlistManager.expandSidebar","Expand sidebar"),children:n.jsx(W.NtdChevronRight,{size:16})})});const ue=X(null);return n.jsxs("div",{style:oe,children:[n.jsxs("div",{style:{...le,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem",display:"inline-flex",alignItems:"center",gap:6},children:[n.jsx(W.NtdMusic,{size:14})," ",g("playlistManager.title","Playlists")]}),n.jsx("button",{style:Z,onClick:v,title:g("playlistManager.collapseSidebar","Collapse sidebar"),"aria-label":g("playlistManager.collapseSidebar","Collapse sidebar"),children:n.jsx(W.NtdChevronLeft,{size:16})})]}),n.jsxs("div",{style:{...le,display:"flex",gap:4,flexWrap:"wrap"},children:[n.jsxs("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>A(!0),children:["+ ",g("playlistManager.newPlaylist","New playlist")]}),n.jsxs("button",{style:{...Z,border:"1px solid var(--nice-border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{j(!0),M(s)},children:[n.jsx(W.NtdFolder,{size:12})," ",g("playlistManager.newFolder","New folder")]})]}),I&&n.jsxs("div",{style:{...le,display:"flex",flexDirection:"column",gap:6},children:[n.jsx("input",{value:T,onChange:J=>O(J.target.value),placeholder:g("playlistManager.playlistName","Playlist name"),style:Y,autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&C(),J.key==="Escape"&&A(!1)}}),n.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[n.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[n.jsx("input",{type:"radio",checked:E==="static",onChange:()=>V("static")}),g("playlistManager.static","Static")]}),n.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[n.jsx("input",{type:"radio",checked:E==="dynamic",onChange:()=>V("dynamic")}),n.jsx(W.NtdLightning,{size:12})," ",g("playlistManager.dynamic","Dynamic")]}),n.jsx("div",{style:{flex:1}}),n.jsx("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:C,"aria-label":"Confirm create playlist",children:n.jsx(W.NtdCheck,{size:12})}),n.jsx("button",{style:Z,onClick:()=>A(!1),"aria-label":"Cancel create playlist",children:n.jsx(W.NtdClose,{size:12})})]})]}),k&&n.jsxs("div",{style:{...le,display:"flex",gap:6},children:[n.jsx("input",{value:N,onChange:J=>R(J.target.value),placeholder:g("playlistManager.folderName","Folder name"),style:{...Y,flex:1},autoFocus:!0,onKeyDown:J=>{J.key==="Enter"&&D(),J.key==="Escape"&&j(!1)}}),n.jsx("button",{style:{...Z,background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:D,"aria-label":"Confirm create folder",children:n.jsx(W.NtdCheck,{size:12})}),n.jsx("button",{style:Z,onClick:()=>j(!1),"aria-label":"Cancel create folder",children:n.jsx(W.NtdClose,{size:12})})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[n.jsxs("div",{style:ne(s===null&&i===null,re==="__root__"),onClick:()=>o(null),onDragOver:J=>B(J,null),onDrop:J=>G(J,null),onDragLeave:H,children:[n.jsx(W.NtdHome,{size:14}),n.jsx("span",{style:{flex:1},children:g("playlistManager.allPlaylists","All playlists")}),n.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),ue.map(J=>ae(J,0)),P.map(J=>se(J,0))]}),r.length>0&&n.jsxs("div",{style:le,children:[n.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:g("playlistManager.tags","Tags")}),n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.map(J=>n.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:J.color+"22",color:J.color,border:`1px solid ${J.color}44`,cursor:"pointer"},children:[n.jsx(ba,{icon:J.icon,size:10}),J.icon?" ":"",J.name]},J.id))})]}),n.jsxs("div",{style:le,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>$(!U),children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdLink,{size:12})," ",g("playlistManager.services","Services")]}),U?n.jsx(W.NtdChevronUp,{size:12}):n.jsx(W.NtdChevronDown,{size:12})]}),U&&n.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[Ht.Spotify,Ht.Tidal,Ht.YouTube].map(J=>{const de=vf[J],me=a.find(ve=>ve.platform===J);return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 8px",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)",fontSize:"0.78rem"},children:[n.jsx(W.NtdCircle,{size:10,style:{color:de.color}}),n.jsx("span",{style:{flex:1},children:de.label}),me!=null&&me.connected?n.jsxs(n.Fragment,{children:[n.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:me.username??g("playlistManager.connected","Connected")}),n.jsx("button",{style:{...Z,color:"var(--nice-danger, #ef4444)"},onClick:()=>y(J),"aria-label":g("playlistManager.disconnect","Disconnect"),children:n.jsx(W.NtdClose,{size:12})})]}):n.jsx("button",{style:{...Z,background:de.color,color:"var(--nice-text-on-primary, #fff)",borderRadius:4,padding:"2px 8px"},onClick:()=>p(J),children:g("playlistManager.connect","Connect")})]},J)})})]})]})},xf=({playlist:e,tags:t,onPlay:r,selectedTrackIds:a,onSelectionChange:s})=>{const{t:i}=Te(),o=u.useCallback(l=>{const c=new Set(a);c.has(l)?c.delete(l):c.add(l),s(c)},[a,s]);return e.tracks.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:60,opacity:.3},children:[n.jsx("span",{style:{marginBottom:8,display:"inline-flex"},children:n.jsx(W.NtdMusic,{size:32})}),n.jsx("span",{style:{fontSize:"0.82rem"},children:i("playlistManager.emptyPlaylist","This playlist is empty")})]}):n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:10},children:e.tracks.map(l=>{const c=a.has(l.id);return n.jsxs("div",{onClick:()=>o(l.id),onDoubleClick:()=>r(l),style:{border:c?"2px solid var(--nice-color-accent, #3b82f6)":"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,padding:10,cursor:"pointer",background:c?"var(--nice-accent-tint-10, #eff6ff)":"var(--nice-bg-elevated, #fff)",transition:"all 0.12s"},children:[n.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:6,background:"linear-gradient(135deg, var(--playlist-track-bg1, #6366f140), var(--playlist-track-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.5rem",marginBottom:6},children:n.jsx(W.NtdMusic,{size:24})}),n.jsx("div",{style:{fontWeight:500,fontSize:"0.78rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.title}),n.jsx("div",{style:{fontSize:"0.68rem",opacity:.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:l.artist})]},l.id)})})},Sl=u.memo(xf),ii=e=>e.replace(/[^a-z0-9_-]/gi,"-"),oi={background:"none",border:"none",cursor:"pointer",fontSize:"0.78rem",padding:"2px 4px",opacity:.4},Sf=({playlists:e,folders:t,tags:r,activeFolderId:a,onSelectPlaylist:s,onDeletePlaylist:i,onDuplicatePlaylist:o})=>{const{t:l}=Te(),c=u.useMemo(()=>a?e.filter(d=>d.folderId===a):e,[e,a]);return c.length===0?n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:60,opacity:.4},children:[n.jsx("span",{style:{marginBottom:12,display:"inline-flex"},children:n.jsx(W.NtdMusic,{size:40})}),n.jsx("span",{style:{fontSize:"0.85rem"},children:l("playlistManager.emptyState","No playlists yet")})]}):n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))",gap:12},children:c.map(d=>{var f;const h=t.find(p=>p.id===d.folderId);return n.jsxs("div",{onClick:()=>s(d.id),style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:12,padding:16,cursor:"pointer",background:"var(--nice-bg-elevated, #fff)",transition:"box-shadow 0.15s, transform 0.15s"},onMouseEnter:p=>{p.currentTarget.style.boxShadow="0 4px 12px var(--nice-overlay-8, rgba(0, 0, 0, 0.08))",p.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:p=>{p.currentTarget.style.boxShadow="none",p.currentTarget.style.transform="none"},children:[n.jsx("div",{style:{width:"100%",aspectRatio:"1",borderRadius:8,background:"linear-gradient(135deg, var(--playlist-cover-bg1, #6366f140), var(--playlist-cover-bg2, #6366f110))",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"2.5rem",marginBottom:10},children:d.type===ss.Dynamic?n.jsx(W.NtdLightning,{size:40}):n.jsx(W.NtdMusic,{size:40})}),n.jsx("div",{style:{fontWeight:600,fontSize:"0.85rem",marginBottom:2},children:d.name}),n.jsxs("div",{style:{fontSize:"0.72rem",opacity:.5},children:[d.trackCount," ",l("playlistManager.tracks","tracks"),h&&n.jsxs(n.Fragment,{children:[" — ",n.jsx(W.NtdFolder,{size:11})," ",h.name]})]}),((f=d.tags)==null?void 0:f.length)>0&&n.jsx("div",{style:{display:"flex",gap:4,marginTop:6,flexWrap:"wrap"},children:d.tags.slice(0,3).map(p=>{const y=r.find(m=>m.id===p);return y?n.jsx("span",{style:{padding:"1px 8px",borderRadius:12,background:`var(--tag-${ii(p)}-bg, ${y.color}18)`,color:`var(--tag-${ii(p)}, ${y.color})`,fontSize:"0.65rem",fontWeight:500},children:y.name},p):null})}),n.jsxs("div",{style:{display:"flex",gap:4,marginTop:8},children:[n.jsx("button",{onClick:p=>{p.stopPropagation(),o(d.id)},style:oi,title:l("playlistManager.duplicate","Duplicate"),"aria-label":l("playlistManager.duplicate","Duplicate"),children:n.jsx(W.NtdCopy,{size:14})}),n.jsx("button",{onClick:p=>{p.stopPropagation(),i(d.id)},style:oi,title:l("playlistManager.delete","Delete"),"aria-label":l("playlistManager.delete","Delete"),children:n.jsx(W.NtdTrash,{size:14})})]})]},d.id)})})},kl=u.memo(Sf),li=[{value:wt.Library,label:"Library",hex:"var(--nice-info, #6366f1)",css:"var(--source-library, #6366f1)",cssBg:"var(--source-library-bg, #6366f118)"},{value:wt.Spotify,label:"Spotify",hex:"var(--nice-success, #1db954)",css:"var(--source-spotify, #1db954)",cssBg:"var(--source-spotify-bg, #1db95418)"},{value:wt.Tidal,label:"Tidal",hex:"var(--nice-text, #000000)",css:"var(--source-tidal, #000000)",cssBg:"var(--source-tidal-bg, #00000018)"},{value:wt.YouTube,label:"YouTube",hex:"var(--nice-danger, #ff0000)",css:"var(--source-youtube, #ff0000)",cssBg:"var(--source-youtube-bg, #ff000018)"},{value:wt.MusicBrainz,label:"MusicBrainz",hex:"#ba478f",css:"var(--source-musicbrainz, #ba478f)",cssBg:"var(--source-musicbrainz-bg, #ba478f18)"}],wl=({onSearch:e,results:t,isSearching:r,onAddToPlaylist:a,onPlayPreview:s})=>{const{t:i}=Te(),[o,l]=u.useState(""),[c,d]=u.useState(new Set([wt.Library,wt.Spotify,wt.Tidal,wt.YouTube])),[h,f]=u.useState(new Set),[p,y]=u.useState(!1),m=u.useRef(null),x=u.useCallback(R=>{d(w=>{const M=new Set(w);return M.has(R)?M.delete(R):M.add(R),M})},[]),v=u.useCallback(R=>{l(R),m.current&&clearTimeout(m.current),R.trim().length>=2&&(m.current=setTimeout(()=>{e(R.trim(),Array.from(c))},350))},[c,e]),g=u.useCallback(R=>{R.preventDefault(),o.trim().length>=2&&e(o.trim(),Array.from(c))},[o,c,e]),S=u.useCallback(R=>{f(w=>{const M=new Set(w);return M.has(R)?M.delete(R):M.add(R),M})},[]),b=u.useCallback(()=>{h.size===t.length?f(new Set):f(new Set(t.map(R=>R.id)))},[h,t]),k=u.useCallback(()=>{const R=t.filter(w=>h.has(w.id));R.length>0&&(a(R),f(new Set))},[t,h,a]),j=R=>{if(!R)return"--:--";const w=Math.floor(R/60),M=R%60;return`${w}:${M.toString().padStart(2,"0")}`},N=R=>{const w=li.find(M=>M.value===R);return n.jsx(W.NtdCircle,{size:10,style:{color:w?w.css:"var(--nice-text-secondary, #6b7280)"}})};return n.jsxs("div",{style:{border:"1px solid var(--nice-border-color, #e5e7eb)",borderRadius:10,background:"var(--nice-bg-elevated, #fff)",overflow:"hidden"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 12px",gap:8,cursor:"pointer",background:"var(--nice-color-surface, #f9fafb)"},onClick:()=>y(!p),children:[n.jsx(W.NtdSearch,{size:16}),n.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:i("playlistManager.search","Search")}),n.jsx("span",{style:{marginLeft:"auto",fontSize:"0.75rem",opacity:.5},children:p?n.jsx(W.NtdChevronUp,{size:12}):n.jsx(W.NtdChevronDown,{size:12})})]}),p&&n.jsxs("div",{style:{padding:"0 12px 12px"},children:[n.jsx("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap"},children:li.map(R=>{const w=c.has(R.value);return n.jsxs("button",{onClick:()=>x(R.value),style:{padding:"4px 10px",borderRadius:20,border:w?`2px solid ${R.css}`:"1px solid var(--nice-border-color, #d1d5db)",background:w?R.cssBg:"transparent",color:w?R.css:"var(--nice-text-secondary, #6b7280)",fontSize:"0.72rem",cursor:"pointer",fontWeight:w?600:400,transition:"all 0.15s"},children:[n.jsx(W.NtdCircle,{size:8,style:{color:R.css}})," ",R.label]},R.value)})}),n.jsxs("form",{onSubmit:g,style:{display:"flex",gap:6,marginBottom:8},children:[n.jsx("input",{type:"text",value:o,onChange:R=>v(R.target.value),placeholder:i("playlistManager.searchPlaceholder","Search tracks, artists, albums..."),style:{flex:1,padding:"6px 12px",borderRadius:8,border:"1px solid var(--nice-border-color, #d1d5db)",background:"var(--nice-input-bg, #fff)",color:"var(--nice-text-primary, #1f2937)",fontSize:"0.82rem"}}),n.jsx("button",{type:"submit",disabled:o.trim().length<2||r,style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.82rem",cursor:"pointer",opacity:o.trim().length<2?.5:1},"aria-label":i("playlistManager.search","Search"),children:r?n.jsx(W.NtdClock,{size:14}):n.jsx(W.NtdSearch,{size:14})})]}),t.length>0&&n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4,alignItems:"center"},children:[n.jsxs("label",{style:{fontSize:"0.72rem",display:"flex",alignItems:"center",gap:4,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:h.size===t.length&&t.length>0,onChange:b}),i("playlistManager.selectAll","Select all")]}),n.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[t.length," ",i("playlistManager.results","results")]}),n.jsx("div",{style:{flex:1}}),h.size>0&&n.jsxs("button",{onClick:k,style:{padding:"3px 10px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #3b82f6)",color:"var(--btn-text, #fff)",fontSize:"0.72rem",cursor:"pointer"},children:[n.jsx(W.NtdPlus,{size:12})," ",i("playlistManager.addSelected","Add selected")," (",h.size,")"]})]}),n.jsx("div",{style:{maxHeight:300,overflowY:"auto",borderRadius:6,border:"1px solid var(--nice-border-color, #e5e7eb)"},children:t.map(R=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:"1px solid var(--nice-border-color, #f3f4f6)",background:h.has(R.id)?"var(--nice-accent-tint-10, #eff6ff)":"transparent",cursor:"pointer",fontSize:"0.78rem"},onClick:()=>S(R.id),children:[n.jsx("input",{type:"checkbox",checked:h.has(R.id),readOnly:!0}),N(R.source),R.imageUrl&&n.jsx("img",{src:R.imageUrl,alt:R.title||i("common.coverArt","Cover art"),style:{width:28,height:28,borderRadius:4,objectFit:"cover"}}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:R.title}),n.jsxs("div",{style:{fontSize:"0.7rem",opacity:.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[R.artist,R.album?` — ${R.album}`:""]})]}),n.jsx("span",{style:{opacity:.5,fontSize:"0.7rem",flexShrink:0},children:j(R.duration)}),s&&n.jsx("button",{onClick:w=>{w.stopPropagation(),s(R)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem"},title:i("playlistManager.preview","Preview"),"aria-label":i("playlistManager.preview","Preview"),children:n.jsx(W.NtdPlay,{size:14})})]},R.id))})]}),r&&n.jsxs("div",{style:{textAlign:"center",padding:20,opacity:.5,fontSize:"0.82rem"},children:[n.jsx(W.NtdClock,{size:14})," ",i("playlistManager.searching","Searching"),"..."]}),!r&&o.trim().length>=2&&t.length===0&&n.jsx("div",{style:{textAlign:"center",padding:20,opacity:.4,fontSize:"0.82rem"},children:i("playlistManager.noResults","No results")})]})]})},kf=[{value:1,label:"Spotify",icon:n.jsx(W.NtdMusic,{size:16}),color:"var(--source-spotify, #1db954)"},{value:2,label:"Tidal",icon:n.jsx(W.NtdMusic,{size:16}),color:"var(--source-tidal, #000000)"},{value:3,label:"Apple Music",icon:n.jsx(W.NtdMusic,{size:16}),color:"var(--source-apple, #fa243c)"},{value:4,label:"YouTube",icon:n.jsx(W.NtdMusic,{size:16}),color:"var(--source-youtube, #ff0000)"},{value:99,label:"Manual Paste",icon:n.jsx(W.NtdMusic,{size:16}),color:"var(--source-manual, #6366f1)"}],wf={display:"flex",flexDirection:"column",gap:16,padding:24,borderRadius:12,background:"var(--nice-bg-primary, #ffffff)",border:"1px solid var(--nice-border, #e2e8f0)",maxWidth:640,minHeight:400},Cf={display:"flex",justifyContent:"space-between",alignItems:"center"},jf={display:"flex",gap:4,marginBottom:8},Ln={padding:"8px 20px",borderRadius:6,border:"none",background:"var(--nice-color-accent, #6366f1)",color:"var(--nice-text-on-primary, #fff)",cursor:"pointer",fontWeight:600},sr={...Ln,background:"transparent",color:"var(--nice-text-primary, #334155)",border:"1px solid var(--nice-border, #e2e8f0)"},ci={padding:12,borderRadius:8,border:"1px solid var(--nice-border, #e2e8f0)",cursor:"pointer",transition:"border-color 0.15s"},Cl=["connect","browse","tracks","options","importing","done"];function Mf(e){return Cl.indexOf(e)}function Rf(e){if(!e)return"--:--";const t=Math.floor(e/60),r=Math.floor(e%60);return`${t}:${r.toString().padStart(2,"0")}`}const jl=({connections:e=[],onConnect:t=()=>{},onDisconnect:r=()=>{},onFetchPlaylists:a=async()=>[],onFetchTracks:s=async()=>[],onImport:i=async()=>({playlistName:"",imported:0,skipped:0,failed:0,failedTracks:[]}),onClose:o=()=>{},targetFolders:l,sources:c})=>{const{t:d}=Te(),[h,f]=u.useState("connect"),[p,y]=u.useState(null),[m,x]=u.useState([]),[v,g]=u.useState(null),[S,b]=u.useState([]),[k,j]=u.useState(new Set),[N,R]=u.useState(!1),[w,M]=u.useState(null),[I,A]=u.useState(null),[T,O]=u.useState(null),[E,V]=u.useState({mergeTags:!0,mergeFolders:!0,overwriteExisting:!1}),[ee,z]=u.useState(""),q=u.useMemo(()=>new Set(e.filter(Z=>Z.connected).map(Z=>Z.platform)),[e]),K=u.useCallback(Z=>e.find(Y=>Y.platform===Z),[e]),re=u.useCallback(Z=>{if(y(Z),Z===99){f("tracks"),z(""),b([]),R(!1);return}q.has(Z)?(f("browse"),R(!0),O(null),a(Z).then(Y=>{x(Y),R(!1)}).catch(Y=>{O(String(Y)),R(!1)})):t(Z)},[q,t,a]),_=u.useCallback(Z=>{g(Z),f("tracks"),R(!0),O(null),s(Z).then(Y=>{b(Y),j(new Set(Y.map(se=>se.externalId))),R(!1)}).catch(Y=>{O(String(Y)),R(!1)})},[s]),U=u.useCallback(Z=>{j(Y=>{const se=new Set(Y);return se.has(Z)?se.delete(Z):se.add(Z),se})},[]),$=u.useCallback(()=>{j(Z=>Z.size===S.length?new Set:new Set(S.map(Y=>Y.externalId)))},[S]),P=u.useCallback(async()=>{if(!v)return;const Z=S.filter(Y=>k.has(Y.externalId));if(Z.length!==0){f("importing"),M({total:Z.length,imported:0,skipped:0,failed:0}),O(null);try{const Y=await i(v,Z,E),se=Y&&typeof Y=="object"&&"imported"in Y?Y:{playlistName:v.name,imported:Z.length,skipped:0,failed:0,failedTracks:[]};A(se),f("done")}catch(Y){O(String(Y)),f("options")}}},[v,S,k,E,i]),F=h!=="connect"&&h!=="importing"&&h!=="done",D=u.useCallback(()=>{switch(h){case"browse":f("connect");break;case"tracks":f("browse");break;case"options":f("tracks");break}},[h]),C=()=>n.jsx("div",{style:jf,children:Cl.map((Z,Y)=>n.jsx("div",{style:{flex:1,height:4,borderRadius:2,background:Y<=Mf(h)?"var(--nice-color-accent, #6366f1)":"var(--nice-border, #e2e8f0)",transition:"background 0.2s"}},Z))}),L=()=>n.jsxs("div",{style:{display:"grid",gap:12},children:[n.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlatform","Select a music platform to import from")}),kf.map(Z=>{const Y=K(Z.value),se=q.has(Z.value);return n.jsxs("div",{style:{...ci,display:"flex",alignItems:"center",gap:12,borderColor:se?Z.color:void 0},onClick:()=>re(Z.value),role:"button",tabIndex:0,onKeyDown:ae=>ae.key==="Enter"&&re(Z.value),children:[n.jsx("span",{style:{color:Z.color,display:"inline-flex"},"aria-hidden":"true",children:Z.icon}),n.jsxs("div",{style:{flex:1},children:[n.jsx("strong",{children:Z.label}),(Y==null?void 0:Y.username)&&n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:Y.username})]}),se?n.jsxs("span",{style:{color:Z.color,fontSize:12,fontWeight:600},children:[d("importWizard.connected","Connected")," ",n.jsx(W.NtdCheck,{size:12})]}):n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.clickToConnect","Click to connect")})]},Z.value)})]}),B=()=>n.jsxs("div",{style:{display:"grid",gap:12},children:[n.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.selectPlaylist","Select a playlist to import")}),N?n.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loading","Loading playlists…")}):n.jsxs("div",{style:{display:"grid",gap:8,maxHeight:320,overflowY:"auto"},children:[m.map(Z=>n.jsxs("div",{style:{...ci,display:"flex",alignItems:"center",gap:12},onClick:()=>_(Z),role:"button",tabIndex:0,onKeyDown:Y=>Y.key==="Enter"&&_(Z),children:[Z.coverUrl&&n.jsx("img",{src:Z.coverUrl,alt:"",style:{width:48,height:48,borderRadius:6,objectFit:"cover"}}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.name}),Z.description&&n.jsx("div",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.description})]}),n.jsxs("span",{style:{fontSize:12,color:"var(--nice-text-dim, #64748b)",whiteSpace:"nowrap"},children:[Z.trackCount," ",d("importWizard.tracks","tracks")]})]},Z.id)),m.length===0&&n.jsx("div",{style:{textAlign:"center",padding:24,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.noPlaylists","No playlists found")})]})]}),G=u.useCallback(Z=>{const se=Z.split(`
68
+ `).map(ae=>ae.trim()).filter(Boolean).map((ae,ue)=>{const J=ae.match(/^(.+?)\s*[-–—]\s*(.+)$/);return J?{externalId:`paste-${ue}`,title:J[2].trim(),artist:J[1].trim(),album:void 0,duration:0}:{externalId:`paste-${ue}`,title:ae,artist:"",album:void 0,duration:0}});b(se),j(new Set(se.map(ae=>ae.externalId)))},[]),H=()=>n.jsxs("div",{style:{display:"grid",gap:12},children:[p===99&&S.length===0&&n.jsxs("div",{style:{display:"grid",gap:8},children:[n.jsx("p",{style:{margin:0,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.pasteInstructions",'Paste your track list below (one track per line). Use "Artist - Title" format for best results.')}),n.jsx("textarea",{value:ee,onChange:Z=>z(Z.target.value),placeholder:`Daft Punk - Get Lucky
69
69
  The Weeknd - Blinding Lights
70
- Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),r.jsx("button",{style:{...En,opacity:Z.trim().length===0?.5:1},disabled:Z.trim().length===0,onClick:()=>G(Z),type:"button",children:u("importWizard.parseTracks","Parse Tracks")})]}),(f!==99||k.length>0)&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsxs("p",{style:{margin:0,fontWeight:600},children:[x==null?void 0:x.name," — ",S.size,"/",k.length," ",u("importWizard.selected","selected")]}),r.jsx("button",{style:rr,onClick:j,type:"button",children:S.size===k.length?u("importWizard.deselectAll","Deselect All"):u("importWizard.selectAll","Select All")})]}),R?r.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--text-dim, #64748b)"},children:u("importWizard.loadingTracks","Loading tracks…")}):r.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:r.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[r.jsx("thead",{children:r.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",textAlign:"left"},children:[r.jsx("th",{style:{padding:"4px 8px",width:32}}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.title","Title")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.artist","Artist")}),r.jsx("th",{style:{padding:"4px 8px"},children:u("importWizard.album","Album")}),r.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:u("importWizard.duration","Duration")})]})}),r.jsx("tbody",{children:k.map(V=>{const K=S.has(V.externalId);return r.jsxs("tr",{style:{borderBottom:"1px solid var(--border, #e2e8f0)",opacity:K?1:.5,cursor:"pointer"},onClick:()=>W(V.externalId),children:[r.jsx("td",{style:{padding:"6px 8px"},children:r.jsx("input",{type:"checkbox",checked:K,readOnly:!0})}),r.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:V.title}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:V.artist}),r.jsx("td",{style:{padding:"6px 8px",color:"var(--text-dim, #64748b)"},children:V.album??"—"}),r.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--text-dim, #64748b)"},children:vf(V.duration)})]},V.externalId)})})]})}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsxs("button",{style:{...En,opacity:S.size===0?.5:1},disabled:S.size===0,onClick:()=>p("options"),type:"button",children:[u("importWizard.next","Next")," →"]})})]})]}),X=()=>r.jsxs("div",{style:{display:"grid",gap:16},children:[r.jsx("p",{style:{margin:0,fontWeight:600},children:u("importWizard.importOptions","Import options")}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.mergeTags,onChange:V=>U(K=>({...K,mergeTags:V.target.checked}))}),u("importWizard.mergeTags","Merge tags from source playlist")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.mergeFolders,onChange:V=>U(K=>({...K,mergeFolders:V.target.checked}))}),u("importWizard.mergeFolders","Merge into existing folder structure")]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:L.overwriteExisting,onChange:V=>U(K=>({...K,overwriteExisting:V.target.checked}))}),u("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&r.jsxs("div",{style:{display:"grid",gap:4},children:[r.jsx("label",{style:{fontSize:13,fontWeight:500},children:u("importWizard.targetFolder","Target folder")}),r.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border, #e2e8f0)"},value:L.targetFolderId??"",onChange:V=>U(K=>({...K,targetFolderId:V.target.value||void 0})),children:[r.jsx("option",{value:"",children:u("importWizard.root","— Root —")}),l.map(V=>r.jsx("option",{value:V.id,children:V.name},V.id))]})]}),r.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--info-bg, #eff6ff)",fontSize:13},children:u("importWizard.summary",`Ready to import ${S.size} tracks from "${(x==null?void 0:x.name)??""}"`)}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[r.jsx("button",{style:rr,onClick:P,type:"button",children:u("importWizard.back","← Back")}),r.jsx("button",{style:En,onClick:F,type:"button",children:u("importWizard.startImport","Start Import")})]})]}),ie=()=>{const V=C?Math.round(C.imported/C.total*100):0;return r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.importing","Importing…")}),r.jsx("div",{style:{height:8,borderRadius:4,background:"var(--border, #e2e8f0)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${V}%`,background:"var(--accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),C&&r.jsxs("div",{style:{fontSize:13,color:"var(--text-dim, #64748b)"},children:[C.imported," / ",C.total," ",u("importWizard.tracks","tracks"),C.currentTrack&&r.jsxs("div",{style:{marginTop:4},children:[r.jsx(se.NtdMusic,{size:12})," ",C.currentTrack]})]})]})},le=()=>r.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[r.jsx("span",{style:{display:"inline-flex",justifyContent:"center"},"aria-hidden":"true",children:r.jsx(se.NtdCheck,{size:48})}),r.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:u("importWizard.complete","Import Complete")}),O&&r.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[r.jsxs("div",{children:[r.jsx("strong",{children:O.imported})," ",u("importWizard.imported","imported")]}),O.skipped>0&&r.jsxs("div",{style:{color:"var(--warning, #f59e0b)"},children:[O.skipped," ",u("importWizard.skipped","skipped (duplicates)")]}),O.failed>0&&r.jsxs("div",{style:{color:"var(--error, #ef4444)"},children:[O.failed," ",u("importWizard.failed","failed")]}),O.failedTracks.length>0&&r.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--text-dim, #64748b)"},children:[r.jsx("summary",{style:{cursor:"pointer"},children:u("importWizard.showFailed","Show failed tracks")}),r.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:O.failedTracks.map((V,K)=>r.jsx("li",{children:V},K))})]})]}),r.jsx("button",{style:En,onClick:o,type:"button",children:u("importWizard.close","Done")})]}),te={connect:u("importWizard.stepConnect","Connect"),browse:u("importWizard.stepBrowse","Browse"),tracks:u("importWizard.stepTracks","Select Tracks"),options:u("importWizard.stepOptions","Options"),importing:u("importWizard.stepImporting","Importing"),done:u("importWizard.stepDone","Done")};return r.jsxs("div",{style:gf,children:[T(),r.jsxs("div",{style:yf,children:[r.jsxs("h2",{style:{margin:0,fontSize:18},children:[u("importWizard.title","Import Playlist")," — ",te[h]]}),I&&r.jsxs("button",{style:rr,onClick:P,type:"button",children:["← ",u("importWizard.back","Back")]}),h==="connect"&&r.jsx("button",{style:rr,onClick:o,type:"button","aria-label":u("importWizard.close","Close"),title:u("importWizard.close","Close"),children:r.jsx(se.NtdClose,{size:14})})]}),E&&r.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--error-bg, #fef2f2)",color:"var(--error, #ef4444)",fontSize:13},children:E}),h==="connect"&&z(),h==="browse"&&B(),h==="tracks"&&Y(),h==="options"&&X(),h==="importing"&&ie(),h==="done"&&le()]})},Sf=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",emoji:"🎵",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",emoji:"🍀",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",emoji:"🔺",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",emoji:"✨",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",emoji:"🔇",dir:null}],kf="concert-harp",os=Object.fromEntries(Sf.map(e=>[e.id,e])),wf="nice2dev-note-sound-set";function jl(){try{const e=localStorage.getItem(wf);if(e&&os[e])return e}catch{}return kf}function li(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function Cl(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const n=t.fillStyle;if(n.startsWith("#")){const s=parseInt(n.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function Jr(e,t){const n=Cl(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function jf(e){const t=Cl(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Ml(){const e=li("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=li("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",s=jf(e)<.45;return{base:Jr(e,.92),staffLine:Jr(e,.22),outline:s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[Jr(t,.95)],isDark:n,notesDark:s}}const zr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Rl=46,wt=5,pr=4,Cf=(Rl-(wt-1)*pr)/2,Mf=6,Rf=18,Nf=110,Tf=50,Or=zr?Tf:Nf,$f=zr?4:2,Pf=zr?2:4,ci=zr?1:0,Af=180,di=2.8,ui=40,Ef=14,hi=1.2,If=16,ea=[64,67,71,74,77],rn=64,In=77;function Lf(e){const t=Math.max(0,Math.min(wt-1,e)),n=Math.floor(t),a=Math.min(n+1,wt-1),s=t-n;return Math.round(ea[n]+(ea[a]-ea[n])*s)}function Df(e){return(Math.max(rn-1*(In-rn)/(wt-1),Math.min(In+1*(In-rn)/(wt-1),e))-rn)/(In-rn)*(wt-1)}const pi=2.5,fi=.72,_f=.55,Ln=new Map;let fr=null;async function Ff(e){const t=e??jl(),n=os[t];if(!n||!n.dir){Ln.clear(),fr=t;return}if(fr===t&&Ln.size>0)return;Ln.clear(),fr=t;const a=mn(),s=[];for(let i=rn;i<=In;i++)s.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{Ln.set(i,o)}).catch(()=>{}));await Promise.all(s)}function mi(e){const t=Ln.get(e);if(!t)return;const n=mn(),a=n.createBufferSource();a.buffer=t;const s=n.createGain();s.gain.value=.7,a.connect(s).connect(n.destination),a.start()}const gi=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function zf(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Of(e){const t=zf(42),n=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(wt+1)-.5,char:gi[Math.floor(t()*gi.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return n.sort((a,s)=>a.x-s.x),n}const ut=Of(Or),kn=new Float32Array(Or),ar=new Float32Array(Or),Dn=new Float32Array(Or);let ba=!1;const Bf=(wt-1)/2;function Gf(){if(!ba){ba=!0;for(let e=0;e<ut.length;e++)Dn[e]=ut[e].lineIdx}}let xa=[],yi="";function Wf(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Uf(e){const t=Wf(e);t===yi&&xa.length===ut.length||(yi=t,xa=ut.map(n=>{const a=Math.ceil(n.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(n.rot*Math.PI/180),o.font=`${n.size}px serif`,o.textAlign="center",o.textBaseline="middle",o.lineWidth=1.8,o.strokeStyle=e.outline,o.strokeText(n.char,0,0),o.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],o.fillText(n.char,0,0),{canvas:i,ox:a,oy:a}}))}function Nl({pitchMidiRef:e}={}){const t=d.useRef(null),n=d.useRef(0),a=d.useRef(0),s=d.useRef(0),i=d.useRef(null),o=d.useRef(0),l=d.useRef(0),c=d.useRef(null),u=d.useRef(null),h=d.useRef(!1),p=d.useCallback((v,x,g)=>{const k=Cf+v*pr,b=x/g*Math.PI*2;return k+Math.sin(b)*Mf},[]),f=d.useCallback(v=>{const x=t.current;if(!x)return;if(l.current++,ci>0&&l.current%(ci+1)!==0){s.current=v,n.current=requestAnimationFrame(f);return}const g=x.getContext("2d");if(!g)return;const k=Math.min(window.devicePixelRatio||1,Pf),b=x.getBoundingClientRect(),S=b.width,M=b.height;(x.width!==Math.round(S*k)||x.height!==Math.round(M*k))&&(x.width=Math.round(S*k),x.height=Math.round(M*k),g.setTransform(k,0,0,k,0,0));const R=s.current?(v-s.current)/1e3:0;s.current=v,a.current=(a.current+Rf*R)%S,g.clearRect(0,0,S,M),o.current++,(!i.current||o.current%60===0)&&(i.current=Ml());const N=i.current;Uf(N),g.strokeStyle=N.staffLine,g.lineWidth=.7;for(let $=0;$<wt;$++){g.beginPath();for(let E=0;E<=S;E+=$f){const _=p($,E,S);E===0?g.moveTo(E,_):g.lineTo(E,_)}g.stroke()}const C=a.current,w=(e==null?void 0:e.current)??null;if(w!==null){Gf();const $=Df(w),E=pi*R;for(let _=0;_<ut.length;_++){const U=(ut[_].lineIdx-Bf)*_f,A=$*fi+($+U)*(1-fi)-Dn[_];Dn[_]+=A>0?Math.min(E,A):Math.max(-E,A)}}else if(ba){const $=pi*.4*R;for(let E=0;E<ut.length;E++){const L=ut[E].lineIdx-Dn[E];Dn[E]+=L>0?Math.min($,L):Math.max(-$,L)}}const O=c.current;O&&(O.timer-=R,O.timer<=0&&(c.current=null));for(let $=0;$<ut.length;$++){const E=ut[$];if(ar[$]>0){ar[$]-=R;const U=Math.max(0,ar[$]/di);kn[$]+=Af*U*R,kn[$]>S&&(kn[$]-=S)}const _=xa[$];if(!_)continue;const L=E.lineIdx;for(let U=0;U<2;U++){let A=((E.x*S-C-kn[$]+U*S)%S+S)%S;const q=p(Math.max(0,Math.min(wt-1,Math.round(L))),A,S),H=(L-Math.round(L))*pr;let re=q+H;if(O&&O.timer>0){const D=A-O.x,W=re-O.y,j=Math.sqrt(D*D+W*W);if(j<ui&&j>.1){const F=O.timer/hi,I=Ef*(1-j/ui)*F;A+=D/j*I,re+=W/j*I}}g.drawImage(_.canvas,A-_.ox,re-_.oy)}}n.current=requestAnimationFrame(f)},[p]),y=d.useCallback(v=>{const x=t.current;if(!x)return;const g=x.getBoundingClientRect(),k=v.clientX-g.left,b=v.clientY-g.top,S=g.width,M=a.current;let R=1/0,N=-1;for(let C=0;C<ut.length;C++){const w=ut[C],$=((w.x*S-M-kn[C])%S+S)%S,E=p(Math.max(0,Math.min(wt-1,Math.round(w.lineIdx))),$,S),_=(w.lineIdx-Math.round(w.lineIdx))*pr,L=E+_,U=$-k,Z=L-b,A=U*U+Z*Z;A<R&&(R=A,N=C)}if(N>=0&&Math.sqrt(R)<If){ar[N]=di;const C=ut[N],w=Lf(C.lineIdx);try{Bt();const O=jl(),$=os[O];$!=null&&$.dir&&(fr!==O||!h.current?(h.current=!0,Ff(O).then(()=>mi(w))):mi(w))}catch{}}c.current={x:k,y:b,timer:hi}},[p]),m=d.useCallback(v=>{const x=t.current;if(!x)return;const g=x.getBoundingClientRect(),k=v.clientX-g.left,b=v.clientY-g.top;u.current={x:k,y:b},c.current&&c.current.timer>0&&(c.current.x=k,c.current.y=b)},[]);return d.useEffect(()=>(n.current=requestAnimationFrame(f),()=>cancelAnimationFrame(n.current)),[f]),r.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:m,style:{display:"block",width:"100%",height:Rl,marginBottom:5,cursor:"pointer",background:"transparent"}})}const qf=14,Vf=.9,Hf=320,Kf=160,Yf=6,bi=8,Zf=14,xi=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function Tl(){const e=d.useRef(null),t=d.useRef([]),n=d.useRef(0),a=d.useRef(0),s=d.useRef([]),i=d.useRef(null),o=d.useRef(0),l=d.useCallback((u,h)=>{for(let p=0;p<qf;p++){const f=Math.random()*Math.PI*2,y=Kf*(.4+Math.random()*.6),m=Vf*(.6+Math.random()*.4),v=Math.random()<.15?0:-1;t.current.push({x:u,y:h,vx:Math.cos(f)*y,vy:Math.sin(f)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*Yf*2,size:bi+Math.random()*(Zf-bi),char:xi[Math.floor(Math.random()*xi.length)],life:m,maxLife:m,colorIdx:v})}},[]),c=d.useCallback(u=>{const h=e.current;if(!h){n.current=requestAnimationFrame(c);return}const p=h.getContext("2d");if(!p){n.current=requestAnimationFrame(c);return}const f=window.devicePixelRatio||1,y=window.innerWidth,m=window.innerHeight;(h.width!==Math.round(y*f)||h.height!==Math.round(m*f))&&(h.width=Math.round(y*f),h.height=Math.round(m*f),h.style.width=`${y}px`,h.style.height=`${m}px`,p.setTransform(f,0,0,f,0,0));const v=a.current?Math.min((u-a.current)/1e3,.05):0;a.current=u,p.clearRect(0,0,y,m),o.current++,(!i.current||o.current%60===0)&&(i.current=Ml());const x=i.current;if(navigator.getGamepads){const k=navigator.getGamepads();for(let b=0;b<k.length;b++){const S=k[b];if(S)for(let M=0;M<S.buttons.length;M++){const R=b*100+M,N=S.buttons[M].pressed;N&&!s.current[R]&&l(y/2,m/2),s.current[R]=N}}}const g=[];p.textAlign="center",p.textBaseline="middle";for(const k of t.current){if(k.life-=v,k.life<=0)continue;k.vy+=Hf*v,k.x+=k.vx*v,k.y+=k.vy*v,k.rot+=k.vr*v;const b=Math.max(0,k.life/k.maxLife),S=.5+.5*b;p.save(),p.globalAlpha=b,p.translate(k.x,k.y),p.rotate(k.rot),p.font=`${k.size*S}px serif`,p.lineWidth=1.4,p.strokeStyle=x.notesDark?`rgba(255,255,255,${b*.8})`:`rgba(0,0,0,${b*.55})`,p.strokeText(k.char,0,0);const M=k.colorIdx<0?x.base:x.accents[k.colorIdx%x.accents.length];p.fillStyle=M.replace(/[\d.]+\)$/,`${b})`),p.fillText(k.char,0,0),p.restore(),g.push(k)}t.current=g,n.current=requestAnimationFrame(c)},[l]);return d.useEffect(()=>{const u=p=>{l(p.clientX,p.clientY)},h=p=>{if(p.key!=="Enter")return;const f=document.activeElement;if(f){const y=f.getBoundingClientRect();l(y.left+y.width/2,y.top+y.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",u,!0),window.addEventListener("keydown",h,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",u,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(n.current)}},[c,l]),r.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const mr={type:"gain",enabled:!0,mix:1,gain:0},_n={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},Fn={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},zn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},gr={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},yr={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},br={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},xr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},vr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},Sr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},Xf={gain:{unity:{...mr,gain:0},boost:{...mr,gain:6},cut:{...mr,gain:-6}},compressor:{gentle:{..._n,threshold:-20,ratio:2,attack:30,release:200},moderate:{..._n,threshold:-24,ratio:4,attack:10,release:100},aggressive:{..._n,threshold:-30,ratio:8,attack:1,release:50},limiter:{..._n,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...Fn,decay:.5,roomSize:.2,damping:.7},large_hall:{...Fn,decay:3,roomSize:.8,damping:.3},plate:{...Fn,decay:1.5,roomSize:.5,damping:.4},cathedral:{...Fn,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...zn,time:80,feedback:.1,mix:.3},quarter_note:{...zn,time:500,feedback:.4,mix:.3},dotted_eighth:{...zn,time:375,feedback:.5,mix:.3},long_ambient:{...zn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...gr,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...gr,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...gr,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...yr,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...yr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...yr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...br,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...br,filterType:"highpass",frequency:100,q:.7},telephone:{...br,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...xr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...xr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...xr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...vr,rate:3,depth:.4,waveform:"sine"},fast:{...vr,rate:8,depth:.6,waveform:"sine"},choppy:{...vr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...Sr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...Sr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...Sr,rate:1,depth:.5,feedback:.4,stages:6}}};function vi(e){return Math.pow(10,e/20)}function Qf(e,t,n,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let u=0;u<i;u++){const h=u/s,p=Math.exp(-h/n),f=1-a*(u/i);c[u]=(Math.random()*2-1)*p*f}}return o}function Jf(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class em{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,n){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return n!==void 0&&n>=0&&n<this.effects.length?this.effects.splice(n,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const n=this.effects.findIndex(s=>s.id===t);if(n===-1)return!1;const a=this.effects[n];for(const s of a.nodes)s.disconnect();return this.effects.splice(n,1),this.reconnectChain(),!0}updateEffect(t,n){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...n},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,n){if(t<0||t>=this.effects.length||n<0||n>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(n,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const n of t.nodes)n.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,n){const{audioContext:a}=this,s=[];let i,o;switch(n.type){case"gain":{const l=a.createGain();l.gain.value=vi(n.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=n.threshold,l.ratio.value=n.ratio,l.attack.value=n.attack/1e3,l.release.value=n.release/1e3,l.knee.value=n.knee;const c=a.createGain();c.gain.value=vi(n.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=Qf(a,n.decay,n.decay,n.damping);const c=a.createGain(),u=a.createGain(),h=a.createGain(),p=a.createGain();c.gain.value=n.mix,u.gain.value=1-n.mix,h.connect(l),h.connect(u),l.connect(c),c.connect(p),u.connect(p),s.push(h,l,c,u,p),i=h,o=p;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=n.time/1e3;const c=a.createGain();c.gain.value=n.feedback;const u=a.createBiquadFilter();u.type="lowpass",u.frequency.value=n.highCut;const h=a.createGain(),p=a.createGain(),f=a.createGain(),y=a.createGain();h.gain.value=n.mix,p.gain.value=1-n.mix,f.connect(l),f.connect(p),l.connect(u),u.connect(c),c.connect(l),u.connect(h),h.connect(y),p.connect(y),s.push(f,l,u,c,h,p,y),i=f,o=y;break}case"eq":{const l=[];let c=null;for(const u of n.bands){const h=a.createBiquadFilter();h.type=u.type,h.frequency.value=u.frequency,h.Q.value=u.q,h.gain.value=u.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=n.filterType,l.frequency.value=n.frequency,l.Q.value=n.q,l.gain.value=n.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=Jf(n.drive,n.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+n.tone*1e4;const u=a.createGain(),h=a.createGain(),p=a.createGain(),f=a.createGain();u.gain.value=n.mix,h.gain.value=1-n.mix,p.connect(l),p.connect(h),l.connect(c),c.connect(u),u.connect(f),h.connect(f),s.push(p,l,c,u,h,f),i=p,o=f;break}case"tremolo":{const l=a.createOscillator();l.type=n.waveform,l.frequency.value=n.rate;const c=a.createGain();c.gain.value=n.depth*.5;const u=a.createGain();u.gain.value=1-n.depth*.5,l.connect(c),c.connect(u.gain),l.start(),s.push(l,c,u),i=o=u;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=n.rate;const u=a.createGain();u.gain.value=n.depth*n.frequency;let h=null;for(let v=0;v<n.stages;v++){const x=a.createBiquadFilter();x.type="allpass",x.frequency.value=n.frequency,x.Q.value=.5,c.connect(u),u.connect(x.frequency),h&&h.connect(x),h=x,l.push(x)}const p=a.createGain(),f=a.createGain(),y=a.createGain(),m=a.createGain();p.gain.value=n.mix,f.gain.value=1-n.mix,y.connect(l[0]),y.connect(f),l[l.length-1].connect(p),p.connect(m),f.connect(m),c.start(),s.push(c,u,...l,p,f,y,m),i=y,o=m;break}default:throw new Error(`Unknown effect type: ${n.type}`)}return{id:t,params:n,nodes:s,input:i,output:o}}reconnectChain(){this.inputNode.disconnect();for(const n of this.effects)n.output.disconnect();if(this.bypass||this.effects.length===0){this.inputNode.connect(this.outputNode);return}let t=this.inputNode;for(const n of this.effects)n.params.enabled&&(t.connect(n.input),t=n.output);t.connect(this.outputNode)}dispose(){this.clear(),this.inputNode.disconnect(),this.outputNode.disconnect()}}const $l={gain:r.jsx(se.NtdVolume,{size:16}),compressor:r.jsx(se.NtdSettings,{size:16}),reverb:r.jsx(se.NtdMountain,{size:16}),delay:r.jsx(se.NtdStopwatch,{size:16}),chorus:r.jsx(se.NtdSparkle,{size:16}),eq:r.jsx(se.NtdBarChart,{size:16}),filter:r.jsx(se.NtdFilter,{size:16}),distortion:r.jsx(se.NtdLightning,{size:16}),tremolo:r.jsx(se.NtdWave,{size:16}),phaser:r.jsx(se.NtdMagicWand,{size:16})},Pl={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},tm={gain:mr,compressor:_n,reverb:Fn,delay:zn,chorus:gr,eq:yr,filter:br,distortion:xr,tremolo:vr,phaser:Sr},nm=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],Le=({value:e,min:t,max:n,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=d.useRef(null),[u,h]=d.useState(!1),p=d.useRef(0),f=d.useRef(e),y=d.useCallback(v=>{l||(v.preventDefault(),h(!0),p.current=v.clientY,f.current=e)},[l,e]);d.useEffect(()=>{if(!u)return;const v=g=>{const k=p.current-g.clientY,b=n-t,M=k/200*b,R=Math.min(n,Math.max(t,f.current+M));o(a<1?R:Math.round(R/a)*a)},x=()=>{h(!1)};return document.addEventListener("mousemove",v),document.addEventListener("mouseup",x),()=>{document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",x)}},[u,t,n,a,o]);const m=(e-t)/(n-t)*270-135;return r.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[r.jsx("div",{className:`nice-fx-knob__dial ${u?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:r.jsx("div",{className:"nice-fx-knob__indicator"})}),r.jsx("div",{className:"nice-fx-knob__label",children:s}),r.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function rm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx(Le,{value:e.gain,min:-60,max:12,step:.1,label:"Gain",unit:"dB",onChange:u=>t({...e,gain:u}),disabled:!e.enabled})})}function am({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.threshold,min:-60,max:0,label:"Threshold",unit:"dB",onChange:u=>t({...e,threshold:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.ratio,min:1,max:20,label:"Ratio",onChange:u=>t({...e,ratio:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.attack,min:.1,max:200,label:"Attack",unit:"ms",onChange:u=>t({...e,attack:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.release,min:10,max:1e3,label:"Release",unit:"ms",onChange:u=>t({...e,release:u}),disabled:!e.enabled}),!c&&r.jsxs(r.Fragment,{children:[r.jsx(Le,{value:e.knee,min:0,max:40,label:"Knee",unit:"dB",onChange:u=>t({...e,knee:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.makeupGain,min:0,max:24,label:"Makeup",unit:"dB",onChange:u=>t({...e,makeupGain:u}),disabled:!e.enabled})]})]})})}function sm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.decay,min:.1,max:10,step:.1,label:"Decay",unit:"s",onChange:u=>t({...e,decay:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.damping,min:0,max:1,step:.01,label:"Damping",onChange:u=>t({...e,damping:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.roomSize,min:0,max:1,step:.01,label:"Room",onChange:u=>t({...e,roomSize:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function im({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.time,min:0,max:2e3,label:"Time",unit:"ms",onChange:u=>t({...e,time:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.feedback,min:0,max:1,step:.01,label:"Feedback",onChange:u=>t({...e,feedback:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.highCut,min:200,max:2e4,label:"HiCut",unit:"Hz",onChange:u=>t({...e,highCut:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function om({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsxs("div",{className:"nice-fx-card__controls",children:[r.jsx(Le,{value:e.drive,min:0,max:1,step:.01,label:"Drive",onChange:u=>t({...e,drive:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.tone,min:0,max:1,step:.01,label:"Tone",onChange:u=>t({...e,tone:u}),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})]})})}function jt({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:u}){const[h,p]=d.useState(!1);return r.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[r.jsxs("div",{className:"nice-fx-card__header",children:[r.jsx("span",{className:"nice-fx-card__icon",children:$l[e.type]}),r.jsx("span",{className:"nice-fx-card__title",children:Pl[e.type]}),r.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:r.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),l&&Object.keys(o).length>0&&r.jsxs("div",{className:"nice-fx-card__presets",children:[r.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>p(!h),"aria-label":"Presets",children:r.jsx(se.NtdChevronDown,{size:12})}),h&&r.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(o).map(([f,y])=>r.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...y,enabled:e.enabled}),p(!1)},children:f.replace(/_/g," ")},f))})]}),r.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:n,title:"Remove",children:"×"})]}),r.jsx("div",{className:"nice-fx-card__body",children:u})]})}function lm({effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return r.jsx(jt,{effect:e,onChange:t,onRemove:n,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:r.jsx("div",{className:"nice-fx-card__generic",children:r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:u=>t({...e,mix:u}),disabled:!e.enabled})})})}function cm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??1.5,min:.1,max:10,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.3,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function dm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.low??0,min:-12,max:12,step:.5,label:"Low",onChange:i=>s("low",i),disabled:!e.enabled}),r.jsx(Le,{value:a.mid??0,min:-12,max:12,step:.5,label:"Mid",onChange:i=>s("mid",i),disabled:!e.enabled}),r.jsx(Le,{value:a.high??0,min:-12,max:12,step:.5,label:"High",onChange:i=>s("high",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function um({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.frequency??1e3,min:20,max:2e4,step:1,label:"Freq",onChange:i=>s("frequency",i),disabled:!e.enabled}),r.jsx(Le,{value:a.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:i=>s("Q",i),disabled:!e.enabled}),r.jsx(Le,{value:a.gain??0,min:-24,max:24,step:.5,label:"Gain",onChange:i=>s("gain",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function hm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??5,min:.1,max:20,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function pm({effect:e,onChange:t,...n}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return r.jsx(jt,{effect:e,onChange:t,...n,children:r.jsxs("div",{className:"nice-fx-card__row",children:[r.jsx(Le,{value:a.rate??.5,min:.01,max:8,step:.01,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),r.jsx(Le,{value:a.depth??.7,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),r.jsx(Le,{value:a.feedback??.5,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),r.jsx(Le,{value:a.stages??4,min:2,max:12,step:2,label:"Stages",onChange:i=>s("stages",i),disabled:!e.enabled}),r.jsx(Le,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}const fm=({audioContext:e,chain:t,effects:n,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=nm,showPresets:l=!0,compact:c=!1,className:u=""})=>{const[h,p]=d.useState((n==null?void 0:n.map(C=>C.params))||[]),[f,y]=d.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[m,v]=d.useState(!1),x=d.useMemo(()=>t||(e?new em(e):null),[e,t]),g=d.useCallback((C,w)=>{const O=[...h];O[C]=w,p(O),a==null||a(O),x&&(s==null||s(x))},[h,a,x,s]),k=d.useCallback(C=>{if(h.length>=i)return;const w={...tm[C]},O=[...h,w];p(O),a==null||a(O),v(!1)},[h,i,a]),b=d.useCallback(C=>{const w=h.filter((O,$)=>$!==C);p(w),a==null||a(w)},[h,a]),S=d.useCallback(C=>{y({isDragging:!0,dragIndex:C,dropIndex:-1})},[]),M=d.useCallback(()=>{if(f.dragIndex!==-1&&f.dropIndex!==-1&&f.dragIndex!==f.dropIndex){const C=[...h],[w]=C.splice(f.dragIndex,1);C.splice(f.dropIndex,0,w),p(C),a==null||a(C)}y({isDragging:!1,dragIndex:-1,dropIndex:-1})},[f,h,a]),R=d.useCallback((C,w)=>{C.preventDefault(),f.isDragging&&y(O=>({...O,dropIndex:w}))},[f.isDragging]),N=(C,w)=>{const O={onRemove:()=>b(w),onDragStart:()=>S(w),onDragEnd:M,isDragTarget:f.dropIndex===w,presets:Xf[C.type]||{},showPresets:l,compact:c};switch(C.type){case"gain":return r.jsx(rm,{effect:C,onChange:$=>g(w,$),...O},w);case"compressor":return r.jsx(am,{effect:C,onChange:$=>g(w,$),...O},w);case"reverb":return r.jsx(sm,{effect:C,onChange:$=>g(w,$),...O},w);case"delay":return r.jsx(im,{effect:C,onChange:$=>g(w,$),...O},w);case"distortion":return r.jsx(om,{effect:C,onChange:$=>g(w,$),...O},w);case"chorus":return r.jsx(cm,{effect:C,onChange:$=>g(w,$),...O},w);case"eq":return r.jsx(dm,{effect:C,onChange:$=>g(w,$),...O},w);case"filter":return r.jsx(um,{effect:C,onChange:$=>g(w,$),...O},w);case"tremolo":return r.jsx(hm,{effect:C,onChange:$=>g(w,$),...O},w);case"phaser":return r.jsx(pm,{effect:C,onChange:$=>g(w,$),...O},w);default:return r.jsx(lm,{effect:C,onChange:$=>g(w,$),...O},w)}};return r.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${u}`,children:[r.jsxs("div",{className:"nice-fx-rack__header",children:[r.jsx("h3",{className:"nice-fx-rack__title",children:"Effects Chain"}),r.jsxs("span",{className:"nice-fx-rack__count",children:[h.length,"/",i]})]}),r.jsx("div",{className:"nice-fx-rack__chain",children:h.length===0?r.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):h.map((C,w)=>r.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:O=>R(O,w),children:[N(C,w),w<h.length-1&&r.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:r.jsx(se.NtdArrowRight,{size:14})})]},w))}),h.length<i&&r.jsxs("div",{className:"nice-fx-rack__add",children:[r.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>v(!m),children:"+ Add Effect"}),m&&r.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(C=>r.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>k(C),children:[r.jsx("span",{className:"nice-fx-rack__add-icon",children:$l[C]}),r.jsx("span",{className:"nice-fx-rack__add-label",children:Pl[C]})]},C))})]})]})},Al=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Si(e,t,n){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,n)}return i}function sr(e){const t=Math.max(1,e),n=44100,a=new Float32Array(n),s=Math.PI/180;for(let i=0;i<n;i++){const o=i*2/n-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class El{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,n,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let n=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;n+=s*s}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,n);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const a of n.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,n=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,n),!0)}updateIntensity(t,n){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,n))}clearAllEffects(){for(const[t]of this.activeEffects){const n=this.activeEffects.get(t);if(n)for(const a of n.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,n]of this.activeEffects)try{n.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const n of this.effectOrder){const a=this.activeEffects.get(n);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const a=this.audioCtx,s=n/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,n,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),u=t.createDelay(1),h=t.createOscillator(),p=t.createOscillator(),f=t.createGain(),y=t.createGain(),m=n-1,v=Math.abs(m)*5+2,x=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=v,f.gain.value=x,h.connect(f),f.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=v,y.gain.value=x,p.connect(y),y.connect(u.delayTime),u.delayTime.value=.02+x;const g=t.createGain();g.gain.value=.5;const k=t.createGain();return k.gain.value=.5,s.connect(c),s.connect(u),c.connect(g),u.connect(k),g.connect(o),k.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),p.start(),{type:"chipmunk",nodes:[s,c,u,h,p,f,y,g,k,o,l,i],input:s,output:i}}buildRobot(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+n*.4;const o=t.createGain();o.gain.value=1-n*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+n*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+n*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const u=t.createGain();u.gain.value=.004,c.connect(u),u.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDelay(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,a);const u=t.createGain();u.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(u),i.connect(h),u.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,u,h,o],input:i,output:o}}buildCave(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+n*.3;const o=t.createDelay(2);o.delayTime.value=.35+n*.25;const l=t.createDelay(2);l.delayTime.value=.55+n*.3;const c=t.createGain();c.gain.value=.5;const u=t.createGain();u.gain.value=.35;const h=t.createGain();h.gain.value=.25;const p=t.createConvolver();p.buffer=Si(t,2+n*3,3);const f=t.createGain();f.gain.value=.3+n*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(u),u.connect(o),a.connect(l),l.connect(h),h.connect(l),i.connect(f),o.connect(f),l.connect(f),a.connect(p),p.connect(f);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),f.connect(s),{type:"cave",nodes:[a,i,o,l,c,u,h,p,f,y,s],input:a,output:s}}buildReverb(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createConvolver();l.buffer=Si(t,n,a);const c=t.createGain();c.gain.value=.4+s*.5;const u=t.createGain();return u.gain.value=1,i.connect(l),l.connect(c),i.connect(u),c.connect(o),u.connect(o),{type:"reverb",nodes:[i,l,c,u,o],input:i,output:o}}buildChorus(t,n){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const u=t.createDelay(.1);u.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),h.connect(p),p.connect(u.delayTime);const f=t.createGain();f.gain.value=.3+n*.2,a.connect(u),u.connect(f),f.connect(s),h.start(),o.push(u,h,p,f)}return{type:"chorus",nodes:o,input:a,output:s}}buildFlanger(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,o.connect(l),l.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const u=t.createGain();u.gain.value=.5+n*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(u),a.connect(h),u.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,u,h,s],input:a,output:s}}buildDistortion(t,n,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=sr(n),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,n,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=n,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=sr(15+n*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+n*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+n*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-n*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=sr(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-n)*400,i.Q.value=5+n*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const u=t.createGain();return u.gain.value=.3-n*.2,a.connect(i),i.connect(c),a.connect(u),c.connect(s),u.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,u,s],input:a,output:s}}buildWhisper(t,n){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+n*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let u=0;u<256;u++){const h=u/255*2-1;l[u]=Math.sign(h)*Math.pow(Math.abs(h),.3+n*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=sr(20+n*50),c.oversample="2x";const u=t.createBiquadFilter();u.type="lowshelf",u.frequency.value=200,u.gain.value=8+n*8;const h=t.createGain();h.gain.value=.7+n*.3;const p=t.createGain();return p.gain.value=.3,a.connect(i),i.connect(c),c.connect(u),u.connect(h),a.connect(p),h.connect(s),p.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,u,h,p,s],input:a,output:s}}buildTremolo(t,n){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,n){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,o.connect(l),l.connect(i.delayTime);const c=[],u=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of u){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+n*15,m.gain.value=4+n*8,a.connect(m),m.connect(h),c.push(m)}const p=t.createGain();p.gain.value=.7;const f=t.createGain();return f.gain.value=.5+n*.3,a.connect(i),i.connect(f),h.connect(f),a.connect(p),f.connect(s),p.connect(s),o.start(),{type:"autotune",nodes:[a,i,o,l,...c,h,f,p,s],input:a,output:s}}buildVocoder(t,n){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sawtooth",i.frequency.value=110+n*110;const o=t.createGain();o.gain.value=0;const l=8,c=[a,s,i,o],u=t.createGain();u.gain.value=.5+n*.5,c.push(u);for(let p=0;p<l;p++){const f=200*Math.pow(2,p*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=f,y.Q.value=4;const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=f,m.Q.value=4;const v=t.createGain();v.gain.value=0,a.connect(y),y.connect(v.gain),i.connect(m),m.connect(v),v.connect(u),c.push(y,m,v)}u.connect(s);const h=t.createGain();return h.gain.value=.3-n*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const mm={sparkle:se.NtdSparkle,music:se.NtdMusic,skull:se.NtdSkull,robot:se.NtdRobot,ghost:se.NtdGhost,mountain:se.NtdMountain,wave:se.NtdWave,lightning:se.NtdLightning,phone:se.NtdPhone,megaphone:se.NtdMegaphone,"volume-mute":se.NtdVolumeMute,microphone:se.NtdMicrophone,volume:se.NtdVolume},gm=({deviceId:e,mediaStream:t,compact:n=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:u}=Te(),h=a??u,p=d.useRef(null),[f,y]=d.useState(!1),[m,v]=d.useState(()=>Al.map(A=>({...A}))),[x,g]=d.useState(!0),[k,b]=d.useState(80),[S,M]=d.useState(100),[R,N]=d.useState(0),C=d.useRef(0),w=d.useCallback(()=>{const A=()=>{var q;(q=p.current)!=null&&q.isStarted&&(N(p.current.getLevel()),C.current=requestAnimationFrame(A))};C.current=requestAnimationFrame(A)},[]),O=d.useCallback(()=>{C.current&&cancelAnimationFrame(C.current)},[]),$=d.useCallback(async()=>{const A=new El;p.current=A;try{t?await A.startWithStream(t):await A.start(e),A.setMonitoring(x),A.setVolume(k/100),A.setInputGain(S/100);for(const q of m)q.enabled&&A.addEffect(q.type,q.intensity);y(!0),w()}catch(q){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",q)}},[e,t,x,k,S,m,w]),E=d.useCallback(()=>{var A;O(),(A=p.current)==null||A.stop(),p.current=null,y(!1),N(0)},[O]);d.useEffect(()=>()=>{var A;O(),(A=p.current)==null||A.stop(),p.current=null},[O]);const _=d.useCallback(A=>{v(q=>q.map(H=>{var D;if(H.type!==A)return H;const re={...H,enabled:!H.enabled};return(D=p.current)!=null&&D.isStarted&&(re.enabled?p.current.addEffect(A,re.intensity):p.current.removeEffect(A)),re}))},[]),L=d.useCallback((A,q)=>{v(H=>H.map(re=>{var D;return re.type!==A?re:(re.enabled&&((D=p.current)!=null&&D.isStarted)&&p.current.updateIntensity(A,q),{...re,intensity:q})}))},[]);d.useEffect(()=>{var A;(A=p.current)==null||A.setVolume(k/100)},[k]),d.useEffect(()=>{var A;(A=p.current)==null||A.setInputGain(S/100)},[S]),d.useEffect(()=>{var A;(A=p.current)==null||A.setMonitoring(x)},[x]);const U=d.useCallback(()=>{var A;(A=p.current)==null||A.clearAllEffects(),v(q=>q.map(H=>({...H,enabled:!1})))},[]),Z=m.filter(A=>A.enabled).length;return l==="hidden"?null:r.jsxs("div",{className:`nice-vocal-effects-rack${s?` ${s}`:""}`,style:{border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:n?12:20,background:"var(--bg-secondary)",color:"var(--nice-text, inherit)",...i},id:o,"data-testid":c,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,gap:8},children:[r.jsxs("h3",{style:{margin:0,fontSize:n?16:20,display:"flex",alignItems:"center",gap:8},children:[r.jsx(se.NtdMicrophone,{size:n?16:20})," ",h("vocalEffects.title","Vocal effects")]}),r.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[Z>0&&r.jsxs(we.NiceBadge,{variant:"primary",children:[Z," ",h("vocalEffects.active","active")]}),f?r.jsx(we.NiceButton,{variant:"danger",size:"sm",onClick:E,children:h("vocalEffects.stop","Stop")}):r.jsx(we.NiceButton,{variant:"primary",size:"sm",onClick:$,children:h("vocalEffects.start","Start mic")})]})]}),r.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[r.jsx(we.NiceToggle,{checked:x,onChange:g,label:r.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),r.jsx("div",{style:{width:100},children:r.jsx(we.NiceSlider,{value:k,onChange:b,min:0,max:200})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),r.jsx("div",{style:{width:100},children:r.jsx(we.NiceSlider,{value:S,onChange:M,min:0,max:300})}),r.jsxs("span",{style:{minWidth:36,fontSize:12},children:[S,"%"]})]}),f&&r.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,R*300)}%`,background:R>.5?"var(--nice-danger, #ef4444)":R>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),Z>0&&r.jsx(we.NiceButton,{variant:"ghost",size:"sm",onClick:U,children:h("vocalEffects.clearAll","Clear all")})]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${n?130:160}px, 1fr))`,gap:n?6:10},children:m.map(A=>r.jsxs("div",{style:{border:A.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:n?"6px 8px":"10px 12px",background:A.enabled?"var(--nice-accent-tint-10, rgba(59,130,246,0.08))":"transparent",transition:"all 0.15s ease"},children:[r.jsxs("button",{type:"button",onClick:()=>_(A.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:A.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const q=mm[A.icon]??se.NtdMusic;return r.jsx(q,{size:n?18:22})})(),r.jsx("span",{style:{fontSize:n?12:14,fontWeight:A.enabled?700:500,color:A.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:A.label})]}),A.enabled&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:q=>q.stopPropagation(),children:[r.jsx("div",{style:{flex:1},children:r.jsx(we.NiceSlider,{value:A.intensity,onChange:q=>L(A.type,q),min:0,max:100})}),r.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:A.intensity})]})]},A.type))}),r.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},Il={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},ym=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],bm=({deviceId:e,onDeviceChange:t,settings:n,onSettingsChange:a,audioInputs:s,algorithms:i=ym,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:u})=>{const{t:h}=Te(),p=u??h,f=d.useMemo(()=>({...Il,...n}),[n]),y=$=>a==null?void 0:a({...f,...$}),[m,v]=d.useState([]);d.useEffect(()=>{var _,L,U;if(s||!((_=navigator.mediaDevices)!=null&&_.enumerateDevices))return;let $=!1;const E=()=>navigator.mediaDevices.enumerateDevices().then(Z=>!$&&v(Z.filter(A=>A.kind==="audioinput"))).catch(()=>{});return E(),(U=(L=navigator.mediaDevices).addEventListener)==null||U.call(L,"devicechange",E),()=>{var Z,A;$=!0,(A=(Z=navigator.mediaDevices).removeEventListener)==null||A.call(Z,"devicechange",E)}},[s]);const x=s??m,g=d.useMemo(()=>x.map(($,E)=>({value:$.deviceId,label:$.label||`${p("audioInput.microphone","Microphone")} ${E+1}`})),[x,p]),[k,b]=d.useState(!1),[S,M]=d.useState(0),R=d.useRef(null),N=()=>{const $=R.current;$&&(cancelAnimationFrame($.raf),$.stream.getTracks().forEach(E=>E.stop()),$.ctx.close().catch(()=>{}),R.current=null),b(!1),M(0)},C=async()=>{try{const $=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),E=new AudioContext,_=E.createMediaStreamSource($),L=E.createAnalyser();L.fftSize=1024,_.connect(L);const U=new Float32Array(L.fftSize),Z=()=>{L.getFloatTimeDomainData(U);let A=0;for(let q=0;q<U.length;q++)A+=U[q]*U[q];M(Math.sqrt(A/U.length)*(f.gain||1)),R.current.raf=requestAnimationFrame(Z)};R.current={ctx:E,stream:$,raf:requestAnimationFrame(Z)},b(!0)}catch{}};d.useEffect(()=>()=>N(),[]);const w={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},O=($,E,_)=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[r.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:$}),r.jsx("div",{style:{flex:1},children:E}),r.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:_})]});return r.jsxs("div",{className:"nice-audio-input-picker",style:{display:"flex",flexDirection:"column",gap:c?8:12,border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:c?12:16,color:"var(--nice-text, inherit)"},children:[r.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[r.jsxs("div",{style:{flex:"1 1 220px",minWidth:180},children:[r.jsxs("label",{style:{...w,display:"inline-flex",alignItems:"center",gap:4},children:[r.jsx(se.NtdMicrophone,{size:13})," ",p("audioInput.device","Microphone")]}),r.jsx(we.NiceSelect,{options:g,value:e??"",onChange:$=>t==null?void 0:t(typeof $=="string"?$:$[0]),placeholder:p("audioInput.selectDevice","Select microphone"),size:"sm"})]}),r.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[r.jsx("label",{style:w,children:p("audioInput.algorithm","Pitch algorithm")}),r.jsx(we.NiceSelect,{options:i,value:f.algorithm,onChange:$=>y({algorithm:typeof $=="string"?$:$[0]}),size:"sm"})]})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[O(p("audioInput.gain","Gain"),r.jsx(we.NiceSlider,{value:Math.round(f.gain*100),onChange:$=>y({gain:$/100}),min:0,max:300}),`${Math.round(f.gain*100)}%`),O(p("audioInput.rmsThreshold","RMS gate"),r.jsx(we.NiceSlider,{value:Math.round(f.rmsThreshold*1e3),onChange:$=>y({rmsThreshold:$/1e3}),min:0,max:200}),f.rmsThreshold.toFixed(3)),O(p("audioInput.pitchThreshold","Pitch clarity"),r.jsx(we.NiceSlider,{value:Math.round(f.pitchThreshold*100),onChange:$=>y({pitchThreshold:$/100}),min:0,max:100}),f.pitchThreshold.toFixed(2)),!c&&O(p("audioInput.smoothing","Smoothing"),r.jsx(we.NiceSlider,{value:f.smoothingWindow,onChange:$=>y({smoothingWindow:$}),min:0,max:12}),`${f.smoothingWindow}`),!c&&O(p("audioInput.hysteresis","Hysteresis"),r.jsx(we.NiceSlider,{value:f.hysteresisFrames,onChange:$=>y({hysteresisFrames:$}),min:0,max:12}),`${f.hysteresisFrames}`),!c&&O(p("audioInput.offset","Latency"),r.jsx(we.NiceSlider,{value:f.offsetMs,onChange:$=>y({offsetMs:$}),min:-200,max:500}),`${f.offsetMs}ms`)]}),r.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[r.jsx(we.NiceToggle,{checked:f.useHanning,onChange:$=>y({useHanning:$}),label:p("audioInput.hanning","Hanning window")}),o&&r.jsxs(r.Fragment,{children:[r.jsx(we.NiceButton,{variant:k?"danger":"secondary",size:"sm",onClick:k?N:C,children:k?p("audioInput.stopTest","Stop test"):p("audioInput.testMic","Test mic")}),r.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--bg-tertiary)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${Math.min(100,S*300)}%`,background:S>.5?"var(--nice-danger, #ef4444)":S>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&r.jsxs(we.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[r.jsx(se.NtdSettings,{size:14})," ",p("audioInput.calibrate","Calibrate latency")]})]})]})};class Ll{constructor(t,n){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(n)}applyCC(t,n,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=n/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const u=this.audioContext.currentTime;return l.gain.setValueAtTime(0,u),l.gain.linearRampToValueAtTime(c,u+.01),l.gain.exponentialRampToValueAtTime(c*.7,u+.1),l.gain.setValueAtTime(c*.7,u+a-.05),l.gain.exponentialRampToValueAtTime(.001,u+a),o.start(u),o.stop(u+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,n,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const u=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=n;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(u,h+.01),c.gain.exponentialRampToValueAtTime(u*.7,h+.1),c.gain.setValueAtTime(u*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:n})=>{try{t.stop(),n.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ki=it.scoped("AudioPlaybackEngine");class xm{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(n))}removeMidiCCEvent(t,n){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==n))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ki.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const n=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,n.connect(a),a.connect(s),{input:n,output:s}}case"compressor":{const n=this.audioContext.createDynamicsCompressor();return n.threshold.value=t.params.threshold||-24,n.ratio.value=t.params.ratio||4,n.attack.value=t.params.attack||.003,n.release.value=t.params.release||.25,n.knee.value=t.params.knee||30,n}case"delay":{const n=this.audioContext.createDelay(5);n.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),n.connect(a),a.connect(n),n.connect(s),{input:n,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const n=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let u=0;u<a;u++)c[u]=(Math.random()*2-1)*Math.pow(1-u/a,2)}n.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),n.connect(i),{input:n,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let u=0;u<s;u++){const h=u*2/s-1;i[u]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}n.curve=i,n.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),n.connect(l),{input:n,output:l,dry:c,connect:function(u){l.connect(u),c.connect(u)}}}default:return null}}catch(n){return ki.error("Failed to create effect node:",t.type,n),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,n){const a=this.clips.get(t);a&&(Object.assign(a,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new Ll(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const a=this.midiTracks.get(t);a&&(a.volume=n);const s=this.synths.get(t);s&&s.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const a=n.startTime+n.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const n=this.isPlaying;n&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),n&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const p=this.createEffectNode(h);if(p)if("input"in p&&"output"in p){const f=p;o.connect(f.input),o=f.output,"dry"in p&&s.connect(f.dry)}else o.connect(p),o=p}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),u=this.audioContext.currentTime+(l-this.currentTime);u>=this.audioContext.currentTime&&(a.start(u,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const n=this.scheduledSources.get(t);if(n){try{n.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const n=this.synths.get(t.layerId);if(n&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&n.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,u=l.time,h=i.value,p=l.value,f=i.handleType||"linear",y=Math.max(2,Math.ceil((u-c)*20));for(let m=0;m<=y;++m){const v=m/y;let x=h;if(f==="linear")x=h+(p-h)*v;else if(f==="step")x=v<1?h:p;else if(f==="exp"){const S=Math.max(h/127,.001),M=Math.max(p/127,.001);x=S*Math.pow(M/S,v)*127}const g=c+(u-c)*v,k=this.audioContext.currentTime+(g-this.currentTime);k>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,x,k)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const n=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+n,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,n,a){this.loopRegion={start:t,end:n,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const vm=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Br(e={}){const{channelFilter:t,sysex:n=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=d.useState(null),[c,u]=d.useState(!1),[h,p]=d.useState([]),f=d.useRef(null),y=d.useCallback((m,v)=>{const x=m.data??new Uint8Array(0),g=x[0]??0,k=x[1]??0,b=x[2]??0,S=m.timeStamp,M=g&240,R=g&15,N=v.id,C=v.name??"MIDI Input",w=t===void 0||t===R;if((M===144||M===128)&&w){const O=M===144&&b>0;return{type:O?"noteon":"noteoff",note:k,velocity:O?b:0,channel:R,ts:S,deviceId:N,deviceName:C}}return M===176&&w?{type:"cc",controller:k,value:b,channel:R,ts:S,deviceId:N,deviceName:C}:M===208&&w?{type:"aftertouch",pressure:k,channel:R,ts:S,deviceId:N,deviceName:C}:M===224&&w?{type:"pitchbend",value:(k|b<<7)-8192,channel:R,ts:S,deviceId:N,deviceName:C}:M===192&&w?{type:"program",program:k,channel:R,ts:S,deviceId:N,deviceName:C}:{type:"unknown",status:g,data1:k,data2:b,channel:R,ts:S,deviceId:N,deviceName:C}},[t]);return d.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let m=!1;return navigator.requestMIDIAccess({sysex:n}).then(v=>{if(m)return;f.current=v,u(!0);const x=()=>{const g=Array.from(v.inputs.values()),k=s?g.filter(b=>(b.name||"").toUpperCase().includes(s.toUpperCase())):g;p(k),i==null||i(k),g.forEach(b=>b.onmidimessage=null),k.forEach(b=>{b.onmidimessage=S=>a==null?void 0:a(y(S,b))})};x(),v.onstatechange=()=>x()}),()=>{m=!0;const v=f.current;v&&(v.inputs.forEach(x=>x.onmidimessage=null),v.onstatechange=null)}},[s,a,i,y,n]),{supported:o,granted:c,inputs:h}}const ls="nice2dev.midiLearn";function Sm(){try{const e=localStorage.getItem(ls);return e?JSON.parse(e):{}}catch{return{}}}function wi(e){const t={};for(const n of e)t[n.id]={id:n.id,type:n.type,number:n.number,channel:n.channel,min:n.min,max:n.max};localStorage.setItem(ls,JSON.stringify(t))}function km(e){const{parameters:t,onParameterChange:n}=e,[a,s]=d.useState(()=>{const b=Sm();return t.map(S=>{const M=b[S.id];return{id:S.id,paramName:S.name,type:(M==null?void 0:M.type)??"cc",number:M==null?void 0:M.number,channel:M==null?void 0:M.channel,min:(M==null?void 0:M.min)??S.min??0,max:(M==null?void 0:M.max)??S.max??127,value:0}})}),[i,o]=d.useState({learning:!1,targetId:null}),[l,c]=d.useState(null),u=d.useRef(a);u.current=a;const h=d.useRef(n);h.current=n;const p=d.useRef(i);p.current=i;const f=d.useCallback(b=>{var M;c(b);const S=p.current;if(S.learning&&S.targetId){if(!u.current.find(C=>C.id===S.targetId))return;let N={};switch(b.type){case"cc":N={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":N={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":N={type:"pitchbend",channel:b.channel};break;case"aftertouch":N={type:"aftertouch",channel:b.channel};break;default:return}s(C=>{const w=C.map(O=>O.id===S.targetId?{...O,...N}:O);return wi(w),w}),o({learning:!1,targetId:null});return}for(const R of u.current){if(R.number===void 0&&R.type!=="pitchbend"&&R.type!=="aftertouch"||R.channel!==void 0&&b.channel!==R.channel)continue;let N=null,C=127;if(R.type==="cc"&&b.type==="cc"&&b.controller===R.number?N=b.value:R.type==="note"&&b.type==="noteon"&&b.note===R.number?N=b.velocity:R.type==="pitchbend"&&b.type==="pitchbend"?(N=b.value+8192,C=16383):R.type==="aftertouch"&&b.type==="aftertouch"&&(N=b.pressure),N!==null){const w=N/C,O=R.min+w*(R.max-R.min);s($=>$.map(E=>E.id===R.id?{...E,value:w}:E)),(M=h.current)==null||M.call(h,R.id,O,w)}}},[]),{supported:y,granted:m}=Br({onEvent:f}),v=d.useCallback(b=>{o({learning:!0,targetId:b})},[]),x=d.useCallback(()=>{o({learning:!1,targetId:null})},[]),g=d.useCallback(b=>{s(S=>{const M=S.map(R=>R.id===b?{...R,type:"cc",number:void 0,channel:void 0}:R);return wi(M),M})},[]),k=d.useCallback(()=>{s(b=>{const S=b.map(M=>({...M,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(ls),S})},[]);return{bindings:a,startLearn:v,cancelLearn:x,removeBinding:g,clearAll:k,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const wm={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function jm(e={}){const{lowerZone:t=wm,onNoteExpression:n,onNoteOn:a,onNoteOff:s}=e,[i,o]=d.useState([]),l=d.useRef(new Map),c=d.useRef(n);c.current=n;const u=d.useRef(a);u.current=a;const h=d.useRef(s);h.current=s;const p=d.useRef(new Set(t.memberChannels));d.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const f=d.useCallback(v=>{var g,k,b,S,M;if(!p.current.has(v.channel??-1))return;const x=`${v.channel}`;switch(v.type){case"noteon":{const R={note:v.note,channel:v.channel,velocity:v.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:v.ts};l.current.set(x,R),o(Array.from(l.current.values())),(g=u.current)==null||g.call(u,R);break}case"noteoff":{l.current.delete(x),o(Array.from(l.current.values())),(k=h.current)==null||k.call(h,v.channel,v.note);break}case"pitchbend":{const R=l.current.get(x);R&&(R.pitchBend=v.value,R.lastUpdate=v.ts,(b=c.current)==null||b.call(c,R),o(Array.from(l.current.values())));break}case"aftertouch":{const R=l.current.get(x);R&&(R.pressure=v.pressure,R.lastUpdate=v.ts,(S=c.current)==null||S.call(c,R),o(Array.from(l.current.values())));break}case"cc":{if(v.controller===74){const R=l.current.get(x);R&&(R.slide=v.value,R.lastUpdate=v.ts,(M=c.current)==null||M.call(c,R),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Br({onEvent:f,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const Cm={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function Mm(e={},t=Cm){const[n,a]=d.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=d.useState([]),o=d.useRef({mode:"idle"}),l=d.useCallback(y=>{a(m=>{const v={...m,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(v)),v})},[]),c=d.useCallback(y=>{var x,g,k,b,S,M,R,N,C;const m=y.deviceName||"MIDI";i(w=>w.includes(m)?w:[...w,m]);const v=o.current;if(v.mode!=="idle"){if(v.mode==="knob"&&y.type==="cc"){const w=v.index;l({knobs:n.knobs.map(O=>O.index===w?{...O,cc:y.controller}:O)}),o.current={mode:"idle"};return}if(v.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),o.current={mode:"idle"};return}if(v.mode==="pad"&&y.type==="noteon"){const w=n.pads.slice();w[v.padIdx]={...w[v.padIdx],note:y.note},l({pads:w}),o.current={mode:"idle"};return}if(v.mode==="transport"&&y.type==="cc"){const w={...n.transport};w[v.action]=y.controller,l({transport:w}),o.current={mode:"idle"};return}}switch(y.type){case"noteon":{n.pads.findIndex(O=>O.note===y.note)>=0?(x=e.onPad)==null||x.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m}):(g=e.onKey)==null||g.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m});break}case"cc":{if(n.fader&&y.controller===n.fader.cc){(k=e.onFader)==null||k.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:m});break}const w=n.knobs.find($=>$.cc===y.controller);if(w){(b=e.onKnob)==null||b.call(e,{index:w.index,cc:y.controller,value:y.value,ts:y.ts,device:m});break}const O=Object.keys(n.transport).find($=>n.transport[$]===y.controller);if(O){(S=e.onTransport)==null||S.call(e,{action:O,value:y.value,ts:y.ts,device:m});break}(M=e.onUnknown)==null||M.call(e,y);break}case"pitchbend":(R=e.onPitchBend)==null||R.call(e,{value:y.value,ts:y.ts,device:m});break;case"aftertouch":(N=e.onAftertouch)==null||N.call(e,{pressure:y.pressure,ts:y.ts,device:m});break;default:(C=e.onUnknown)==null||C.call(e,y)}},[l,e,n]),{supported:u,granted:h,inputs:p}=Br({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(m=>m.name||"MIDI"))}),f=d.useMemo(()=>({knob:y=>o.current={mode:"knob",index:y},fader:()=>o.current={mode:"fader"},pad:y=>o.current={mode:"pad",padIdx:y},transport:y=>o.current={mode:"transport",action:y},cancel:()=>o.current={mode:"idle"},state:()=>o.current}),[]);return{supported:u,granted:h,inputs:p,layout:n,setLayout:l,learn:f,inputsInfo:s}}const va={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},Rm=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Sa={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},Qt=36,wn=38,Rt=42,Jt=51,Nm=49,ka={basic:[{step:0,pitch:Qt,vel:110},{step:0,pitch:Rt,vel:80},{step:2,pitch:Rt,vel:70},{step:4,pitch:wn,vel:100},{step:4,pitch:Rt,vel:80},{step:6,pitch:Rt,vel:70},{step:8,pitch:Qt,vel:100},{step:10,pitch:Rt,vel:70},{step:12,pitch:wn,vel:100},{step:12,pitch:Rt,vel:80},{step:14,pitch:Rt,vel:70}],rock:[{step:0,pitch:Qt,vel:120},{step:0,pitch:Nm,vel:90},{step:4,pitch:wn,vel:110},{step:4,pitch:Rt,vel:80},{step:8,pitch:Qt,vel:110},{step:8,pitch:Rt,vel:80},{step:10,pitch:Qt,vel:90},{step:12,pitch:wn,vel:110},{step:12,pitch:Rt,vel:80}],swing:[{step:0,pitch:Jt,vel:90},{step:3,pitch:Jt,vel:70},{step:4,pitch:Jt,vel:80},{step:8,pitch:Jt,vel:90},{step:11,pitch:Jt,vel:70},{step:12,pitch:Jt,vel:80},{step:4,pitch:Qt,vel:80},{step:12,pitch:wn,vel:70}]},Dl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function Tm(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}let _l=1;const ir=()=>_l++,Fl=e=>60/e,$m=e=>Fl(e)/4;function ta(e,t,n,a){const s=t.length,i=Math.floor(n/s),o=(n%s+s)%s;return e+t[o]+(a+i)*12}function zl(e=Dl){_l=1;const t=e.seed>0?Tm(e.seed):Math.random,n=va[e.scale]??va.pentatonic,a=Sa[e.progression]??Sa.pop,s=ka[e.drumPattern]??ka.basic,i=Fl(e.tempo),o=$m(e.tempo),l=Math.max(1,e.bars),c=16,u=[],h=[],p=[],f=[];let y=0;for(let m=0;m<l;m++){const v=m*4*i,x=m%a.length,g=a[x];for(const b of g)p.push({id:ir(),pitch:ta(e.root,n,b,e.octave-1),start:v,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const k=g[0];for(let b=0;b<4;b++){const S=b===2?k+(t()>.5?2:0):k;h.push({id:ir(),pitch:ta(e.root,n,S,e.octave-2),start:v+b*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const S=v+b*o,M=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(n.length+3,y+M));const R=1+Math.floor(t()*3);u.push({id:ir(),pitch:ta(e.root,n,y,e.octave),start:S,duration:R*o*.95,velocity:85+Math.floor(t()*30)})}for(const b of s)f.push({id:ir(),pitch:b.pitch,start:v+b.step*o,duration:o*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:u,bass:h,chords:p,drums:f,config:e}}const Pm=Object.keys(va),Am=Object.keys(Sa),Em=Object.keys(ka),Im=zl;function He(e,t,n){return{cc:e,paramId:n,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Un(e,t,n){return{cc:e,paramId:n,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function en(e,t,n){return{cc:e,paramId:n,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Ol={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[He(21,1,"mixer.volume"),He(22,2,"mixer.pan"),He(23,3,"fx.reverb"),He(24,4,"fx.delay"),He(25,5,"fx.chorus"),He(26,6,"fx.filter"),He(27,7,"fx.drive"),He(28,8,"fx.eq"),Un(7,"Master Fader","mixer.master"),en(115,"Play","transport.play"),en(114,"Stop","transport.stop"),en(117,"Record","transport.record"),en(112,"Rewind","transport.rewind"),en(113,"Forward","transport.forward"),en(116,"Loop","transport.loop")]},Bl={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[He(1,1,"mixer.volume"),He(2,2,"mixer.pan"),He(3,3,"fx.reverb"),He(4,4,"fx.delay"),He(5,5,"fx.chorus"),He(6,6,"fx.filter"),He(7,7,"fx.drive"),He(8,8,"fx.eq")]},Gl={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[He(7,1,"mixer.volume"),He(74,2,"mixer.pan"),He(71,3,"fx.reverb"),He(76,4,"fx.delay"),He(77,5,"fx.chorus"),He(93,6,"fx.filter"),He(73,7,"fx.drive"),He(75,8,"fx.eq"),Un(1,"Mod Wheel","mixer.master")]},Wl={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>He(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Un(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},cs={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[He(1,1,"mixer.modWheel"),Un(7,"Volume","mixer.volume"),He(10,2,"mixer.pan"),Un(11,"Expression","mixer.expression")]},Ul=[Ol,Bl,Gl,Wl,cs];class Lm{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??cs,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const n=t.toUpperCase(),a=Ul.find(s=>s.deviceMatch&&n.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,n){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-n:n)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:n,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,n,a,s="knob"){const i={cc:t,paramId:n,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(n=>n.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(n=>({...n}))},this.rebuildMap()}static createCustomProfile(t,n){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:n.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function ql(e){return{past:[],present:e,future:[]}}function Vl(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Hl(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Kl(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function Yl(e){return e.past.length>0}function Zl(e){return e.future.length>0}function wa(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function Xl(e,t,n){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=n-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function Ql(e,t){const n=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?n.push({...s}):a.push(s);return{remaining:a,cut:n}}function Jl(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Dm(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function ec(e,t,n,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:a};return[...e,s]}function tc(e,t=3){if(e.length<=2)return e;const n=[...e].sort((s,i)=>s.time-i.time),a=[n[0]];for(let s=1;s<n.length-1;s++)s%t===0&&a.push(n[s]);return a.push(n[n.length-1]),a}function nc(e){return JSON.stringify(e,null,2)}function rc(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&"cc"in n&&"value"in n&&"time"in n):[]}catch{return[]}}function yt(e,t){var n;return((n=e.find(a=>a.layerId===t))==null?void 0:n.events)??[]}function Nt(e,t,n){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:n}:s):[...e,{layerId:t,events:n}]}function _m(e,t){switch(t.type){case"UNDO":return Hl(e);case"REDO":return Kl(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const a=[...yt(n,t.layerId),t.event];n=Nt(n,t.layerId,a);break}case"UPDATE_EVENT":{const a=yt(n,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);n=Nt(n,t.layerId,a);break}case"REMOVE_EVENT":{const a=yt(n,t.layerId).filter(s=>s.id!==t.id);n=Nt(n,t.layerId,a);break}case"SET_EVENTS":n=Nt(n,t.layerId,t.events);break;case"PASTE":{const a=yt(n,t.layerId),s=Xl(a,t.clipboard,t.targetTime);n=Nt(n,t.layerId,s);break}case"CUT":{const a=yt(n,t.layerId),{remaining:s}=Ql(a,t.range);n=Nt(n,t.layerId,s);break}case"DELETE_RANGE":{const a=yt(n,t.layerId),s=Jl(a,t.range);n=Nt(n,t.layerId,s);break}case"RECORD":{const a=yt(n,t.layerId),s=ec(a,t.cc,t.value,t.time);n=Nt(n,t.layerId,s);break}case"THIN":{const a=yt(n,t.layerId),s=tc(a,t.keepEveryN);n=Nt(n,t.layerId,s);break}case"IMPORT":{const a=rc(t.json);a.length>0&&(n=Nt(n,t.layerId,a));break}}return Vl(e,n)}}}function Fm(e=[]){const[t,n]=d.useReducer(_m,ql(e)),a=d.useRef([]),s=d.useCallback(b=>yt(t.present,b),[t.present]),i=d.useCallback((b,S)=>n({type:"ADD_EVENT",layerId:b,event:S}),[]),o=d.useCallback((b,S,M,R,N)=>n({type:"UPDATE_EVENT",layerId:b,id:S,value:M,time:R,handleType:N}),[]),l=d.useCallback((b,S)=>n({type:"REMOVE_EVENT",layerId:b,id:S}),[]),c=d.useCallback((b,S)=>n({type:"SET_EVENTS",layerId:b,events:S}),[]),u=d.useCallback(()=>n({type:"UNDO"}),[]),h=d.useCallback(()=>n({type:"REDO"}),[]),p=d.useCallback((b,S)=>{a.current=wa(yt(t.present,b),S)},[t.present]),f=d.useCallback((b,S)=>{a.current=wa(yt(t.present,b),S),n({type:"CUT",layerId:b,range:S})},[t.present]),y=d.useCallback((b,S)=>{a.current.length>0&&n({type:"PASTE",layerId:b,clipboard:a.current,targetTime:S})},[]),m=d.useCallback((b,S)=>n({type:"DELETE_RANGE",layerId:b,range:S}),[]),v=d.useCallback((b,S,M,R)=>n({type:"RECORD",layerId:b,cc:S,value:M,time:R}),[]),x=d.useCallback((b,S)=>n({type:"THIN",layerId:b,keepEveryN:S}),[]),g=d.useCallback(b=>nc(yt(t.present,b)),[t.present]),k=d.useCallback((b,S)=>n({type:"IMPORT",layerId:b,json:S}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:u,redo:h,canUndo:Yl(t),canRedo:Zl(t),copy:p,cut:f,paste:y,clipboard:a.current,deleteRange:m,record:v,thin:x,exportLane:g,importLane:k}}function ds(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Ht(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>ds()),bpm:n,swing:0,rootNote:60}}function ac(e,t){const n=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:n}}function sc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function ic(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,n))}:s);return{...e,steps:a}}function oc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function lc(e,t,n){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,n))}:s);return{...e,steps:a}}function cc(e,t){const n=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:n}}function dc(e,t){const n=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function uc(e){return{...e,steps:[...e.steps].reverse()}}function hc(e,t){const n=e.steps.length,a=(t%n+n)%n,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function pc(e,t=60,n=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(n-t+1))}:s);return{...e,steps:a}}function fc(e){return{...e,steps:e.steps.map(()=>ds(e.rootNote))}}function us(e,t=4){return 60/e/t}function mc(e,t,n=0,a=4){const s=us(t,a),i=e*s;return e%2===1&&n>0?i+s*n*.5:i}function gc(e){return e.active&&Math.random()<e.probability}function zm(){const e=Ht("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function Om(){const e=Ht("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function Bm(){const e=Ht("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function Gm(e=60){const t=Ht("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function Wm(e=36){const t=Ht("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function Um(e){return JSON.stringify(e,null,2)}function qm(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Vm(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:a}=e,[s,i]=d.useState(()=>a??Ht()),[o,l]=d.useState(-1),[c,u]=d.useState(!1),[h,p]=d.useState([]),f=d.useRef(s);f.current=s;const y=d.useRef(h);y.current=h;const m=d.useRef(c);m.current=c;const v=d.useRef(t);v.current=t;const x=d.useRef(n);x.current=n;const g=d.useRef(null),k=d.useRef(0),b=d.useRef(0),S=d.useCallback(()=>{var Y,X;if(!m.current)return;const I=f.current,P=k.current%I.length,T=I.steps[P];if(gc(T)){const ie=mc(k.current,I.bpm,I.swing);(Y=v.current)==null||Y.call(v,T,P,ie)}const z=(Date.now()-b.current)/1e3;for(let ie=0;ie<y.current.length;ie++){const le=y.current[ie];if(le.enabled&&le.targetCC!==void 0){const te=Aa(le,z,I.bpm);(X=x.current)==null||X.call(x,ie,le.targetCC,te)}}l(P),k.current++;const B=us(I.bpm)*1e3,G=P%2===0?0:B*I.swing*.5;g.current=setTimeout(S,B+G)},[]),M=d.useCallback(()=>{m.current||(k.current=0,b.current=Date.now(),u(!0),m.current=!0,S())},[S]),R=d.useCallback(()=>{u(!1),m.current=!1,l(-1),g.current&&(clearTimeout(g.current),g.current=null)},[]),N=d.useCallback(()=>{m.current?R():M()},[M,R]);d.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const C=d.useCallback(I=>i(P=>ac(P,I)),[]),w=d.useCallback((I,P)=>i(T=>sc(T,I,P)),[]),O=d.useCallback((I,P)=>i(T=>ic(T,I,P)),[]),$=d.useCallback((I,P)=>i(T=>oc(T,I,P)),[]),E=d.useCallback((I,P)=>i(T=>lc(T,I,P)),[]),_=d.useCallback(I=>i(P=>cc(P,I)),[]),L=d.useCallback(I=>i(P=>dc(P,I)),[]),U=d.useCallback(()=>i(I=>uc(I)),[]),Z=d.useCallback(I=>i(P=>hc(P,I)),[]),A=d.useCallback((I,P)=>i(T=>pc(T,I,P)),[]),q=d.useCallback(()=>i(I=>fc(I)),[]),H=d.useCallback(I=>i(P=>({...P,bpm:Math.max(20,Math.min(300,I))})),[]),re=d.useCallback(I=>i(P=>({...P,swing:Math.max(0,Math.min(1,I))})),[]),D=d.useCallback(I=>{i(P=>{if(P.length===I)return P;const T=Array.from({length:I},(z,B)=>B<P.steps.length?P.steps[B]:{active:!1,note:P.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...P,length:I,steps:T}})},[]),W=d.useCallback(I=>{p(P=>[...P,I??Er()])},[]),j=d.useCallback(I=>{p(P=>P.filter((T,z)=>z!==I))},[]),F=d.useCallback((I,P)=>{p(T=>T.map((z,B)=>B===I?{...z,...P}:z))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:M,stop:R,togglePlayback:N,toggle:C,setNote:w,setVelocity:O,setGate:$,setProbability:E,toggleSlide:_,transpose:L,reverse:U,shift:Z,randomizeVel:A,clear:q,setPattern:i,setBpm:H,setSwing:re,setLength:D,addLFO:W,removeLFO:j,updateLFO:F}}function hs(e){const t=d.useRef(null),n=d.useRef(new Map),a=d.useRef(1),s=d.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,u=n.current.get(c);u&&(n.current.delete(c),u.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,u]of n.current)u.reject(new Error(`Worker error: ${l.message}`));n.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return d.useEffect(()=>{const o=n.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),d.useCallback((o,l)=>{const c=a.current++,u=s();return new Promise((h,p)=>{n.current.set(c,{resolve:h,reject:p}),u.postMessage({...o,id:c},l??[])})},[s])}function Hm(){const e=hs(d.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s=.01)=>(await e({buffer:n,sampleRate:a,rmsThreshold:s})).hz,[e])}function Km(){const e=hs(d.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return d.useCallback(async(n,a,s)=>(await e({notes:n,points:a,params:s})).result,[e])}const Ym={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function yc(){return`
70
+ Tame Impala - Let It Happen`,rows:10,style:{width:"100%",padding:12,borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)",fontFamily:"monospace",fontSize:13,resize:"vertical"}}),n.jsx("button",{style:{...Ln,opacity:ee.trim().length===0?.5:1},disabled:ee.trim().length===0,onClick:()=>G(ee),type:"button",children:d("importWizard.parseTracks","Parse Tracks")})]}),(p!==99||S.length>0)&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsxs("p",{style:{margin:0,fontWeight:600},children:[v==null?void 0:v.name," — ",k.size,"/",S.length," ",d("importWizard.selected","selected")]}),n.jsx("button",{style:sr,onClick:$,type:"button",children:k.size===S.length?d("importWizard.deselectAll","Deselect All"):d("importWizard.selectAll","Select All")})]}),N?n.jsx("div",{style:{textAlign:"center",padding:32,color:"var(--nice-text-dim, #64748b)"},children:d("importWizard.loadingTracks","Loading tracks…")}):n.jsx("div",{style:{maxHeight:320,overflowY:"auto"},children:n.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[n.jsx("thead",{children:n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",textAlign:"left"},children:[n.jsx("th",{style:{padding:"4px 8px",width:32}}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.title","Title")}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.artist","Artist")}),n.jsx("th",{style:{padding:"4px 8px"},children:d("importWizard.album","Album")}),n.jsx("th",{style:{padding:"4px 8px",textAlign:"right"},children:d("importWizard.duration","Duration")})]})}),n.jsx("tbody",{children:S.map(Z=>{const Y=k.has(Z.externalId);return n.jsxs("tr",{style:{borderBottom:"1px solid var(--nice-border, #e2e8f0)",opacity:Y?1:.5,cursor:"pointer"},onClick:()=>U(Z.externalId),children:[n.jsx("td",{style:{padding:"6px 8px"},children:n.jsx("input",{type:"checkbox",checked:Y,readOnly:!0})}),n.jsx("td",{style:{padding:"6px 8px",fontWeight:500},children:Z.title}),n.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:Z.artist}),n.jsx("td",{style:{padding:"6px 8px",color:"var(--nice-text-dim, #64748b)"},children:Z.album??"—"}),n.jsx("td",{style:{padding:"6px 8px",textAlign:"right",color:"var(--nice-text-dim, #64748b)"},children:Rf(Z.duration)})]},Z.externalId)})})]})}),n.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:n.jsxs("button",{style:{...Ln,opacity:k.size===0?.5:1},disabled:k.size===0,onClick:()=>f("options"),type:"button",children:[d("importWizard.next","Next")," ",n.jsx(W.NtdArrowRight,{size:12})]})})]})]}),X=()=>n.jsxs("div",{style:{display:"grid",gap:16},children:[n.jsx("p",{style:{margin:0,fontWeight:600},children:d("importWizard.importOptions","Import options")}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:E.mergeTags,onChange:Z=>V(Y=>({...Y,mergeTags:Z.target.checked}))}),d("importWizard.mergeTags","Merge tags from source playlist")]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:E.mergeFolders,onChange:Z=>V(Y=>({...Y,mergeFolders:Z.target.checked}))}),d("importWizard.mergeFolders","Merge into existing folder structure")]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[n.jsx("input",{type:"checkbox",checked:E.overwriteExisting,onChange:Z=>V(Y=>({...Y,overwriteExisting:Z.target.checked}))}),d("importWizard.overwrite","Overwrite existing tracks (match by ISRC)")]}),l&&l.length>0&&n.jsxs("div",{style:{display:"grid",gap:4},children:[n.jsx("label",{style:{fontSize:13,fontWeight:500},children:d("importWizard.targetFolder","Target folder")}),n.jsxs("select",{style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #e2e8f0)"},value:E.targetFolderId??"",onChange:Z=>V(Y=>({...Y,targetFolderId:Z.target.value||void 0})),children:[n.jsx("option",{value:"",children:d("importWizard.root","— Root —")}),l.map(Z=>n.jsx("option",{value:Z.id,children:Z.name},Z.id))]})]}),n.jsx("div",{style:{marginTop:8,padding:12,borderRadius:8,background:"var(--nice-info-bg, #eff6ff)",fontSize:13},children:d("importWizard.summary",`Ready to import ${k.size} tracks from "${(v==null?void 0:v.name)??""}"`)}),n.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[n.jsxs("button",{style:sr,onClick:D,type:"button",children:[n.jsx(W.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),n.jsx("button",{style:Ln,onClick:P,type:"button",children:d("importWizard.startImport","Start Import")})]})]}),oe=()=>{const Z=w?Math.round(w.imported/w.total*100):0;return n.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[n.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.importing","Importing…")}),n.jsx("div",{style:{height:8,borderRadius:4,background:"var(--nice-border, #e2e8f0)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Z}%`,background:"var(--nice-color-accent, #6366f1)",borderRadius:4,transition:"width 0.3s"}})}),w&&n.jsxs("div",{style:{fontSize:13,color:"var(--nice-text-dim, #64748b)"},children:[w.imported," / ",w.total," ",d("importWizard.tracks","tracks"),w.currentTrack&&n.jsxs("div",{style:{marginTop:4},children:[n.jsx(W.NtdMusic,{size:12})," ",w.currentTrack]})]})]})},le=()=>n.jsxs("div",{style:{display:"grid",gap:16,textAlign:"center",padding:24},children:[n.jsx("span",{style:{display:"inline-flex",justifyContent:"center"},"aria-hidden":"true",children:n.jsx(W.NtdCheck,{size:48})}),n.jsx("p",{style:{margin:0,fontWeight:600,fontSize:18},children:d("importWizard.complete","Import Complete")}),I&&n.jsxs("div",{style:{display:"grid",gap:4,fontSize:14},children:[n.jsxs("div",{children:[n.jsx("strong",{children:I.imported})," ",d("importWizard.imported","imported")]}),I.skipped>0&&n.jsxs("div",{style:{color:"var(--nice-color-warning, #f59e0b)"},children:[I.skipped," ",d("importWizard.skipped","skipped (duplicates)")]}),I.failed>0&&n.jsxs("div",{style:{color:"var(--nice-color-error, #ef4444)"},children:[I.failed," ",d("importWizard.failed","failed")]}),I.failedTracks.length>0&&n.jsxs("details",{style:{textAlign:"left",marginTop:8,fontSize:12,color:"var(--nice-text-dim, #64748b)"},children:[n.jsx("summary",{style:{cursor:"pointer"},children:d("importWizard.showFailed","Show failed tracks")}),n.jsx("ul",{style:{marginTop:4,paddingLeft:20},children:I.failedTracks.map((Z,Y)=>n.jsx("li",{children:Z},Y))})]})]}),n.jsx("button",{style:Ln,onClick:o,type:"button",children:d("importWizard.close","Done")})]}),ne={connect:d("importWizard.stepConnect","Connect"),browse:d("importWizard.stepBrowse","Browse"),tracks:d("importWizard.stepTracks","Select Tracks"),options:d("importWizard.stepOptions","Options"),importing:d("importWizard.stepImporting","Importing"),done:d("importWizard.stepDone","Done")};return n.jsxs("div",{style:wf,children:[C(),n.jsxs("div",{style:Cf,children:[n.jsxs("h2",{style:{margin:0,fontSize:18},children:[d("importWizard.title","Import Playlist")," — ",ne[h]]}),F&&n.jsxs("button",{style:sr,onClick:D,type:"button",children:[n.jsx(W.NtdArrowLeft,{size:12})," ",d("importWizard.back","Back")]}),h==="connect"&&n.jsx("button",{style:sr,onClick:o,type:"button","aria-label":d("importWizard.close","Close"),title:d("importWizard.close","Close"),children:n.jsx(W.NtdClose,{size:14})})]}),T&&n.jsx("div",{style:{padding:12,borderRadius:8,background:"var(--nice-error-bg, #fef2f2)",color:"var(--nice-color-error, #ef4444)",fontSize:13},children:T}),h==="connect"&&L(),h==="browse"&&B(),h==="tracks"&&H(),h==="options"&&X(),h==="importing"&&oe(),h==="done"&&le()]})},Nf=[{id:"concert-harp",name:"Concert Harp",description:"Warm concert harp",icon:"music",dir:"concert-harp",attribution:"ConcertHarp SoundFont — source: musical-artifacts.com/artifacts/375"},{id:"celtic-harp",name:"Celtic Harp",description:"Bright celtic harp",icon:"leaf",dir:"celtic-harp"},{id:"triangle",name:"Triangle",description:"Metallic percussion triangle",icon:"triangle",dir:"triangle",attribution:"Triangle SoundFont — source: polyphone.io/en/soundfonts/unpitched-percussion/298-triangle"},{id:"synth",name:"Celesta",description:"Synthesized celesta / music-box",icon:"sparkle",dir:"synth"},{id:"none",name:"Silent",description:"No sound on click",icon:"volumeMute",dir:null}],Tf="concert-harp",cs=Object.fromEntries(Nf.map(e=>[e.id,e])),$f="nice2dev-note-sound-set";function Ml(){try{const e=localStorage.getItem($f);if(e&&cs[e])return e}catch{}return Tf}const Ir=["quarter","eighth","sixteenth","beamed"];function Rl(e,t,r){const a=r*.2,s=r*.15,i=Math.max(1,r*.07),o=r*.72,l=r*.34,c=new Path2D,d=h=>{c.moveTo(h+a,l),c.ellipse(h,l,a,s,-.4,0,Math.PI*2),c.rect(h+a-i,l-o,i,o)};if(t==="beamed"){const h=-r*.24,f=r*.24;d(h),d(f),c.rect(h+a-i,l-o,f-h+i,r*.12)}else{const h=-a*.5;d(h);const f=t==="eighth"?1:t==="sixteenth"?2:0,p=h+a;for(let y=0;y<f;y++){const m=l-o+y*r*.2;c.moveTo(p,m),c.quadraticCurveTo(p+r*.32,m+r*.14,p+r*.18,m+r*.42),c.quadraticCurveTo(p+r*.2,m+r*.22,p,m+r*.14),c.closePath()}}e.stroke(c),e.fill(c)}function di(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function Nl(e){if(!e)return null;const t=document.createElement("canvas").getContext("2d");if(!t)return null;t.fillStyle=e;const r=t.fillStyle;if(r.startsWith("#")){const s=parseInt(r.slice(1),16);return{r:s>>16&255,g:s>>8&255,b:s&255}}const a=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return a?{r:+a[1],g:+a[2],b:+a[3]}:null}function na(e,t){const r=Nl(e);return r?`rgba(${r.r},${r.g},${r.b},${t})`:`rgba(255,255,255,${t})`}function Pf(e){const t=Nl(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Tl(){const e=di("--text-primary")||"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",t=di("--nav-active")||"goldenrod",r=document.documentElement.getAttribute("data-theme")==="dark",s=Pf(e)<.45;return{base:na(e,.92),staffLine:na(e,.22),outline:s?"var(--nice-overlay-light-75, rgba(255, 255, 255, 0.75))":"var(--nice-overlay-55, rgba(0, 0, 0, 0.55))",accents:[na(t,.95)],isDark:r,notesDark:s}}const Gr=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),$l=46,Ct=5,mr=4,Af=($l-(Ct-1)*mr)/2,Ef=6,If=18,Lf=110,Df=50,Wr=Gr?Df:Lf,zf=Gr?4:2,_f=Gr?2:4,ui=Gr?1:0,Ff=180,hi=2.8,pi=40,Of=14,fi=1.2,Bf=16,ra=[64,67,71,74,77],sn=64,Dn=77;function Gf(e){const t=Math.max(0,Math.min(Ct-1,e)),r=Math.floor(t),a=Math.min(r+1,Ct-1),s=t-r;return Math.round(ra[r]+(ra[a]-ra[r])*s)}function Wf(e){return(Math.max(sn-1*(Dn-sn)/(Ct-1),Math.min(Dn+1*(Dn-sn)/(Ct-1),e))-sn)/(Dn-sn)*(Ct-1)}const mi=2.5,gi=.72,Uf=.55,zn=new Map;let gr=null;async function qf(e){const t=e??Ml(),r=cs[t];if(!r||!r.dir){zn.clear(),gr=t;return}if(gr===t&&zn.size>0)return;zn.clear(),gr=t;const a=yn(),s=[];for(let i=sn;i<=Dn;i++)s.push(fetch(`/assets/soundfonts/notes/${r.dir}/note-${i}.mp3`).then(o=>o.arrayBuffer()).then(o=>a.decodeAudioData(o)).then(o=>{zn.set(i,o)}).catch(()=>{}));await Promise.all(s)}function yi(e){const t=zn.get(e);if(!t)return;const r=yn(),a=r.createBufferSource();a.buffer=t;const s=r.createGain();s.gain.value=.7,a.connect(s).connect(r.destination),a.start()}function Vf(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Hf(e){const t=Vf(42),r=[];for(let a=0;a<e;a++){const i=t()<.15?0:-1;r.push({x:t(),lineIdx:t()*(Ct+1)-.5,shape:Ir[Math.floor(t()*Ir.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:i})}return r.sort((a,s)=>a.x-s.x),r}const ht=Hf(Wr),Cn=new Float32Array(Wr),ir=new Float32Array(Wr),_n=new Float32Array(Wr);let xa=!1;const Kf=(Ct-1)/2;function Yf(){if(!xa){xa=!0;for(let e=0;e<ht.length;e++)_n[e]=ht[e].lineIdx}}let Sa=[],bi="";function Xf(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function Zf(e){const t=Xf(e);t===bi&&Sa.length===ht.length||(bi=t,Sa=ht.map(r=>{const a=Math.ceil(r.size*1.6),s=a*2,i=document.createElement("canvas");i.width=s,i.height=s;const o=i.getContext("2d");return o.translate(a,a),o.rotate(r.rot*Math.PI/180),o.lineWidth=1.8,o.strokeStyle=e.outline,o.fillStyle=r.colorIdx<0?e.base:e.accents[r.colorIdx%e.accents.length],Rl(o,r.shape,r.size*1.3),{canvas:i,ox:a,oy:a}}))}function Pl({pitchMidiRef:e}={}){const t=u.useRef(null),r=u.useRef(0),a=u.useRef(0),s=u.useRef(0),i=u.useRef(null),o=u.useRef(0),l=u.useRef(0),c=u.useRef(null),d=u.useRef(null),h=u.useRef(!1),f=u.useCallback((x,v,g)=>{const S=Af+x*mr,b=v/g*Math.PI*2;return S+Math.sin(b)*Ef},[]),p=u.useCallback(x=>{const v=t.current;if(!v)return;if(l.current++,ui>0&&l.current%(ui+1)!==0){s.current=x,r.current=requestAnimationFrame(p);return}const g=v.getContext("2d");if(!g)return;const S=Math.min(window.devicePixelRatio||1,_f),b=v.getBoundingClientRect(),k=b.width,j=b.height;(v.width!==Math.round(k*S)||v.height!==Math.round(j*S))&&(v.width=Math.round(k*S),v.height=Math.round(j*S),g.setTransform(S,0,0,S,0,0));const N=s.current?(x-s.current)/1e3:0;s.current=x,a.current=(a.current+If*N)%k,g.clearRect(0,0,k,j),o.current++,(!i.current||o.current%60===0)&&(i.current=Tl());const R=i.current;Zf(R),g.strokeStyle=R.staffLine,g.lineWidth=.7;for(let A=0;A<Ct;A++){g.beginPath();for(let T=0;T<=k;T+=zf){const O=f(A,T,k);T===0?g.moveTo(T,O):g.lineTo(T,O)}g.stroke()}const w=a.current,M=(e==null?void 0:e.current)??null;if(M!==null){Yf();const A=Wf(M),T=mi*N;for(let O=0;O<ht.length;O++){const V=(ht[O].lineIdx-Kf)*Uf,z=A*gi+(A+V)*(1-gi)-_n[O];_n[O]+=z>0?Math.min(T,z):Math.max(-T,z)}}else if(xa){const A=mi*.4*N;for(let T=0;T<ht.length;T++){const E=ht[T].lineIdx-_n[T];_n[T]+=E>0?Math.min(A,E):Math.max(-A,E)}}const I=c.current;I&&(I.timer-=N,I.timer<=0&&(c.current=null));for(let A=0;A<ht.length;A++){const T=ht[A];if(ir[A]>0){ir[A]-=N;const V=Math.max(0,ir[A]/hi);Cn[A]+=Ff*V*N,Cn[A]>k&&(Cn[A]-=k)}const O=Sa[A];if(!O)continue;const E=T.lineIdx;for(let V=0;V<2;V++){let z=((T.x*k-w-Cn[A]+V*k)%k+k)%k;const q=f(Math.max(0,Math.min(Ct-1,Math.round(E))),z,k),K=(E-Math.round(E))*mr;let re=q+K;if(I&&I.timer>0){const _=z-I.x,U=re-I.y,$=Math.sqrt(_*_+U*U);if($<pi&&$>.1){const P=I.timer/fi,F=Of*(1-$/pi)*P;z+=_/$*F,re+=U/$*F}}g.drawImage(O.canvas,z-O.ox,re-O.oy)}}r.current=requestAnimationFrame(p)},[f]),y=u.useCallback(x=>{const v=t.current;if(!v)return;const g=v.getBoundingClientRect(),S=x.clientX-g.left,b=x.clientY-g.top,k=g.width,j=a.current;let N=1/0,R=-1;for(let w=0;w<ht.length;w++){const M=ht[w],A=((M.x*k-j-Cn[w])%k+k)%k,T=f(Math.max(0,Math.min(Ct-1,Math.round(M.lineIdx))),A,k),O=(M.lineIdx-Math.round(M.lineIdx))*mr,E=T+O,V=A-S,ee=E-b,z=V*V+ee*ee;z<N&&(N=z,R=w)}if(R>=0&&Math.sqrt(N)<Bf){ir[R]=hi;const w=ht[R],M=Gf(w.lineIdx);try{Gt();const I=Ml(),A=cs[I];A!=null&&A.dir&&(gr!==I||!h.current?(h.current=!0,qf(I).then(()=>yi(M))):yi(M))}catch{}}c.current={x:S,y:b,timer:fi}},[f]),m=u.useCallback(x=>{const v=t.current;if(!v)return;const g=v.getBoundingClientRect(),S=x.clientX-g.left,b=x.clientY-g.top;d.current={x:S,y:b},c.current&&c.current.timer>0&&(c.current.x=S,c.current.y=b)},[]);return u.useEffect(()=>(r.current=requestAnimationFrame(p),()=>cancelAnimationFrame(r.current)),[p]),n.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:y,onMouseMove:m,style:{display:"block",width:"100%",height:$l,marginBottom:5,cursor:"pointer",background:"transparent"}})}const Qf=14,Jf=.9,em=320,tm=160,nm=6,vi=8,rm=14;function Al(){const e=u.useRef(null),t=u.useRef([]),r=u.useRef(0),a=u.useRef(0),s=u.useRef([]),i=u.useRef(null),o=u.useRef(0),l=u.useCallback((d,h)=>{for(let f=0;f<Qf;f++){const p=Math.random()*Math.PI*2,y=tm*(.4+Math.random()*.6),m=Jf*(.6+Math.random()*.4),x=Math.random()<.15?0:-1;t.current.push({x:d,y:h,vx:Math.cos(p)*y,vy:Math.sin(p)*y-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*nm*2,size:vi+Math.random()*(rm-vi),shape:Ir[Math.floor(Math.random()*Ir.length)],life:m,maxLife:m,colorIdx:x})}},[]),c=u.useCallback(d=>{const h=e.current;if(!h){r.current=requestAnimationFrame(c);return}const f=h.getContext("2d");if(!f){r.current=requestAnimationFrame(c);return}const p=window.devicePixelRatio||1,y=window.innerWidth,m=window.innerHeight;(h.width!==Math.round(y*p)||h.height!==Math.round(m*p))&&(h.width=Math.round(y*p),h.height=Math.round(m*p),h.style.width=`${y}px`,h.style.height=`${m}px`,f.setTransform(p,0,0,p,0,0));const x=a.current?Math.min((d-a.current)/1e3,.05):0;a.current=d,f.clearRect(0,0,y,m),o.current++,(!i.current||o.current%60===0)&&(i.current=Tl());const v=i.current;if(navigator.getGamepads){const S=navigator.getGamepads();for(let b=0;b<S.length;b++){const k=S[b];if(k)for(let j=0;j<k.buttons.length;j++){const N=b*100+j,R=k.buttons[j].pressed;R&&!s.current[N]&&l(y/2,m/2),s.current[N]=R}}}const g=[];for(const S of t.current){if(S.life-=x,S.life<=0)continue;S.vy+=em*x,S.x+=S.vx*x,S.y+=S.vy*x,S.rot+=S.vr*x;const b=Math.max(0,S.life/S.maxLife),k=.5+.5*b;f.save(),f.globalAlpha=b,f.translate(S.x,S.y),f.rotate(S.rot),f.lineWidth=1.4,f.strokeStyle=v.notesDark?`rgba(255,255,255,${b*.8})`:`rgba(0,0,0,${b*.55})`;const j=S.colorIdx<0?v.base:v.accents[S.colorIdx%v.accents.length];f.fillStyle=j.replace(/[\d.]+\)$/,`${b})`),Rl(f,S.shape,S.size*k*1.3),f.restore(),g.push(S)}t.current=g,r.current=requestAnimationFrame(c)},[l]);return u.useEffect(()=>{const d=f=>{l(f.clientX,f.clientY)},h=f=>{if(f.key!=="Enter")return;const p=document.activeElement;if(p){const y=p.getBoundingClientRect();l(y.left+y.width/2,y.top+y.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",h,!0),r.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",h,!0),cancelAnimationFrame(r.current)}},[c,l]),n.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}const yr={type:"gain",enabled:!0,mix:1,gain:0},Fn={type:"compressor",enabled:!0,mix:1,threshold:-24,ratio:4,attack:10,release:100,knee:6,makeupGain:0},On={type:"reverb",enabled:!0,mix:.3,decay:2,preDelay:10,damping:.5,roomSize:.5},Bn={type:"delay",enabled:!0,mix:.3,time:250,feedback:.4,pingPong:!1,highCut:8e3},br={type:"chorus",enabled:!0,mix:.5,rate:1.5,depth:.5,delay:7,voices:3},vr={type:"eq",enabled:!0,mix:1,bands:[{frequency:60,gain:0,q:1,type:"lowshelf"},{frequency:250,gain:0,q:1,type:"peaking"},{frequency:1e3,gain:0,q:1,type:"peaking"},{frequency:4e3,gain:0,q:1,type:"peaking"},{frequency:12e3,gain:0,q:1,type:"highshelf"}]},xr={type:"filter",enabled:!0,mix:1,filterType:"lowpass",frequency:1e3,q:1,gain:0},Sr={type:"distortion",enabled:!0,mix:.5,drive:.5,tone:.5,curve:"soft"},kr={type:"tremolo",enabled:!0,mix:1,rate:5,depth:.5,waveform:"sine"},wr={type:"phaser",enabled:!0,mix:.5,rate:.5,depth:.5,feedback:.5,stages:4,frequency:1e3},am={gain:{unity:{...yr,gain:0},boost:{...yr,gain:6},cut:{...yr,gain:-6}},compressor:{gentle:{...Fn,threshold:-20,ratio:2,attack:30,release:200},moderate:{...Fn,threshold:-24,ratio:4,attack:10,release:100},aggressive:{...Fn,threshold:-30,ratio:8,attack:1,release:50},limiter:{...Fn,threshold:-3,ratio:20,attack:.1,release:100}},reverb:{small_room:{...On,decay:.5,roomSize:.2,damping:.7},large_hall:{...On,decay:3,roomSize:.8,damping:.3},plate:{...On,decay:1.5,roomSize:.5,damping:.4},cathedral:{...On,decay:5,roomSize:.9,damping:.2,mix:.4}},delay:{slapback:{...Bn,time:80,feedback:.1,mix:.3},quarter_note:{...Bn,time:500,feedback:.4,mix:.3},dotted_eighth:{...Bn,time:375,feedback:.5,mix:.3},long_ambient:{...Bn,time:750,feedback:.6,highCut:3e3,mix:.4}},chorus:{subtle:{...br,rate:.5,depth:.2,voices:2,mix:.3},vintage:{...br,rate:1,depth:.4,voices:2,delay:10,mix:.4},ensemble:{...br,rate:2,depth:.6,voices:4,mix:.5}},eq:{vocal_presence:{...vr,bands:[{frequency:80,gain:-3,q:1,type:"highpass"},{frequency:250,gain:-2,q:1,type:"peaking"},{frequency:3e3,gain:3,q:1.5,type:"peaking"},{frequency:8e3,gain:2,q:1,type:"highshelf"}]},bass_boost:{...vr,bands:[{frequency:60,gain:6,q:1,type:"lowshelf"},{frequency:200,gain:2,q:1,type:"peaking"}]},brightness:{...vr,bands:[{frequency:4e3,gain:3,q:1,type:"peaking"},{frequency:1e4,gain:4,q:1,type:"highshelf"}]}},filter:{low_pass_warm:{...xr,filterType:"lowpass",frequency:2e3,q:.7},high_pass_clean:{...xr,filterType:"highpass",frequency:100,q:.7},telephone:{...xr,filterType:"bandpass",frequency:1500,q:2}},distortion:{overdrive:{...Sr,drive:.3,tone:.6,curve:"soft",mix:.7},crunch:{...Sr,drive:.5,tone:.5,curve:"tube",mix:.8},fuzz:{...Sr,drive:.8,tone:.4,curve:"fuzz",mix:1}},tremolo:{slow:{...kr,rate:3,depth:.4,waveform:"sine"},fast:{...kr,rate:8,depth:.6,waveform:"sine"},choppy:{...kr,rate:6,depth:.9,waveform:"square"}},phaser:{subtle:{...wr,rate:.3,depth:.3,feedback:.3,stages:4},jet:{...wr,rate:.1,depth:.8,feedback:.7,stages:8},rotary:{...wr,rate:1,depth:.5,feedback:.4,stages:6}}};function xi(e){return Math.pow(10,e/20)}function sm(e,t,r,a){const s=e.sampleRate,i=Math.floor(s*t),o=e.createBuffer(2,i,s);for(let l=0;l<2;l++){const c=o.getChannelData(l);for(let d=0;d<i;d++){const h=d/s,f=Math.exp(-h/r),p=1-a*(d/i);c[d]=(Math.random()*2-1)*f*p}}return o}function im(e,t){const a=new Float32Array(44100),s=Math.PI/180;for(let i=0;i<44100;i++){const o=i*2/44100-1;switch(t){case"soft":a[i]=(3+e*10)*o*20*s/(Math.PI+e*10*Math.abs(o));break;case"hard":a[i]=Math.tanh(o*(1+e*5));break;case"fuzz":a[i]=Math.sign(o)*Math.pow(Math.abs(o),1/(1+e*3));break;case"tube":o>=0?a[i]=1-Math.pow(1-o,1+e*2):a[i]=-(1-Math.pow(1+o,1+e*2));break}}return a}class om{constructor(t){this.effects=[],this.bypass=!1,this.audioContext=t,this.inputNode=t.createGain(),this.outputNode=t.createGain(),this.inputNode.connect(this.outputNode)}get input(){return this.inputNode}get output(){return this.outputNode}addEffect(t,r){const a=`effect_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=this.createEffectInstance(a,t);return r!==void 0&&r>=0&&r<this.effects.length?this.effects.splice(r,0,s):this.effects.push(s),this.reconnectChain(),a}removeEffect(t){const r=this.effects.findIndex(s=>s.id===t);if(r===-1)return!1;const a=this.effects[r];for(const s of a.nodes)s.disconnect();return this.effects.splice(r,1),this.reconnectChain(),!0}updateEffect(t,r){const a=this.effects.find(l=>l.id===t);if(!a)return!1;const s={...a.params,...r},i=this.effects.indexOf(a);for(const l of a.nodes)l.disconnect();const o=this.createEffectInstance(t,s);return this.effects[i]=o,this.reconnectChain(),!0}reorderEffects(t,r){if(t<0||t>=this.effects.length||r<0||r>=this.effects.length)return!1;const[a]=this.effects.splice(t,1);return this.effects.splice(r,0,a),this.reconnectChain(),!0}setBypass(t){this.bypass=t,this.reconnectChain()}getEffects(){return[...this.effects]}clear(){for(const t of this.effects)for(const r of t.nodes)r.disconnect();this.effects=[],this.reconnectChain()}createEffectInstance(t,r){const{audioContext:a}=this,s=[];let i,o;switch(r.type){case"gain":{const l=a.createGain();l.gain.value=xi(r.gain),s.push(l),i=o=l;break}case"compressor":{const l=a.createDynamicsCompressor();l.threshold.value=r.threshold,l.ratio.value=r.ratio,l.attack.value=r.attack/1e3,l.release.value=r.release/1e3,l.knee.value=r.knee;const c=a.createGain();c.gain.value=xi(r.makeupGain),l.connect(c),s.push(l,c),i=l,o=c;break}case"reverb":{const l=a.createConvolver();l.buffer=sm(a,r.decay,r.decay,r.damping);const c=a.createGain(),d=a.createGain(),h=a.createGain(),f=a.createGain();c.gain.value=r.mix,d.gain.value=1-r.mix,h.connect(l),h.connect(d),l.connect(c),c.connect(f),d.connect(f),s.push(h,l,c,d,f),i=h,o=f;break}case"delay":{const l=a.createDelay(5);l.delayTime.value=r.time/1e3;const c=a.createGain();c.gain.value=r.feedback;const d=a.createBiquadFilter();d.type="lowpass",d.frequency.value=r.highCut;const h=a.createGain(),f=a.createGain(),p=a.createGain(),y=a.createGain();h.gain.value=r.mix,f.gain.value=1-r.mix,p.connect(l),p.connect(f),l.connect(d),d.connect(c),c.connect(l),d.connect(h),h.connect(y),f.connect(y),s.push(p,l,d,c,h,f,y),i=p,o=y;break}case"eq":{const l=[];let c=null;for(const d of r.bands){const h=a.createBiquadFilter();h.type=d.type,h.frequency.value=d.frequency,h.Q.value=d.q,h.gain.value=d.gain,c&&c.connect(h),c=h,l.push(h)}s.push(...l),i=l[0]||a.createGain(),o=l[l.length-1]||i;break}case"filter":{const l=a.createBiquadFilter();l.type=r.filterType,l.frequency.value=r.frequency,l.Q.value=r.q,l.gain.value=r.gain,s.push(l),i=o=l;break}case"distortion":{const l=a.createWaveShaper();l.curve=im(r.drive,r.curve),l.oversample="4x";const c=a.createBiquadFilter();c.type="lowpass",c.frequency.value=1e3+r.tone*1e4;const d=a.createGain(),h=a.createGain(),f=a.createGain(),p=a.createGain();d.gain.value=r.mix,h.gain.value=1-r.mix,f.connect(l),f.connect(h),l.connect(c),c.connect(d),d.connect(p),h.connect(p),s.push(f,l,c,d,h,p),i=f,o=p;break}case"tremolo":{const l=a.createOscillator();l.type=r.waveform,l.frequency.value=r.rate;const c=a.createGain();c.gain.value=r.depth*.5;const d=a.createGain();d.gain.value=1-r.depth*.5,l.connect(c),c.connect(d.gain),l.start(),s.push(l,c,d),i=o=d;break}case"phaser":{const l=[],c=a.createOscillator();c.type="sine",c.frequency.value=r.rate;const d=a.createGain();d.gain.value=r.depth*r.frequency;let h=null;for(let x=0;x<r.stages;x++){const v=a.createBiquadFilter();v.type="allpass",v.frequency.value=r.frequency,v.Q.value=.5,c.connect(d),d.connect(v.frequency),h&&h.connect(v),h=v,l.push(v)}const f=a.createGain(),p=a.createGain(),y=a.createGain(),m=a.createGain();f.gain.value=r.mix,p.gain.value=1-r.mix,y.connect(l[0]),y.connect(p),l[l.length-1].connect(f),f.connect(m),p.connect(m),c.start(),s.push(c,d,...l,f,p,y,m),i=y,o=m;break}default:throw new Error(`Unknown effect type: ${r.type}`)}return{id:t,params:r,nodes:s,input:i,output:o}}reconnectChain(){this.inputNode.disconnect();for(const r of this.effects)r.output.disconnect();if(this.bypass||this.effects.length===0){this.inputNode.connect(this.outputNode);return}let t=this.inputNode;for(const r of this.effects)r.params.enabled&&(t.connect(r.input),t=r.output);t.connect(this.outputNode)}dispose(){this.clear(),this.inputNode.disconnect(),this.outputNode.disconnect()}}const El={gain:n.jsx(W.NtdVolume,{size:16}),compressor:n.jsx(W.NtdSettings,{size:16}),reverb:n.jsx(W.NtdMountain,{size:16}),delay:n.jsx(W.NtdStopwatch,{size:16}),chorus:n.jsx(W.NtdSparkle,{size:16}),eq:n.jsx(W.NtdBarChart,{size:16}),filter:n.jsx(W.NtdFilter,{size:16}),distortion:n.jsx(W.NtdLightning,{size:16}),tremolo:n.jsx(W.NtdWave,{size:16}),phaser:n.jsx(W.NtdMagicWand,{size:16})},Il={gain:"Gain",compressor:"Compressor",reverb:"Reverb",delay:"Delay",chorus:"Chorus",eq:"EQ",filter:"Filter",distortion:"Distortion",tremolo:"Tremolo",phaser:"Phaser"},lm={gain:yr,compressor:Fn,reverb:On,delay:Bn,chorus:br,eq:vr,filter:xr,distortion:Sr,tremolo:kr,phaser:wr},cm=["gain","compressor","reverb","delay","chorus","eq","filter","distortion","tremolo","phaser"],De=({value:e,min:t,max:r,step:a=1,label:s,unit:i="",onChange:o,disabled:l})=>{const c=u.useRef(null),[d,h]=u.useState(!1),f=u.useRef(0),p=u.useRef(e),y=u.useCallback(x=>{l||(x.preventDefault(),h(!0),f.current=x.clientY,p.current=e)},[l,e]);u.useEffect(()=>{if(!d)return;const x=g=>{const S=f.current-g.clientY,b=r-t,j=S/200*b,N=Math.min(r,Math.max(t,p.current+j));o(a<1?N:Math.round(N/a)*a)},v=()=>{h(!1)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",v),()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",v)}},[d,t,r,a,o]);const m=(e-t)/(r-t)*270-135;return n.jsxs("div",{className:`nice-fx-knob ${l?"nice-fx-knob--disabled":""}`,ref:c,children:[n.jsx("div",{className:`nice-fx-knob__dial ${d?"nice-fx-knob__dial--active":""}`,onMouseDown:y,style:{transform:`rotate(${m}deg)`},children:n.jsx("div",{className:"nice-fx-knob__indicator"})}),n.jsx("div",{className:"nice-fx-knob__label",children:s}),n.jsxs("div",{className:"nice-fx-knob__value",children:[typeof e=="number"&&a<1?e.toFixed(2):e,i]})]})};function dm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsx(De,{value:e.gain,min:-60,max:12,step:.1,label:"Gain",unit:"dB",onChange:d=>t({...e,gain:d}),disabled:!e.enabled})})}function um({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(De,{value:e.threshold,min:-60,max:0,label:"Threshold",unit:"dB",onChange:d=>t({...e,threshold:d}),disabled:!e.enabled}),n.jsx(De,{value:e.ratio,min:1,max:20,label:"Ratio",onChange:d=>t({...e,ratio:d}),disabled:!e.enabled}),n.jsx(De,{value:e.attack,min:.1,max:200,label:"Attack",unit:"ms",onChange:d=>t({...e,attack:d}),disabled:!e.enabled}),n.jsx(De,{value:e.release,min:10,max:1e3,label:"Release",unit:"ms",onChange:d=>t({...e,release:d}),disabled:!e.enabled}),!c&&n.jsxs(n.Fragment,{children:[n.jsx(De,{value:e.knee,min:0,max:40,label:"Knee",unit:"dB",onChange:d=>t({...e,knee:d}),disabled:!e.enabled}),n.jsx(De,{value:e.makeupGain,min:0,max:24,label:"Makeup",unit:"dB",onChange:d=>t({...e,makeupGain:d}),disabled:!e.enabled})]})]})})}function hm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(De,{value:e.decay,min:.1,max:10,step:.1,label:"Decay",unit:"s",onChange:d=>t({...e,decay:d}),disabled:!e.enabled}),n.jsx(De,{value:e.damping,min:0,max:1,step:.01,label:"Damping",onChange:d=>t({...e,damping:d}),disabled:!e.enabled}),n.jsx(De,{value:e.roomSize,min:0,max:1,step:.01,label:"Room",onChange:d=>t({...e,roomSize:d}),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function pm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(De,{value:e.time,min:0,max:2e3,label:"Time",unit:"ms",onChange:d=>t({...e,time:d}),disabled:!e.enabled}),n.jsx(De,{value:e.feedback,min:0,max:1,step:.01,label:"Feedback",onChange:d=>t({...e,feedback:d}),disabled:!e.enabled}),n.jsx(De,{value:e.highCut,min:200,max:2e4,label:"HiCut",unit:"Hz",onChange:d=>t({...e,highCut:d}),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function fm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsxs("div",{className:"nice-fx-card__controls",children:[n.jsx(De,{value:e.drive,min:0,max:1,step:.01,label:"Drive",onChange:d=>t({...e,drive:d}),disabled:!e.enabled}),n.jsx(De,{value:e.tone,min:0,max:1,step:.01,label:"Tone",onChange:d=>t({...e,tone:d}),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})]})})}function jt({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:d}){const[h,f]=u.useState(!1);return n.jsxs("div",{className:`nice-fx-card ${e.enabled?"":"nice-fx-card--disabled"} ${i?"nice-fx-card--drop-target":""} ${c?"nice-fx-card--compact":""}`,draggable:!0,onDragStart:a,onDragEnd:s,children:[n.jsxs("div",{className:"nice-fx-card__header",children:[n.jsx("span",{className:"nice-fx-card__icon",children:El[e.type]}),n.jsx("span",{className:"nice-fx-card__title",children:Il[e.type]}),n.jsx("button",{type:"button",className:`nice-fx-card__toggle ${e.enabled?"nice-fx-card__toggle--active":""}`,onClick:()=>t({...e,enabled:!e.enabled}),title:e.enabled?"Disable":"Enable","aria-pressed":e.enabled,children:n.jsx("span",{className:"nice-fx-card__toggle-dot","aria-hidden":"true"})}),l&&Object.keys(o).length>0&&n.jsxs("div",{className:"nice-fx-card__presets",children:[n.jsx("button",{type:"button",className:"nice-fx-card__preset-btn",onClick:()=>f(!h),"aria-label":"Presets",children:n.jsx(W.NtdChevronDown,{size:12})}),h&&n.jsx("div",{className:"nice-fx-card__preset-menu",children:Object.entries(o).map(([p,y])=>n.jsx("button",{type:"button",className:"nice-fx-card__preset-item",onClick:()=>{t({...y,enabled:e.enabled}),f(!1)},children:p.replace(/_/g," ")},p))})]}),n.jsx("button",{type:"button",className:"nice-fx-card__remove",onClick:r,title:"Remove",children:"×"})]}),n.jsx("div",{className:"nice-fx-card__body",children:d})]})}function mm({effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c}){return n.jsx(jt,{effect:e,onChange:t,onRemove:r,onDragStart:a,onDragEnd:s,isDragTarget:i,presets:o,showPresets:l,compact:c,children:n.jsx("div",{className:"nice-fx-card__generic",children:n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:d=>t({...e,mix:d}),disabled:!e.enabled})})})}function gm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(jt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(De,{value:a.rate??1.5,min:.1,max:10,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(De,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(De,{value:a.feedback??.3,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function ym({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(jt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(De,{value:a.low??0,min:-12,max:12,step:.5,label:"Low",onChange:i=>s("low",i),disabled:!e.enabled}),n.jsx(De,{value:a.mid??0,min:-12,max:12,step:.5,label:"Mid",onChange:i=>s("mid",i),disabled:!e.enabled}),n.jsx(De,{value:a.high??0,min:-12,max:12,step:.5,label:"High",onChange:i=>s("high",i),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function bm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(jt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(De,{value:a.frequency??1e3,min:20,max:2e4,step:1,label:"Freq",onChange:i=>s("frequency",i),disabled:!e.enabled}),n.jsx(De,{value:a.Q??1,min:.1,max:20,step:.1,label:"Q",onChange:i=>s("Q",i),disabled:!e.enabled}),n.jsx(De,{value:a.gain??0,min:-24,max:24,step:.5,label:"Gain",onChange:i=>s("gain",i),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function vm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(jt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(De,{value:a.rate??5,min:.1,max:20,step:.1,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(De,{value:a.depth??.5,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}function xm({effect:e,onChange:t,...r}){const a=e.params||{},s=(i,o)=>t({...e,params:{...a,[i]:o}});return n.jsx(jt,{effect:e,onChange:t,...r,children:n.jsxs("div",{className:"nice-fx-card__row",children:[n.jsx(De,{value:a.rate??.5,min:.01,max:8,step:.01,label:"Rate",onChange:i=>s("rate",i),disabled:!e.enabled}),n.jsx(De,{value:a.depth??.7,min:0,max:1,step:.01,label:"Depth",onChange:i=>s("depth",i),disabled:!e.enabled}),n.jsx(De,{value:a.feedback??.5,min:0,max:.95,step:.01,label:"Feedback",onChange:i=>s("feedback",i),disabled:!e.enabled}),n.jsx(De,{value:a.stages??4,min:2,max:12,step:2,label:"Stages",onChange:i=>s("stages",i),disabled:!e.enabled}),n.jsx(De,{value:e.mix,min:0,max:1,step:.01,label:"Mix",onChange:i=>t({...e,mix:i}),disabled:!e.enabled})]})})}const Sm=({audioContext:e,chain:t,effects:r,onChange:a,onChainUpdate:s,maxEffects:i=10,availableEffects:o=cm,showPresets:l=!0,compact:c=!1,className:d=""})=>{const[h,f]=u.useState((r==null?void 0:r.map(w=>w.params))||[]),[p,y]=u.useState({isDragging:!1,dragIndex:-1,dropIndex:-1}),[m,x]=u.useState(!1),v=u.useMemo(()=>t||(e?new om(e):null),[e,t]),g=u.useCallback((w,M)=>{const I=[...h];I[w]=M,f(I),a==null||a(I),v&&(s==null||s(v))},[h,a,v,s]),S=u.useCallback(w=>{if(h.length>=i)return;const M={...lm[w]},I=[...h,M];f(I),a==null||a(I),x(!1)},[h,i,a]),b=u.useCallback(w=>{const M=h.filter((I,A)=>A!==w);f(M),a==null||a(M)},[h,a]),k=u.useCallback(w=>{y({isDragging:!0,dragIndex:w,dropIndex:-1})},[]),j=u.useCallback(()=>{if(p.dragIndex!==-1&&p.dropIndex!==-1&&p.dragIndex!==p.dropIndex){const w=[...h],[M]=w.splice(p.dragIndex,1);w.splice(p.dropIndex,0,M),f(w),a==null||a(w)}y({isDragging:!1,dragIndex:-1,dropIndex:-1})},[p,h,a]),N=u.useCallback((w,M)=>{w.preventDefault(),p.isDragging&&y(I=>({...I,dropIndex:M}))},[p.isDragging]),R=(w,M)=>{const I={onRemove:()=>b(M),onDragStart:()=>k(M),onDragEnd:j,isDragTarget:p.dropIndex===M,presets:am[w.type]||{},showPresets:l,compact:c};switch(w.type){case"gain":return n.jsx(dm,{effect:w,onChange:A=>g(M,A),...I},M);case"compressor":return n.jsx(um,{effect:w,onChange:A=>g(M,A),...I},M);case"reverb":return n.jsx(hm,{effect:w,onChange:A=>g(M,A),...I},M);case"delay":return n.jsx(pm,{effect:w,onChange:A=>g(M,A),...I},M);case"distortion":return n.jsx(fm,{effect:w,onChange:A=>g(M,A),...I},M);case"chorus":return n.jsx(gm,{effect:w,onChange:A=>g(M,A),...I},M);case"eq":return n.jsx(ym,{effect:w,onChange:A=>g(M,A),...I},M);case"filter":return n.jsx(bm,{effect:w,onChange:A=>g(M,A),...I},M);case"tremolo":return n.jsx(vm,{effect:w,onChange:A=>g(M,A),...I},M);case"phaser":return n.jsx(xm,{effect:w,onChange:A=>g(M,A),...I},M);default:return n.jsx(mm,{effect:w,onChange:A=>g(M,A),...I},M)}};return n.jsxs("div",{className:`nice-fx-rack ${c?"nice-fx-rack--compact":""} ${d}`,children:[n.jsxs("div",{className:"nice-fx-rack__header",children:[n.jsx("h3",{className:"nice-fx-rack__title",children:"Effects Chain"}),n.jsxs("span",{className:"nice-fx-rack__count",children:[h.length,"/",i]})]}),n.jsx("div",{className:"nice-fx-rack__chain",children:h.length===0?n.jsx("div",{className:"nice-fx-rack__empty",children:"No effects. Click + to add."}):h.map((w,M)=>n.jsxs("div",{className:"nice-fx-rack__slot",onDragOver:I=>N(I,M),children:[R(w,M),M<h.length-1&&n.jsx("div",{className:"nice-fx-rack__connector","aria-hidden":"true",children:n.jsx(W.NtdArrowRight,{size:14})})]},M))}),h.length<i&&n.jsxs("div",{className:"nice-fx-rack__add",children:[n.jsx("button",{type:"button",className:"nice-fx-rack__add-btn",onClick:()=>x(!m),children:"+ Add Effect"}),m&&n.jsx("div",{className:"nice-fx-rack__add-menu",children:o.map(w=>n.jsxs("button",{type:"button",className:"nice-fx-rack__add-item",onClick:()=>S(w),children:[n.jsx("span",{className:"nice-fx-rack__add-icon",children:El[w]}),n.jsx("span",{className:"nice-fx-rack__add-label",children:Il[w]})]},w))})]})]})},Ll=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"sparkle"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"sparkle"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"music"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"skull"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"robot"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"ghost"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"mountain"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"mountain"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"wave"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"music"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"wave"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"lightning"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"phone"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"megaphone"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"wave"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"wave"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"volume-mute"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"wave"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"microphone"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"volume"}];function Si(e,t,r){const a=e.sampleRate,s=Math.round(a*t),i=e.createBuffer(2,s,a);for(let o=0;o<2;o++){const l=i.getChannelData(o);for(let c=0;c<s;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/s,r)}return i}function or(e){const t=Math.max(1,e),r=44100,a=new Float32Array(r),s=Math.PI/180;for(let i=0;i<r;i++){const o=i*2/r-1;a[i]=(3+t)*o*20*s/(Math.PI+t*Math.abs(o))}return a}class Dl{constructor(){this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.activeEffects=new Map,this.effectOrder=[],this.monitoring=!0,this._volume=1,this._inputVolume=1,this.started=!1,this.externalStream=!1,this.analyser=null}get isStarted(){return this.started}get context(){return this.audioCtx}get activeEffectTypes(){return[...this.effectOrder]}async start(t){this.started||(this.audioCtx=new AudioContext,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t||void 0,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}}),this.sourceNode=this.audioCtx.createMediaStreamSource(this.mediaStream),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}async startWithStream(t){this.started||(this.externalStream=!0,this.audioCtx=new AudioContext,this.mediaStream=t,this.sourceNode=this.audioCtx.createMediaStreamSource(t),this.inputGain=this.audioCtx.createGain(),this.inputGain.gain.value=this._inputVolume,this.sourceNode.connect(this.inputGain),this.outputGain=this.audioCtx.createGain(),this.outputGain.gain.value=this.monitoring?this._volume:0,this.analyser=this.audioCtx.createAnalyser(),this.analyser.fftSize=2048,this.inputGain.connect(this.outputGain),this.outputGain.connect(this.analyser),this.analyser.connect(this.audioCtx.destination),this.started=!0)}stop(){var t,r,a,s,i,o;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(r=this.outputGain)==null||r.disconnect()}catch{}try{(a=this.inputGain)==null||a.disconnect()}catch{}try{(s=this.sourceNode)==null||s.disconnect()}catch{}try{(i=this.audioCtx)==null||i.close()}catch{}if(!this.externalStream)try{(o=this.mediaStream)==null||o.getTracks().forEach(l=>l.stop())}catch{}this.audioCtx=null,this.mediaStream=null,this.sourceNode=null,this.inputGain=null,this.outputGain=null,this.analyser=null,this.started=!1}setMonitoring(t){this.monitoring=t,this.outputGain&&(this.outputGain.gain.value=t?this._volume:0)}setVolume(t){this._volume=Math.max(0,Math.min(2,t)),this.outputGain&&this.monitoring&&(this.outputGain.gain.value=this._volume)}setInputGain(t){this._inputVolume=Math.max(0,Math.min(3,t)),this.inputGain&&(this.inputGain.gain.value=this._inputVolume)}getLevel(){if(!this.analyser)return 0;const t=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(t);let r=0;for(let a=0;a<t.length;a++){const s=(t[a]-128)/128;r+=s*s}return Math.sqrt(r/t.length)}addEffect(t,r=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const a=this.buildEffectChain(t,r);a&&(this.activeEffects.set(t,a),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const r=this.activeEffects.get(t);if(r){for(const a of r.nodes)try{a.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(a=>a!==t),this.reconnectChain()}}toggleEffect(t,r=50){return this.activeEffects.has(t)?(this.removeEffect(t),!1):(this.addEffect(t,r),!0)}updateIntensity(t,r){this.activeEffects.has(t)&&(this.removeEffect(t),this.addEffect(t,r))}clearAllEffects(){for(const[t]of this.activeEffects){const r=this.activeEffects.get(t);if(r)for(const a of r.nodes)try{a.disconnect()}catch{}}this.activeEffects.clear(),this.effectOrder=[],this.reconnectChain()}reconnectChain(){if(!this.inputGain||!this.outputGain)return;try{this.inputGain.disconnect()}catch{}for(const[,r]of this.activeEffects)try{r.output.disconnect()}catch{}if(this.effectOrder.length===0){this.inputGain.connect(this.outputGain);return}let t=this.inputGain;for(const r of this.effectOrder){const a=this.activeEffects.get(r);a&&(t.connect(a.input),t=a.output)}t.connect(this.outputGain)}buildEffectChain(t,r){const a=this.audioCtx,s=r/100;switch(t){case"chipmunk":return this.buildPitchShift(a,1+s*.8,s);case"helium":return this.buildPitchShift(a,1.5+s*1,s);case"deep":return this.buildPitchShift(a,1/(1+s*.5),s);case"demon":return this.buildDemon(a,s);case"robot":return this.buildRobot(a,s);case"alien":return this.buildAlien(a,s);case"echo":return this.buildDelay(a,.15+s*.35,.3+s*.4,s);case"cave":return this.buildCave(a,s);case"reverb":return this.buildReverb(a,1.5+s*3,2+s*4,s);case"chorus":return this.buildChorus(a,s);case"flanger":return this.buildFlanger(a,s);case"distortion":return this.buildDistortion(a,20+s*100,s);case"telephone":return this.buildBandpass(a,400,3500,s);case"megaphone":return this.buildMegaphone(a,s);case"radio":return this.buildRadio(a,s);case"underwater":return this.buildUnderwater(a,s);case"whisper":return this.buildWhisper(a,s);case"tremolo":return this.buildTremolo(a,s);case"autotune":return this.buildAutotune(a,s);case"vocoder":return this.buildVocoder(a,s);default:return null}}buildPitchShift(t,r,a){const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=1;const o=t.createGain();o.gain.value=.7+a*.3;const l=t.createGain();l.gain.value=1-a*.5;const c=t.createDelay(1),d=t.createDelay(1),h=t.createOscillator(),f=t.createOscillator(),p=t.createGain(),y=t.createGain(),m=r-1,x=Math.abs(m)*5+2,v=Math.abs(m)*.015;h.type="sawtooth",h.frequency.value=x,p.gain.value=v,h.connect(p),p.connect(c.delayTime),c.delayTime.value=.02,f.type="sawtooth",f.frequency.value=x,y.gain.value=v,f.connect(y),y.connect(d.delayTime),d.delayTime.value=.02+v;const g=t.createGain();g.gain.value=.5;const S=t.createGain();return S.gain.value=.5,s.connect(c),s.connect(d),c.connect(g),d.connect(S),g.connect(o),S.connect(o),s.connect(l),o.connect(i),l.connect(i),h.start(),f.start(),{type:"chipmunk",nodes:[s,c,d,h,f,p,y,g,S,o,l,i],input:s,output:i}}buildRobot(t,r){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=.6+r*.4;const o=t.createGain();o.gain.value=1-r*.6;const l=t.createOscillator();l.type="square",l.frequency.value=50+r*200;const c=t.createGain();return c.gain.value=0,l.connect(c.gain),a.connect(c),c.connect(i),a.connect(o),i.connect(s),o.connect(s),l.start(),{type:"robot",nodes:[a,l,c,i,o,s],input:a,output:s}}buildAlien(t,r){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sine",i.frequency.value=300+r*700;const o=t.createGain();o.gain.value=0,i.connect(o.gain),a.connect(o);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+r*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),o.connect(l),l.connect(s);const h=t.createGain();return h.gain.value=.3,a.connect(h),h.connect(s),i.start(),c.start(),{type:"alien",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDelay(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createDelay(2);l.delayTime.value=r;const c=t.createGain();c.gain.value=Math.min(.85,a);const d=t.createGain();d.gain.value=.5+s*.5;const h=t.createGain();return h.gain.value=1,i.connect(l),l.connect(c),c.connect(l),l.connect(d),i.connect(h),d.connect(o),h.connect(o),{type:"echo",nodes:[i,l,c,d,h,o],input:i,output:o}}buildCave(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(2);i.delayTime.value=.2+r*.3;const o=t.createDelay(2);o.delayTime.value=.35+r*.25;const l=t.createDelay(2);l.delayTime.value=.55+r*.3;const c=t.createGain();c.gain.value=.5;const d=t.createGain();d.gain.value=.35;const h=t.createGain();h.gain.value=.25;const f=t.createConvolver();f.buffer=Si(t,2+r*3,3);const p=t.createGain();p.gain.value=.3+r*.3,a.connect(i),i.connect(c),c.connect(i),a.connect(o),o.connect(d),d.connect(o),a.connect(l),l.connect(h),h.connect(l),i.connect(p),o.connect(p),l.connect(p),a.connect(f),f.connect(p);const y=t.createGain();return y.gain.value=.7,a.connect(y),y.connect(s),p.connect(s),{type:"cave",nodes:[a,i,o,l,c,d,h,f,p,y,s],input:a,output:s}}buildReverb(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createConvolver();l.buffer=Si(t,r,a);const c=t.createGain();c.gain.value=.4+s*.5;const d=t.createGain();return d.gain.value=1,i.connect(l),l.connect(c),i.connect(d),c.connect(o),d.connect(o),{type:"reverb",nodes:[i,l,c,d,o],input:i,output:o}}buildChorus(t,r){const a=t.createGain(),s=t.createGain(),i=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],o=[a,s],l=t.createGain();l.gain.value=.7,a.connect(l),l.connect(s),o.push(l);for(const c of i){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const h=t.createOscillator();h.type="sine",h.frequency.value=c.lfoFreq;const f=t.createGain();f.gain.value=c.depth*(.5+r),h.connect(f),f.connect(d.delayTime);const p=t.createGain();p.gain.value=.3+r*.2,a.connect(d),d.connect(p),p.connect(s),h.start(),o.push(d,h,f,p)}return{type:"chorus",nodes:o,input:a,output:s}}buildFlanger(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.02);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=.2+r*2;const l=t.createGain();l.gain.value=.003+r*.002,o.connect(l),l.connect(i.delayTime);const c=t.createGain();c.gain.value=.5+r*.35;const d=t.createGain();d.gain.value=.5+r*.3;const h=t.createGain();return h.gain.value=1,a.connect(i),i.connect(c),c.connect(i),i.connect(d),a.connect(h),d.connect(s),h.connect(s),o.start(),{type:"flanger",nodes:[a,i,o,l,c,d,h,s],input:a,output:s}}buildDistortion(t,r,a){const s=t.createGain(),i=t.createGain(),o=t.createWaveShaper();o.curve=or(r),o.oversample="4x";const l=t.createGain();l.gain.value=.6+a*.4;const c=t.createGain();return c.gain.value=1-a*.4,s.connect(o),o.connect(l),s.connect(c),l.connect(i),c.connect(i),{type:"distortion",nodes:[s,o,l,c,i],input:s,output:i}}buildBandpass(t,r,a,s){const i=t.createGain(),o=t.createGain(),l=t.createBiquadFilter();l.type="highpass",l.frequency.value=r,l.Q.value=.7;const c=t.createBiquadFilter();return c.type="lowpass",c.frequency.value=a,c.Q.value=.7,i.connect(l),l.connect(c),c.connect(o),{type:"telephone",nodes:[i,l,c,o],input:i,output:o}}buildMegaphone(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=4e3;const l=t.createWaveShaper();l.curve=or(15+r*30),l.oversample="2x";const c=t.createBiquadFilter();return c.type="peaking",c.frequency.value=2e3,c.gain.value=6+r*6,c.Q.value=1,a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"megaphone",nodes:[a,i,o,l,c,s],input:a,output:s}}buildRadio(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=300+r*200;const o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=3e3-r*500;const l=t.createBiquadFilter();l.type="peaking",l.frequency.value=1500,l.gain.value=8,l.Q.value=2;const c=t.createWaveShaper();return c.curve=or(10),a.connect(i),i.connect(o),o.connect(l),l.connect(c),c.connect(s),{type:"radio",nodes:[a,i,o,l,c,s],input:a,output:s}}buildUnderwater(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=300+(1-r)*400,i.Q.value=5+r*10;const o=t.createOscillator();o.type="sine",o.frequency.value=.5+r*2;const l=t.createGain();l.gain.value=100+r*200,o.connect(l),l.connect(i.frequency);const c=t.createGain();c.gain.value=.7+r*.3;const d=t.createGain();return d.gain.value=.3-r*.2,a.connect(i),i.connect(c),a.connect(d),c.connect(s),d.connect(s),o.start(),{type:"underwater",nodes:[a,i,o,l,c,d,s],input:a,output:s}}buildWhisper(t,r){const a=t.createGain(),s=t.createGain(),i=t.createBiquadFilter();i.type="highpass",i.frequency.value=500+r*500,i.Q.value=.5;const o=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const h=d/255*2-1;l[d]=Math.sign(h)*Math.pow(Math.abs(h),.3+r*.5)}o.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+r*6,a.connect(i),i.connect(o),o.connect(c),c.connect(s),{type:"whisper",nodes:[a,i,o,c,s],input:a,output:s}}buildDemon(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.1);i.delayTime.value=.03;const o=t.createOscillator();o.type="sawtooth",o.frequency.value=2+r*3;const l=t.createGain();l.gain.value=.02+r*.015,o.connect(l),l.connect(i.delayTime);const c=t.createWaveShaper();c.curve=or(20+r*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+r*8;const h=t.createGain();h.gain.value=.7+r*.3;const f=t.createGain();return f.gain.value=.3,a.connect(i),i.connect(c),c.connect(d),d.connect(h),a.connect(f),h.connect(s),f.connect(s),o.start(),{type:"demon",nodes:[a,i,o,l,c,d,h,f,s],input:a,output:s}}buildTremolo(t,r){const a=t.createGain(),s=t.createGain(),i=t.createGain();i.gain.value=1;const o=t.createOscillator();o.type="sine",o.frequency.value=3+r*12;const l=t.createGain();return l.gain.value=.3+r*.5,o.connect(l),l.connect(i.gain),a.connect(i),i.connect(s),o.start(),{type:"tremolo",nodes:[a,i,o,l,s],input:a,output:s}}buildAutotune(t,r){const a=t.createGain(),s=t.createGain(),i=t.createDelay(.05);i.delayTime.value=.005;const o=t.createOscillator();o.type="sine",o.frequency.value=6+r*8;const l=t.createGain();l.gain.value=.002+r*.002,o.connect(l),l.connect(i.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],h=t.createGain();h.gain.value=.15;for(const y of d){const m=t.createBiquadFilter();m.type="peaking",m.frequency.value=y,m.Q.value=8+r*15,m.gain.value=4+r*8,a.connect(m),m.connect(h),c.push(m)}const f=t.createGain();f.gain.value=.7;const p=t.createGain();return p.gain.value=.5+r*.3,a.connect(i),i.connect(p),h.connect(p),a.connect(f),p.connect(s),f.connect(s),o.start(),{type:"autotune",nodes:[a,i,o,l,...c,h,p,f,s],input:a,output:s}}buildVocoder(t,r){const a=t.createGain(),s=t.createGain(),i=t.createOscillator();i.type="sawtooth",i.frequency.value=110+r*110;const o=t.createGain();o.gain.value=0;const l=8,c=[a,s,i,o],d=t.createGain();d.gain.value=.5+r*.5,c.push(d);for(let f=0;f<l;f++){const p=200*Math.pow(2,f*.5),y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=p,y.Q.value=4;const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=p,m.Q.value=4;const x=t.createGain();x.gain.value=0,a.connect(y),y.connect(x.gain),i.connect(m),m.connect(x),x.connect(d),c.push(y,m,x)}d.connect(s);const h=t.createGain();return h.gain.value=.3-r*.2,a.connect(h),h.connect(s),c.push(h),i.start(),{type:"vocoder",nodes:c,input:a,output:s}}}const km={sparkle:W.NtdSparkle,music:W.NtdMusic,skull:W.NtdSkull,robot:W.NtdRobot,ghost:W.NtdGhost,mountain:W.NtdMountain,wave:W.NtdWave,lightning:W.NtdLightning,phone:W.NtdPhone,megaphone:W.NtdMegaphone,"volume-mute":W.NtdVolumeMute,microphone:W.NtdMicrophone,volume:W.NtdVolume},wm=({deviceId:e,mediaStream:t,compact:r=!1,t:a,className:s,style:i,id:o,accessMode:l,"data-testid":c})=>{const{t:d}=Te(),h=a??d,f=u.useRef(null),[p,y]=u.useState(!1),[m,x]=u.useState(()=>Ll.map(z=>({...z}))),[v,g]=u.useState(!0),[S,b]=u.useState(80),[k,j]=u.useState(100),[N,R]=u.useState(0),w=u.useRef(0),M=u.useCallback(()=>{const z=()=>{var q;(q=f.current)!=null&&q.isStarted&&(R(f.current.getLevel()),w.current=requestAnimationFrame(z))};w.current=requestAnimationFrame(z)},[]),I=u.useCallback(()=>{w.current&&cancelAnimationFrame(w.current)},[]),A=u.useCallback(async()=>{const z=new Dl;f.current=z;try{t?await z.startWithStream(t):await z.start(e),z.setMonitoring(v),z.setVolume(S/100),z.setInputGain(k/100);for(const q of m)q.enabled&&z.addEffect(q.type,q.intensity);y(!0),M()}catch(q){typeof console<"u"&&console.warn("[VocalEffectsRack] start error",q)}},[e,t,v,S,k,m,M]),T=u.useCallback(()=>{var z;I(),(z=f.current)==null||z.stop(),f.current=null,y(!1),R(0)},[I]);u.useEffect(()=>()=>{var z;I(),(z=f.current)==null||z.stop(),f.current=null},[I]);const O=u.useCallback(z=>{x(q=>q.map(K=>{var _;if(K.type!==z)return K;const re={...K,enabled:!K.enabled};return(_=f.current)!=null&&_.isStarted&&(re.enabled?f.current.addEffect(z,re.intensity):f.current.removeEffect(z)),re}))},[]),E=u.useCallback((z,q)=>{x(K=>K.map(re=>{var _;return re.type!==z?re:(re.enabled&&((_=f.current)!=null&&_.isStarted)&&f.current.updateIntensity(z,q),{...re,intensity:q})}))},[]);u.useEffect(()=>{var z;(z=f.current)==null||z.setVolume(S/100)},[S]),u.useEffect(()=>{var z;(z=f.current)==null||z.setInputGain(k/100)},[k]),u.useEffect(()=>{var z;(z=f.current)==null||z.setMonitoring(v)},[v]);const V=u.useCallback(()=>{var z;(z=f.current)==null||z.clearAllEffects(),x(q=>q.map(K=>({...K,enabled:!1})))},[]),ee=m.filter(z=>z.enabled).length;return l==="hidden"?null:n.jsxs("div",{className:`nice-vocal-effects-rack${s?` ${s}`:""}`,style:{border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:r?12:20,background:"var(--nice-bg-secondary)",color:"var(--nice-text, inherit)",...i},id:o,"data-testid":c,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16,gap:8},children:[n.jsxs("h3",{style:{margin:0,fontSize:r?16:20,display:"flex",alignItems:"center",gap:8},children:[n.jsx(W.NtdMicrophone,{size:r?16:20})," ",h("vocalEffects.title","Vocal effects")]}),n.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[ee>0&&n.jsxs(Ce.NiceBadge,{variant:"primary",children:[ee," ",h("vocalEffects.active","active")]}),p?n.jsx(Ce.NiceButton,{variant:"danger",size:"sm",onClick:T,children:h("vocalEffects.stop","Stop")}):n.jsx(Ce.NiceButton,{variant:"primary",size:"sm",onClick:A,children:h("vocalEffects.start","Start mic")})]})]}),n.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[n.jsx(Ce.NiceToggle,{checked:v,onChange:g,label:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdVolume,{size:14})," ",h("vocalEffects.monitor","Monitor")]})}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.volume","Vol"),n.jsx("div",{style:{width:100},children:n.jsx(Ce.NiceSlider,{value:S,onChange:b,min:0,max:200})}),n.jsxs("span",{style:{minWidth:36,fontSize:12},children:[S,"%"]})]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[h("vocalEffects.gain","Gain"),n.jsx("div",{style:{width:100},children:n.jsx(Ce.NiceSlider,{value:k,onChange:j,min:0,max:300})}),n.jsxs("span",{style:{minWidth:36,fontSize:12},children:[k,"%"]})]}),p&&n.jsx("div",{style:{width:80,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Math.min(100,N*300)}%`,background:N>.5?"var(--nice-danger, #ef4444)":N>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})}),ee>0&&n.jsx(Ce.NiceButton,{variant:"ghost",size:"sm",onClick:V,children:h("vocalEffects.clearAll","Clear all")})]}),n.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${r?130:160}px, 1fr))`,gap:r?6:10},children:m.map(z=>n.jsxs("div",{style:{border:z.enabled?"2px solid var(--nice-accent, #3b82f6)":"1px solid var(--nice-border, #e2e8f0)",borderRadius:10,padding:r?"6px 8px":"10px 12px",background:z.enabled?"var(--nice-accent-tint-10, rgba(59,130,246,0.08))":"transparent",transition:"all 0.15s ease"},children:[n.jsxs("button",{type:"button",onClick:()=>O(z.type),style:{display:"flex",alignItems:"center",gap:6,width:"100%",marginBottom:z.enabled?6:0,background:"transparent",border:"none",cursor:"pointer",color:"inherit",textAlign:"left"},children:[(()=>{const q=km[z.icon]??W.NtdMusic;return n.jsx(q,{size:r?18:22})})(),n.jsx("span",{style:{fontSize:r?12:14,fontWeight:z.enabled?700:500,color:z.enabled?"var(--nice-accent, #3b82f6)":"inherit"},children:z.label})]}),z.enabled&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},onClick:q=>q.stopPropagation(),children:[n.jsx("div",{style:{flex:1},children:n.jsx(Ce.NiceSlider,{value:z.intensity,onChange:q=>E(z.type,q),min:0,max:100})}),n.jsx("span",{style:{fontSize:11,minWidth:24,color:"var(--nice-text-muted, #64748b)"},children:z.intensity})]})]},z.type))}),n.jsx("div",{style:{marginTop:12,fontSize:12,color:"var(--nice-text-muted, #94a3b8)",textAlign:"center"},children:h("vocalEffects.hint","Click effects to toggle. Multiple effects can be active at once — adjust intensity with the slider.")})]})},zl={algorithm:"pitchy",gain:1,rmsThreshold:.02,pitchThreshold:.6,smoothingWindow:3,hysteresisFrames:2,useHanning:!1,offsetMs:0},Cm=[{value:"pitchy",label:"Pitchy (fast)"},{value:"autocorrelation",label:"Autocorrelation"},{value:"librosa",label:"Librosa (server)"},{value:"crepe",label:"CREPE (AI, server)"}],jm=({deviceId:e,onDeviceChange:t,settings:r,onSettingsChange:a,audioInputs:s,algorithms:i=Cm,showLevelMeter:o=!0,onCalibrate:l,compact:c=!1,t:d})=>{const{t:h}=Te(),f=d??h,p=u.useMemo(()=>({...zl,...r}),[r]),y=A=>a==null?void 0:a({...p,...A}),[m,x]=u.useState([]);u.useEffect(()=>{var O,E,V;if(s||!((O=navigator.mediaDevices)!=null&&O.enumerateDevices))return;let A=!1;const T=()=>navigator.mediaDevices.enumerateDevices().then(ee=>!A&&x(ee.filter(z=>z.kind==="audioinput"))).catch(()=>{});return T(),(V=(E=navigator.mediaDevices).addEventListener)==null||V.call(E,"devicechange",T),()=>{var ee,z;A=!0,(z=(ee=navigator.mediaDevices).removeEventListener)==null||z.call(ee,"devicechange",T)}},[s]);const v=s??m,g=u.useMemo(()=>v.map((A,T)=>({value:A.deviceId,label:A.label||`${f("audioInput.microphone","Microphone")} ${T+1}`})),[v,f]),[S,b]=u.useState(!1),[k,j]=u.useState(0),N=u.useRef(null),R=()=>{const A=N.current;A&&(cancelAnimationFrame(A.raf),A.stream.getTracks().forEach(T=>T.stop()),A.ctx.close().catch(()=>{}),N.current=null),b(!1),j(0)},w=async()=>{try{const A=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e?{exact:e}:void 0}}),T=new AudioContext,O=T.createMediaStreamSource(A),E=T.createAnalyser();E.fftSize=1024,O.connect(E);const V=new Float32Array(E.fftSize),ee=()=>{E.getFloatTimeDomainData(V);let z=0;for(let q=0;q<V.length;q++)z+=V[q]*V[q];j(Math.sqrt(z/V.length)*(p.gain||1)),N.current.raf=requestAnimationFrame(ee)};N.current={ctx:T,stream:A,raf:requestAnimationFrame(ee)},b(!0)}catch{}};u.useEffect(()=>()=>R(),[]);const M={fontSize:12,fontWeight:600,color:"var(--nice-text-muted, #94a3b8)",marginBottom:4,display:"block"},I=(A,T,O)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[n.jsx("span",{style:{flex:"0 0 120px",fontSize:13},children:A}),n.jsx("div",{style:{flex:1},children:T}),n.jsx("span",{style:{flex:"0 0 48px",textAlign:"right",fontSize:12,color:"var(--nice-text-muted, #94a3b8)"},children:O})]});return n.jsxs("div",{className:"nice-audio-input-picker",style:{display:"flex",flexDirection:"column",gap:c?8:12,border:"1px solid var(--nice-border, #e2e8f0)",borderRadius:12,padding:c?12:16,color:"var(--nice-text, inherit)"},children:[n.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap"},children:[n.jsxs("div",{style:{flex:"1 1 220px",minWidth:180},children:[n.jsxs("label",{style:{...M,display:"inline-flex",alignItems:"center",gap:4},children:[n.jsx(W.NtdMicrophone,{size:13})," ",f("audioInput.device","Microphone")]}),n.jsx(Ce.NiceSelect,{options:g,value:e??"",onChange:A=>t==null?void 0:t(typeof A=="string"?A:A[0]),placeholder:f("audioInput.selectDevice","Select microphone"),size:"sm"})]}),n.jsxs("div",{style:{flex:"1 1 200px",minWidth:160},children:[n.jsx("label",{style:M,children:f("audioInput.algorithm","Pitch algorithm")}),n.jsx(Ce.NiceSelect,{options:i,value:p.algorithm,onChange:A=>y({algorithm:typeof A=="string"?A:A[0]}),size:"sm"})]})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[I(f("audioInput.gain","Gain"),n.jsx(Ce.NiceSlider,{value:Math.round(p.gain*100),onChange:A=>y({gain:A/100}),min:0,max:300}),`${Math.round(p.gain*100)}%`),I(f("audioInput.rmsThreshold","RMS gate"),n.jsx(Ce.NiceSlider,{value:Math.round(p.rmsThreshold*1e3),onChange:A=>y({rmsThreshold:A/1e3}),min:0,max:200}),p.rmsThreshold.toFixed(3)),I(f("audioInput.pitchThreshold","Pitch clarity"),n.jsx(Ce.NiceSlider,{value:Math.round(p.pitchThreshold*100),onChange:A=>y({pitchThreshold:A/100}),min:0,max:100}),p.pitchThreshold.toFixed(2)),!c&&I(f("audioInput.smoothing","Smoothing"),n.jsx(Ce.NiceSlider,{value:p.smoothingWindow,onChange:A=>y({smoothingWindow:A}),min:0,max:12}),`${p.smoothingWindow}`),!c&&I(f("audioInput.hysteresis","Hysteresis"),n.jsx(Ce.NiceSlider,{value:p.hysteresisFrames,onChange:A=>y({hysteresisFrames:A}),min:0,max:12}),`${p.hysteresisFrames}`),!c&&I(f("audioInput.offset","Latency"),n.jsx(Ce.NiceSlider,{value:p.offsetMs,onChange:A=>y({offsetMs:A}),min:-200,max:500}),`${p.offsetMs}ms`)]}),n.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"},children:[n.jsx(Ce.NiceToggle,{checked:p.useHanning,onChange:A=>y({useHanning:A}),label:f("audioInput.hanning","Hanning window")}),o&&n.jsxs(n.Fragment,{children:[n.jsx(Ce.NiceButton,{variant:S?"danger":"secondary",size:"sm",onClick:S?R:w,children:S?f("audioInput.stopTest","Stop test"):f("audioInput.testMic","Test mic")}),n.jsx("div",{style:{width:100,height:8,borderRadius:4,background:"var(--nice-bg-tertiary)",overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:`${Math.min(100,k*300)}%`,background:k>.5?"var(--nice-danger, #ef4444)":k>.2?"var(--nice-warning, #f59e0b)":"var(--nice-success, #4caf50)",transition:"width 0.05s"}})})]}),l&&e&&n.jsxs(Ce.NiceButton,{variant:"ghost",size:"sm",onClick:()=>l(e),children:[n.jsx(W.NtdSettings,{size:14})," ",f("audioInput.calibrate","Calibrate latency")]})]})]})};class _l{constructor(t,r){this.activeNotes=new Map,this.audioContext=t,this.masterGain=t.createGain(),this.masterGain.gain.value=.3,this.masterGain.connect(r)}applyCC(t,r,a){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,r=100,a=1,s="sine"){const i=this.midiToFreq(t),o=this.audioContext.createOscillator(),l=this.audioContext.createGain();o.type=s,o.frequency.value=i;const c=r/127*.8;l.gain.value=c,o.connect(l),l.connect(this.masterGain);const d=this.audioContext.currentTime;return l.gain.setValueAtTime(0,d),l.gain.linearRampToValueAtTime(c,d+.01),l.gain.exponentialRampToValueAtTime(c*.7,d+.1),l.gain.setValueAtTime(c*.7,d+a-.05),l.gain.exponentialRampToValueAtTime(.001,d+a),o.start(d),o.stop(d+a),o.onended=()=>{l.disconnect(),o.disconnect()},{osc:o,gain:l}}scheduleNote(t,r,a,s=100,i="sine"){const o=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=i,l.frequency.value=o;const d=s/127*.8;l.connect(c),c.connect(this.masterGain);const h=r;return c.gain.setValueAtTime(0,h),c.gain.linearRampToValueAtTime(d,h+.01),c.gain.exponentialRampToValueAtTime(d*.7,h+.1),c.gain.setValueAtTime(d*.7,h+a-.05),c.gain.exponentialRampToValueAtTime(.001,h+a),l.start(h),l.stop(h+a),l.onended=()=>{c.disconnect(),l.disconnect()},{osc:l,gain:c}}setVolume(t){this.masterGain.gain.value=Math.max(0,Math.min(1,t))}stopAll(){this.activeNotes.forEach(({osc:t,gain:r})=>{try{t.stop(),r.disconnect(),t.disconnect()}catch{}}),this.activeNotes.clear()}dispose(){this.stopAll(),this.masterGain.disconnect()}}const ki=ot.scoped("AudioPlaybackEngine");class Mm{constructor(){this.audioContext=null,this.masterGain=null,this.masterFilter=null,this.clips=new Map,this.scheduledSources=new Map,this.midiTracks=new Map,this.synths=new Map,this.isPlaying=!1,this.startTimeOffset=0,this.audioContextStartTime=0,this.currentTime=0,this.loopRegion={start:0,end:0,enabled:!1},this.bpm=120,this.duration=0,this.initAudioContext()}setMidiCCEvents(t,r){const a=this.midiTracks.get(t);a&&(a.ccEvents=r)}getMidiCCEvents(t){const r=this.midiTracks.get(t);return(r==null?void 0:r.ccEvents)||[]}addMidiCCEvent(t,r){const a=this.midiTracks.get(t);a&&(a.ccEvents||(a.ccEvents=[]),a.ccEvents.push(r))}removeMidiCCEvent(t,r){const a=this.midiTracks.get(t);a&&a.ccEvents&&(a.ccEvents=a.ccEvents.filter(s=>s.id!==r))}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.masterGain=this.audioContext.createGain(),this.masterFilter=this.audioContext.createBiquadFilter(),this.masterFilter.type="peaking",this.masterFilter.frequency.value=1200,this.masterFilter.Q.value=.7,this.masterFilter.gain.value=0,this.masterGain.connect(this.masterFilter),this.masterFilter.connect(this.audioContext.destination),this.masterGain.gain.value=.8,this.audioContext.state==="suspended"&&this.audioContext.resume()}catch(t){ki.error("Failed to initialize AudioContext:",t)}}createEffectNode(t){if(!this.audioContext||t.bypass)return null;try{switch(t.type){case"eq3":{const r=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter(),s=this.audioContext.createBiquadFilter();return r.type="lowshelf",r.frequency.value=t.params.lowFreq||250,r.gain.value=t.params.lowGain||0,a.type="peaking",a.frequency.value=1e3,a.Q.value=1,a.gain.value=t.params.midGain||0,s.type="highshelf",s.frequency.value=t.params.highFreq||4e3,s.gain.value=t.params.highGain||0,r.connect(a),a.connect(s),{input:r,output:s}}case"compressor":{const r=this.audioContext.createDynamicsCompressor();return r.threshold.value=t.params.threshold||-24,r.ratio.value=t.params.ratio||4,r.attack.value=t.params.attack||.003,r.release.value=t.params.release||.25,r.knee.value=t.params.knee||30,r}case"delay":{const r=this.audioContext.createDelay(5);r.delayTime.value=t.params.time||.25;const a=this.audioContext.createGain();a.gain.value=t.params.feedback||.3;const s=this.audioContext.createGain();s.gain.value=t.params.mix||.3;const i=this.audioContext.createGain();return i.gain.value=1-(t.params.mix||.3),r.connect(a),a.connect(r),r.connect(s),{input:r,output:s,dry:i,connect:function(o){s.connect(o),i.connect(o)}}}case"reverb":{const r=this.audioContext.createConvolver(),a=this.audioContext.sampleRate*(t.params.decay||2),s=this.audioContext.createBuffer(2,a,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=s.getChannelData(l);for(let d=0;d<a;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/a,2)}r.buffer=s;const i=this.audioContext.createGain();i.gain.value=t.params.mix||.3;const o=this.audioContext.createGain();return o.gain.value=1-(t.params.mix||.3),r.connect(i),{input:r,output:i,dry:o,connect:function(l){i.connect(l),o.connect(l)}}}case"distortion":{const r=this.audioContext.createWaveShaper(),a=t.params.amount||20,s=44100,i=new Float32Array(s),o=Math.PI/180;for(let d=0;d<s;d++){const h=d*2/s-1;i[d]=(3+a)*h*20*o/(Math.PI+a*Math.abs(h))}r.curve=i,r.oversample="4x";const l=this.audioContext.createGain();l.gain.value=t.params.mix||.5;const c=this.audioContext.createGain();return c.gain.value=1-(t.params.mix||.5),r.connect(l),{input:r,output:l,dry:c,connect:function(d){l.connect(d),c.connect(d)}}}default:return null}}catch(r){return ki.error("Failed to create effect node:",t.type,r),null}}addClip(t){this.clips.set(t.id,t),this.updateDuration()}removeClip(t){this.clips.delete(t),this.stopClip(t),this.updateDuration()}updateClip(t,r){const a=this.clips.get(t);a&&(Object.assign(a,r),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(r=>r.layerId===t)}setMidiTrack(t,r,a="sine",s=.5){if(this.midiTracks.set(t,{layerId:t,notes:r,instrument:a,volume:s}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const i=new _l(this.audioContext,this.masterGain);i.setVolume(s),this.synths.set(t,i)}}removeMidiTrack(t){this.midiTracks.delete(t);const r=this.synths.get(t);r&&(r.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,r){const a=this.midiTracks.get(t);a&&(a.volume=r);const s=this.synths.get(t);s&&s.setVolume(r)}updateDuration(){let t=0;this.clips.forEach(r=>{const a=r.startTime+r.duration;a>t&&(t=a)}),this.duration=t}play(){!this.audioContext||this.isPlaying||(this.audioContext.state==="suspended"&&this.audioContext.resume(),this.isPlaying=!0,this.audioContextStartTime=this.audioContext.currentTime,this.startTimeOffset=this.currentTime,this.scheduleClips(),this.scheduleMidiNotes(),this.startTimeTracking(),this.onPlayStateChange&&this.onPlayStateChange(!0))}pause(){this.isPlaying&&(this.isPlaying=!1,this.stopAllSources(),this.onPlayStateChange&&this.onPlayStateChange(!1))}stop(){this.pause(),this.seek(0)}seek(t){const r=this.isPlaying;r&&this.pause(),this.currentTime=Math.max(0,Math.min(t,this.duration)),this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),r&&this.play()}scheduleClips(){!this.audioContext||!this.masterGain||this.clips.forEach(t=>{if(t.startTime+t.duration<=this.currentTime)return;const a=this.audioContext.createBufferSource();a.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(a.playbackRate.value=1/t.stretchFactor);const s=this.audioContext.createGain();s.gain.value=t.volume;const i=this.audioContext.createStereoPanner();i.pan.value=t.pan,a.connect(s);let o=s;if(t.effectChain&&t.effectChain.length>0)for(const h of t.effectChain){const f=this.createEffectNode(h);if(f)if("input"in f&&"output"in f){const p=f;o.connect(p.input),o=p.output,"dry"in f&&s.connect(p.dry)}else o.connect(f),o=f}o.connect(i),i.connect(this.masterGain);const l=t.startTime,c=Math.max(0,this.currentTime-l),d=this.audioContext.currentTime+(l-this.currentTime);d>=this.audioContext.currentTime&&(a.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,a),a.onended=()=>{this.scheduledSources.delete(t.id)})})}stopClip(t){const r=this.scheduledSources.get(t);if(r){try{r.stop()}catch{}this.scheduledSources.delete(t)}}stopAllSources(){this.scheduledSources.forEach(t=>{try{t.stop()}catch{}}),this.scheduledSources.clear(),this.synths.forEach(t=>t.stopAll())}scheduleMidiNotes(){this.audioContext&&this.midiTracks.forEach(t=>{const r=this.synths.get(t.layerId);if(r&&(t.notes.forEach(a=>{if(a.start+a.duration<=this.currentTime)return;const i=Math.max(0,this.currentTime-a.start),o=this.audioContext.currentTime+(a.start-this.currentTime);o>=this.audioContext.currentTime&&r.scheduleNote(a.pitch,o,a.duration-i,a.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const a=[...t.ccEvents].sort((o,l)=>o.time-l.time);let i=a[0];for(let o=1;o<a.length;++o){const l=a[o],c=i.time,d=l.time,h=i.value,f=l.value,p=i.handleType||"linear",y=Math.max(2,Math.ceil((d-c)*20));for(let m=0;m<=y;++m){const x=m/y;let v=h;if(p==="linear")v=h+(f-h)*x;else if(p==="step")v=x<1?h:f;else if(p==="exp"){const k=Math.max(h/127,.001),j=Math.max(f/127,.001);v=k*Math.pow(j/k,x)*127}const g=c+(d-c)*x,S=this.audioContext.currentTime+(g-this.currentTime);S>=this.audioContext.currentTime&&typeof r.applyCC=="function"&&r.applyCC(l.cc,v,S)}i=l}}})}startTimeTracking(){if(!this.audioContext)return;const t=()=>{if(!this.isPlaying||!this.audioContext)return;const r=this.audioContext.currentTime-this.audioContextStartTime;if(this.currentTime=this.startTimeOffset+r,this.loopRegion.enabled&&this.currentTime>=this.loopRegion.end){this.seek(this.loopRegion.start);return}if(this.currentTime>=this.duration){this.stop();return}this.onTimeUpdate&&this.onTimeUpdate(this.currentTime),requestAnimationFrame(t)};requestAnimationFrame(t)}setLoopRegion(t,r,a){this.loopRegion={start:t,end:r,enabled:a}}setBPM(t){this.bpm=Math.max(20,Math.min(300,t))}getBPM(){return this.bpm}setMasterVolume(t){this.masterGain&&(this.masterGain.gain.value=Math.max(0,Math.min(1,t)))}setMasterFilter(t){this.masterFilter&&(t.type&&(this.masterFilter.type=t.type),t.frequency!=null&&(this.masterFilter.frequency.value=Math.max(20,Math.min(2e4,t.frequency))),t.q!=null&&(this.masterFilter.Q.value=Math.max(.1,Math.min(18,t.q))),t.gain!=null&&"gain"in this.masterFilter&&(this.masterFilter.gain.value=Math.max(-40,Math.min(40,t.gain))))}getCurrentTime(){return this.currentTime}getDuration(){return this.duration}getIsPlaying(){return this.isPlaying}setOnTimeUpdate(t){this.onTimeUpdate=t}setOnPlayStateChange(t){this.onPlayStateChange=t}dispose(){this.stop(),this.audioContext&&this.audioContext.close(),this.clips.clear()}}const Rm=[{name:"Grand Piano",waveform:"sawtooth",attack:.02,sustain:.7,release:1.2,eq:{C:2,D:1,E:1,F:0,G:0,A:-1,B:-2,C2:-3},category:"Keyboard"},{name:"Electric Piano",waveform:"triangle",attack:.03,sustain:.8,release:1,eq:{C:0,D:1,E:2,F:3,G:1,A:-1,B:-2,C2:-2},category:"Keyboard"},{name:"Harpsichord",waveform:"square",attack:.01,sustain:.5,release:.6,eq:{C:-1,D:-1,E:0,F:2,G:3,A:1,B:0,C2:-1},category:"Keyboard"},{name:"Violin",waveform:"triangle",attack:.3,sustain:1,release:1.5,eq:{C:3,D:2,E:2,F:1,G:-1,A:-2,B:-3,C2:-3},category:"String"},{name:"Acoustic Guitar",waveform:"sawtooth",attack:.2,sustain:.6,release:.9,eq:{C:-1,D:-2,E:0,F:1,G:3,A:2,B:0,C2:-2},category:"String"},{name:"Electric Guitar",waveform:"square",attack:.05,sustain:.7,release:1.2,eq:{C:-2,D:1,E:2,F:2,G:1,A:0,B:-1,C2:-3},category:"String"},{name:"Kick Drum",waveform:"sine",attack:.005,sustain:.1,release:.2,eq:{C:5,D:3,E:0,F:-3,G:-5,A:-7,B:-9,C2:-10},category:"Percussion"},{name:"Snare Drum",waveform:"triangle",attack:.01,sustain:.2,release:.3,eq:{C:-2,D:-1,E:1,F:2,G:3,A:2,B:0,C2:-2},category:"Percussion"},{name:"Hi-Hat",waveform:"square",attack:.002,sustain:.05,release:.1,eq:{C:-5,D:-3,E:0,F:2,G:5,A:7,B:9,C2:10},category:"Percussion"},{name:"Acoustic Bass",waveform:"sine",attack:.08,sustain:.8,release:1.2,eq:{C:4,D:3,E:2,F:1,G:0,A:-1,B:-2,C2:-3},category:"Bass"},{name:"Electric Bass",waveform:"square",attack:.05,sustain:.9,release:1.3,eq:{C:3,D:2,E:1,F:0,G:-1,A:-2,B:-3,C2:-4},category:"Bass"},{name:"Trumpet",waveform:"sawtooth",attack:.1,sustain:.9,release:1.5,eq:{C:2,D:3,E:4,F:5,G:3,A:1,B:-1,C2:-3},category:"Brass"},{name:"Trombone",waveform:"triangle",attack:.2,sustain:1,release:1.7,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-2,C2:-4},category:"Brass"},{name:"Saxophone",waveform:"sawtooth",attack:.15,sustain:.8,release:1.3,eq:{C:2,D:3,E:4,F:3,G:1,A:-1,B:-2,C2:-3},category:"Woodwind"},{name:"Clarinet",waveform:"triangle",attack:.18,sustain:.9,release:1.6,eq:{C:3,D:4,E:5,F:4,G:2,A:0,B:-1,C2:-2},category:"Woodwind"},{name:"Saw Synth",waveform:"sawtooth",attack:.05,sustain:.9,release:1.2,eq:{C:2,D:3,E:4,F:3,G:2,A:0,B:-1,C2:-2},category:"Synth"},{name:"Square Lead",waveform:"square",attack:.04,sustain:.85,release:1.1,eq:{C:2,D:3,E:4,F:3,G:1,A:0,B:-1,C2:-3},category:"Synth"}];function Ur(e={}){const{channelFilter:t,sysex:r=!1,onEvent:a,inputNameIncludes:s,onInputsChanged:i}=e,[o,l]=u.useState(null),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(null),y=u.useCallback((m,x)=>{const v=m.data??new Uint8Array(0),g=v[0]??0,S=v[1]??0,b=v[2]??0,k=m.timeStamp,j=g&240,N=g&15,R=x.id,w=x.name??"MIDI Input",M=t===void 0||t===N;if((j===144||j===128)&&M){const I=j===144&&b>0;return{type:I?"noteon":"noteoff",note:S,velocity:I?b:0,channel:N,ts:k,deviceId:R,deviceName:w}}return j===176&&M?{type:"cc",controller:S,value:b,channel:N,ts:k,deviceId:R,deviceName:w}:j===208&&M?{type:"aftertouch",pressure:S,channel:N,ts:k,deviceId:R,deviceName:w}:j===224&&M?{type:"pitchbend",value:(S|b<<7)-8192,channel:N,ts:k,deviceId:R,deviceName:w}:j===192&&M?{type:"program",program:S,channel:N,ts:k,deviceId:R,deviceName:w}:{type:"unknown",status:g,data1:S,data2:b,channel:N,ts:k,deviceId:R,deviceName:w}},[t]);return u.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let m=!1;return navigator.requestMIDIAccess({sysex:r}).then(x=>{if(m)return;p.current=x,d(!0);const v=()=>{const g=Array.from(x.inputs.values()),S=s?g.filter(b=>(b.name||"").toUpperCase().includes(s.toUpperCase())):g;f(S),i==null||i(S),g.forEach(b=>b.onmidimessage=null),S.forEach(b=>{b.onmidimessage=k=>a==null?void 0:a(y(k,b))})};v(),x.onstatechange=()=>v()}),()=>{m=!0;const x=p.current;x&&(x.inputs.forEach(v=>v.onmidimessage=null),x.onstatechange=null)}},[s,a,i,y,r]),{supported:o,granted:c,inputs:h}}const ds="nice2dev.midiLearn";function Nm(){try{const e=localStorage.getItem(ds);return e?JSON.parse(e):{}}catch{return{}}}function wi(e){const t={};for(const r of e)t[r.id]={id:r.id,type:r.type,number:r.number,channel:r.channel,min:r.min,max:r.max};localStorage.setItem(ds,JSON.stringify(t))}function Tm(e){const{parameters:t,onParameterChange:r}=e,[a,s]=u.useState(()=>{const b=Nm();return t.map(k=>{const j=b[k.id];return{id:k.id,paramName:k.name,type:(j==null?void 0:j.type)??"cc",number:j==null?void 0:j.number,channel:j==null?void 0:j.channel,min:(j==null?void 0:j.min)??k.min??0,max:(j==null?void 0:j.max)??k.max??127,value:0}})}),[i,o]=u.useState({learning:!1,targetId:null}),[l,c]=u.useState(null),d=u.useRef(a);d.current=a;const h=u.useRef(r);h.current=r;const f=u.useRef(i);f.current=i;const p=u.useCallback(b=>{var j;c(b);const k=f.current;if(k.learning&&k.targetId){if(!d.current.find(w=>w.id===k.targetId))return;let R={};switch(b.type){case"cc":R={type:"cc",number:b.controller,channel:b.channel};break;case"noteon":R={type:"note",number:b.note,channel:b.channel};break;case"pitchbend":R={type:"pitchbend",channel:b.channel};break;case"aftertouch":R={type:"aftertouch",channel:b.channel};break;default:return}s(w=>{const M=w.map(I=>I.id===k.targetId?{...I,...R}:I);return wi(M),M}),o({learning:!1,targetId:null});return}for(const N of d.current){if(N.number===void 0&&N.type!=="pitchbend"&&N.type!=="aftertouch"||N.channel!==void 0&&b.channel!==N.channel)continue;let R=null,w=127;if(N.type==="cc"&&b.type==="cc"&&b.controller===N.number?R=b.value:N.type==="note"&&b.type==="noteon"&&b.note===N.number?R=b.velocity:N.type==="pitchbend"&&b.type==="pitchbend"?(R=b.value+8192,w=16383):N.type==="aftertouch"&&b.type==="aftertouch"&&(R=b.pressure),R!==null){const M=R/w,I=N.min+M*(N.max-N.min);s(A=>A.map(T=>T.id===N.id?{...T,value:M}:T)),(j=h.current)==null||j.call(h,N.id,I,M)}}},[]),{supported:y,granted:m}=Ur({onEvent:p}),x=u.useCallback(b=>{o({learning:!0,targetId:b})},[]),v=u.useCallback(()=>{o({learning:!1,targetId:null})},[]),g=u.useCallback(b=>{s(k=>{const j=k.map(N=>N.id===b?{...N,type:"cc",number:void 0,channel:void 0}:N);return wi(j),j})},[]),S=u.useCallback(()=>{s(b=>{const k=b.map(j=>({...j,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(ds),k})},[]);return{bindings:a,startLearn:x,cancelLearn:v,removeBinding:g,clearAll:S,learnState:i,midiSupported:y,midiGranted:m,lastEvent:l}}const $m={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Pm(e={}){const{lowerZone:t=$m,onNoteExpression:r,onNoteOn:a,onNoteOff:s}=e,[i,o]=u.useState([]),l=u.useRef(new Map),c=u.useRef(r);c.current=r;const d=u.useRef(a);d.current=a;const h=u.useRef(s);h.current=s;const f=u.useRef(new Set(t.memberChannels));u.useEffect(()=>{f.current=new Set(t.memberChannels)},[t.memberChannels]);const p=u.useCallback(x=>{var g,S,b,k,j;if(!f.current.has(x.channel??-1))return;const v=`${x.channel}`;switch(x.type){case"noteon":{const N={note:x.note,channel:x.channel,velocity:x.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:x.ts};l.current.set(v,N),o(Array.from(l.current.values())),(g=d.current)==null||g.call(d,N);break}case"noteoff":{l.current.delete(v),o(Array.from(l.current.values())),(S=h.current)==null||S.call(h,x.channel,x.note);break}case"pitchbend":{const N=l.current.get(v);N&&(N.pitchBend=x.value,N.lastUpdate=x.ts,(b=c.current)==null||b.call(c,N),o(Array.from(l.current.values())));break}case"aftertouch":{const N=l.current.get(v);N&&(N.pressure=x.pressure,N.lastUpdate=x.ts,(k=c.current)==null||k.call(c,N),o(Array.from(l.current.values())));break}case"cc":{if(x.controller===74){const N=l.current.get(v);N&&(N.slide=x.value,N.lastUpdate=x.ts,(j=c.current)==null||j.call(c,N),o(Array.from(l.current.values())))}break}}},[]),{supported:y,granted:m}=Ur({onEvent:p,sysex:!1});return{activeNotes:i,midiSupported:y,midiGranted:m}}const Am={name:"M-Audio Oxygen 25 (MKIV)",deviceMatch:"OXYGEN",knobs:[{index:1,cc:21,label:"Knob 1"},{index:2,cc:22,label:"Knob 2"},{index:3,cc:23,label:"Knob 3"},{index:4,cc:24,label:"Knob 4"},{index:5,cc:25,label:"Knob 5"},{index:6,cc:26,label:"Knob 6"},{index:7,cc:27,label:"Knob 7"},{index:8,cc:28,label:"Knob 8"}],fader:{cc:7,label:"Fader (Channel Volume)"},pads:[{note:36,label:"Kick C1"},{note:38,label:"Snare D1"},{note:42,label:"HH Closed F#1"},{note:46,label:"HH Open A#1"},{note:48,label:"Tom1 C2"},{note:45,label:"Tom2 A1"},{note:43,label:"Floor G1"},{note:49,label:"Crash C#2"}],transport:{play:115,stop:114,record:117,rew:112,ff:113,loop:116}};function Em(e={},t=Am){const[r,a]=u.useState(()=>{const y=localStorage.getItem("oxygen25.layout");return y?JSON.parse(y):t}),[s,i]=u.useState([]),o=u.useRef({mode:"idle"}),l=u.useCallback(y=>{a(m=>{const x={...m,...y};return localStorage.setItem("oxygen25.layout",JSON.stringify(x)),x})},[]),c=u.useCallback(y=>{var v,g,S,b,k,j,N,R,w;const m=y.deviceName||"MIDI";i(M=>M.includes(m)?M:[...M,m]);const x=o.current;if(x.mode!=="idle"){if(x.mode==="knob"&&y.type==="cc"){const M=x.index;l({knobs:r.knobs.map(I=>I.index===M?{...I,cc:y.controller}:I)}),o.current={mode:"idle"};return}if(x.mode==="fader"&&y.type==="cc"){l({fader:{cc:y.controller,label:"Fader"}}),o.current={mode:"idle"};return}if(x.mode==="pad"&&y.type==="noteon"){const M=r.pads.slice();M[x.padIdx]={...M[x.padIdx],note:y.note},l({pads:M}),o.current={mode:"idle"};return}if(x.mode==="transport"&&y.type==="cc"){const M={...r.transport};M[x.action]=y.controller,l({transport:M}),o.current={mode:"idle"};return}}switch(y.type){case"noteon":{r.pads.findIndex(I=>I.note===y.note)>=0?(v=e.onPad)==null||v.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m}):(g=e.onKey)==null||g.call(e,{note:y.note,velocity:y.velocity,ts:y.ts,device:m});break}case"cc":{if(r.fader&&y.controller===r.fader.cc){(S=e.onFader)==null||S.call(e,{cc:y.controller,value:y.value,ts:y.ts,device:m});break}const M=r.knobs.find(A=>A.cc===y.controller);if(M){(b=e.onKnob)==null||b.call(e,{index:M.index,cc:y.controller,value:y.value,ts:y.ts,device:m});break}const I=Object.keys(r.transport).find(A=>r.transport[A]===y.controller);if(I){(k=e.onTransport)==null||k.call(e,{action:I,value:y.value,ts:y.ts,device:m});break}(j=e.onUnknown)==null||j.call(e,y);break}case"pitchbend":(N=e.onPitchBend)==null||N.call(e,{value:y.value,ts:y.ts,device:m});break;case"aftertouch":(R=e.onAftertouch)==null||R.call(e,{pressure:y.pressure,ts:y.ts,device:m});break;default:(w=e.onUnknown)==null||w.call(e,y)}},[l,e,r]),{supported:d,granted:h,inputs:f}=Ur({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:y=>i(y.map(m=>m.name||"MIDI"))}),p=u.useMemo(()=>({knob:y=>o.current={mode:"knob",index:y},fader:()=>o.current={mode:"fader"},pad:y=>o.current={mode:"pad",padIdx:y},transport:y=>o.current={mode:"transport",action:y},cancel:()=>o.current={mode:"idle"},state:()=>o.current}),[]);return{supported:d,granted:h,inputs:f,layout:r,setLayout:l,learn:p,inputsInfo:s}}const ka={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],mixolydian:[0,2,4,5,7,9,10],pentatonic:[0,2,4,7,9],minorPenta:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]},Im=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],wa={pop:[[0,4,7],[5,9,0],[7,11,2],[5,9,0]],rock:[[0,4,7],[5,9,0],[3,7,10],[5,9,0]],jazz:[[0,4,7,11],[2,5,9,0],[5,9,0,4],[0,4,7,11]],blues12:[[0,4,7],[0,4,7],[0,4,7],[0,4,7],[5,9,0],[5,9,0],[0,4,7],[0,4,7],[7,11,2],[5,9,0],[0,4,7],[7,11,2]]},en=36,jn=38,Nt=42,tn=51,Lm=49,Ca={basic:[{step:0,pitch:en,vel:110},{step:0,pitch:Nt,vel:80},{step:2,pitch:Nt,vel:70},{step:4,pitch:jn,vel:100},{step:4,pitch:Nt,vel:80},{step:6,pitch:Nt,vel:70},{step:8,pitch:en,vel:100},{step:10,pitch:Nt,vel:70},{step:12,pitch:jn,vel:100},{step:12,pitch:Nt,vel:80},{step:14,pitch:Nt,vel:70}],rock:[{step:0,pitch:en,vel:120},{step:0,pitch:Lm,vel:90},{step:4,pitch:jn,vel:110},{step:4,pitch:Nt,vel:80},{step:8,pitch:en,vel:110},{step:8,pitch:Nt,vel:80},{step:10,pitch:en,vel:90},{step:12,pitch:jn,vel:110},{step:12,pitch:Nt,vel:80}],swing:[{step:0,pitch:tn,vel:90},{step:3,pitch:tn,vel:70},{step:4,pitch:tn,vel:80},{step:8,pitch:tn,vel:90},{step:11,pitch:tn,vel:70},{step:12,pitch:tn,vel:80},{step:4,pitch:en,vel:80},{step:12,pitch:jn,vel:70}]},Fl={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function Dm(e){let t=e|0;return()=>{t=t+1831565813|0;let r=Math.imul(t^t>>>15,1|t);return r=r+Math.imul(r^r>>>7,61|r)^r,((r^r>>>14)>>>0)/4294967296}}let Ol=1;const lr=()=>Ol++,Bl=e=>60/e,zm=e=>Bl(e)/4;function aa(e,t,r,a){const s=t.length,i=Math.floor(r/s),o=(r%s+s)%s;return e+t[o]+(a+i)*12}function Gl(e=Fl){Ol=1;const t=e.seed>0?Dm(e.seed):Math.random,r=ka[e.scale]??ka.pentatonic,a=wa[e.progression]??wa.pop,s=Ca[e.drumPattern]??Ca.basic,i=Bl(e.tempo),o=zm(e.tempo),l=Math.max(1,e.bars),c=16,d=[],h=[],f=[],p=[];let y=0;for(let m=0;m<l;m++){const x=m*4*i,v=m%a.length,g=a[v];for(const b of g)f.push({id:lr(),pitch:aa(e.root,r,b,e.octave-1),start:x,duration:4*i-.01,velocity:70+Math.floor(t()*20)});const S=g[0];for(let b=0;b<4;b++){const k=b===2?S+(t()>.5?2:0):S;h.push({id:lr(),pitch:aa(e.root,r,k,e.octave-2),start:x+b*i,duration:i*.9,velocity:80+Math.floor(t()*30)})}for(let b=0;b<c;b++){if(t()>e.density)continue;const k=x+b*o,j=t()>.8?t()>.5?2:-2:t()>.5?1:-1;y=Math.max(-3,Math.min(r.length+3,y+j));const N=1+Math.floor(t()*3);d.push({id:lr(),pitch:aa(e.root,r,y,e.octave),start:k,duration:N*o*.95,velocity:85+Math.floor(t()*30)})}for(const b of s)p.push({id:lr(),pitch:b.pitch,start:x+b.step*o,duration:o*.8,velocity:b.vel+Math.floor(t()*10-5)})}return{melody:d,bass:h,chords:f,drums:p,config:e}}const _m=Object.keys(ka),Fm=Object.keys(wa),Om=Object.keys(Ca),Bm=Gl;function Ke(e,t,r){return{cc:e,paramId:r,label:`Knob ${t}`,controlType:"knob",min:0,max:127,inverted:!1}}function Vn(e,t,r){return{cc:e,paramId:r,label:t,controlType:"fader",min:0,max:127,inverted:!1}}function nn(e,t,r){return{cc:e,paramId:r,label:t,controlType:"button",min:0,max:127,inverted:!1}}const Wl={id:"oxygen25",name:"M-Audio Oxygen 25 (MkIV)",deviceMatch:"OXYGEN",mappings:[Ke(21,1,"mixer.volume"),Ke(22,2,"mixer.pan"),Ke(23,3,"fx.reverb"),Ke(24,4,"fx.delay"),Ke(25,5,"fx.chorus"),Ke(26,6,"fx.filter"),Ke(27,7,"fx.drive"),Ke(28,8,"fx.eq"),Vn(7,"Master Fader","mixer.master"),nn(115,"Play","transport.play"),nn(114,"Stop","transport.stop"),nn(117,"Record","transport.record"),nn(112,"Rewind","transport.rewind"),nn(113,"Forward","transport.forward"),nn(116,"Loop","transport.loop")]},Ul={id:"mpk-mini",name:"Akai MPK Mini",deviceMatch:"MPK",mappings:[Ke(1,1,"mixer.volume"),Ke(2,2,"mixer.pan"),Ke(3,3,"fx.reverb"),Ke(4,4,"fx.delay"),Ke(5,5,"fx.chorus"),Ke(6,6,"fx.filter"),Ke(7,7,"fx.drive"),Ke(8,8,"fx.eq")]},ql={id:"minilab",name:"Arturia MiniLab",deviceMatch:"Arturia MiniLab",mappings:[Ke(7,1,"mixer.volume"),Ke(74,2,"mixer.pan"),Ke(71,3,"fx.reverb"),Ke(76,4,"fx.delay"),Ke(77,5,"fx.chorus"),Ke(93,6,"fx.filter"),Ke(73,7,"fx.drive"),Ke(75,8,"fx.eq"),Vn(1,"Mod Wheel","mixer.master")]},Vl={id:"launch-control-xl",name:"Novation Launch Control XL",deviceMatch:"Launch Control",mappings:[...Array.from({length:8},(e,t)=>Ke(13+t,t+1,`mixer.send${t+1}`)),...Array.from({length:8},(e,t)=>Vn(77+t,`Fader ${t+1}`,`mixer.track${t+1}`))]},us={id:"generic",name:"Generic MIDI Controller",deviceMatch:"",mappings:[Ke(1,1,"mixer.modWheel"),Vn(7,"Volume","mixer.volume"),Ke(10,2,"mixer.pan"),Vn(11,"Expression","mixer.expression")]},Hl=[Wl,Ul,ql,Vl,us];class Gm{constructor(t){this.ccMap=new Map,this.onChange=null,this.profile=t??us,this.rebuildMap()}setProfile(t){this.profile=t,this.rebuildMap()}getProfile(){return this.profile}autoDetect(t){const r=t.toUpperCase(),a=Hl.find(s=>s.deviceMatch&&r.includes(s.deviceMatch.toUpperCase()));return a?(this.setProfile(a),a):null}onMappedChange(t){this.onChange=t}handleCC(t,r){var c;const a=this.ccMap.get(t);if(!a)return null;const i=(a.inverted?127-r:r)/127,o=a.min+i*(a.max-a.min),l={paramId:a.paramId,label:a.label,rawValue:r,scaledValue:o,normalizedValue:i};return(c=this.onChange)==null||c.call(this,l),l}setMapping(t,r,a,s="knob"){const i={cc:t,paramId:r,label:a,controlType:s,min:0,max:127,inverted:!1},o=this.profile.mappings.findIndex(l=>l.cc===t);o>=0?this.profile.mappings[o]=i:this.profile.mappings.push(i),this.ccMap.set(t,i)}removeMapping(t){this.profile.mappings=this.profile.mappings.filter(r=>r.cc!==t),this.ccMap.delete(t)}getMappings(){return[...this.profile.mappings]}getMapping(t){return this.ccMap.get(t)}exportConfig(){return{...this.profile,mappings:this.profile.mappings.map(t=>({...t}))}}importConfig(t){this.profile={...t,mappings:t.mappings.map(r=>({...r}))},this.rebuildMap()}static createCustomProfile(t,r){return{id:`custom-${t.toLowerCase().replace(/\s+/g,"-")}`,name:t,deviceMatch:"",mappings:r.map(a=>({...a,min:0,max:127,inverted:!1}))}}rebuildMap(){this.ccMap.clear();for(const t of this.profile.mappings)this.ccMap.set(t.cc,t)}}function Kl(e){return{past:[],present:e,future:[]}}function Yl(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function Xl(e){if(e.past.length===0)return e;const t=e.past[e.past.length-1];return{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future]}}function Zl(e){if(e.future.length===0)return e;const t=e.future[0];return{past:[...e.past,e.present],present:t,future:e.future.slice(1)}}function Ql(e){return e.past.length>0}function Jl(e){return e.future.length>0}function ja(e,t){return e.filter(r=>r.time>=t.start&&r.time<=t.end).map(r=>({...r}))}function ec(e,t,r){if(t.length===0)return e;const a=Math.min(...t.map(o=>o.time)),s=r-a,i=t.map(o=>({...o,id:Date.now()+Math.floor(Math.random()*1e4)+o.id,time:o.time+s}));return[...e,...i]}function tc(e,t){const r=[],a=[];for(const s of e)s.time>=t.start&&s.time<=t.end?r.push({...s}):a.push(s);return{remaining:a,cut:r}}function nc(e,t){return e.filter(r=>r.time<t.start||r.time>t.end)}function Wm(e,t){return e.filter(r=>r.time>=t.start&&r.time<=t.end).map(r=>r.id)}function rc(e,t,r,a){const s={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:r,time:a};return[...e,s]}function ac(e,t=3){if(e.length<=2)return e;const r=[...e].sort((s,i)=>s.time-i.time),a=[r[0]];for(let s=1;s<r.length-1;s++)s%t===0&&a.push(r[s]);return a.push(r[r.length-1]),a}function sc(e){return JSON.stringify(e,null,2)}function ic(e){try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&"id"in r&&"cc"in r&&"value"in r&&"time"in r):[]}catch{return[]}}function bt(e,t){var r;return((r=e.find(a=>a.layerId===t))==null?void 0:r.events)??[]}function Tt(e,t,r){return e.find(s=>s.layerId===t)?e.map(s=>s.layerId===t?{...s,events:r}:s):[...e,{layerId:t,events:r}]}function Um(e,t){switch(t.type){case"UNDO":return Xl(e);case"REDO":return Zl(e);default:{let r=e.present;switch(t.type){case"ADD_EVENT":{const a=[...bt(r,t.layerId),t.event];r=Tt(r,t.layerId,a);break}case"UPDATE_EVENT":{const a=bt(r,t.layerId).map(s=>s.id===t.id?{...s,value:t.value,time:t.time,handleType:t.handleType??s.handleType}:s);r=Tt(r,t.layerId,a);break}case"REMOVE_EVENT":{const a=bt(r,t.layerId).filter(s=>s.id!==t.id);r=Tt(r,t.layerId,a);break}case"SET_EVENTS":r=Tt(r,t.layerId,t.events);break;case"PASTE":{const a=bt(r,t.layerId),s=ec(a,t.clipboard,t.targetTime);r=Tt(r,t.layerId,s);break}case"CUT":{const a=bt(r,t.layerId),{remaining:s}=tc(a,t.range);r=Tt(r,t.layerId,s);break}case"DELETE_RANGE":{const a=bt(r,t.layerId),s=nc(a,t.range);r=Tt(r,t.layerId,s);break}case"RECORD":{const a=bt(r,t.layerId),s=rc(a,t.cc,t.value,t.time);r=Tt(r,t.layerId,s);break}case"THIN":{const a=bt(r,t.layerId),s=ac(a,t.keepEveryN);r=Tt(r,t.layerId,s);break}case"IMPORT":{const a=ic(t.json);a.length>0&&(r=Tt(r,t.layerId,a));break}}return Yl(e,r)}}}function qm(e=[]){const[t,r]=u.useReducer(Um,Kl(e)),a=u.useRef([]),s=u.useCallback(b=>bt(t.present,b),[t.present]),i=u.useCallback((b,k)=>r({type:"ADD_EVENT",layerId:b,event:k}),[]),o=u.useCallback((b,k,j,N,R)=>r({type:"UPDATE_EVENT",layerId:b,id:k,value:j,time:N,handleType:R}),[]),l=u.useCallback((b,k)=>r({type:"REMOVE_EVENT",layerId:b,id:k}),[]),c=u.useCallback((b,k)=>r({type:"SET_EVENTS",layerId:b,events:k}),[]),d=u.useCallback(()=>r({type:"UNDO"}),[]),h=u.useCallback(()=>r({type:"REDO"}),[]),f=u.useCallback((b,k)=>{a.current=ja(bt(t.present,b),k)},[t.present]),p=u.useCallback((b,k)=>{a.current=ja(bt(t.present,b),k),r({type:"CUT",layerId:b,range:k})},[t.present]),y=u.useCallback((b,k)=>{a.current.length>0&&r({type:"PASTE",layerId:b,clipboard:a.current,targetTime:k})},[]),m=u.useCallback((b,k)=>r({type:"DELETE_RANGE",layerId:b,range:k}),[]),x=u.useCallback((b,k,j,N)=>r({type:"RECORD",layerId:b,cc:k,value:j,time:N}),[]),v=u.useCallback((b,k)=>r({type:"THIN",layerId:b,keepEveryN:k}),[]),g=u.useCallback(b=>sc(bt(t.present,b)),[t.present]),S=u.useCallback((b,k)=>r({type:"IMPORT",layerId:b,json:k}),[]);return{snapshots:t.present,getEvents:s,addEvent:i,updateEvent:o,removeEvent:l,setEvents:c,undo:d,redo:h,canUndo:Ql(t),canRedo:Jl(t),copy:f,cut:p,paste:y,clipboard:a.current,deleteRange:m,record:x,thin:v,exportLane:g,importLane:S}}function hs(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function Yt(e="New Pattern",t=16,r=120){return{name:e,length:t,steps:Array.from({length:t},()=>hs()),bpm:r,swing:0,rootNote:60}}function oc(e,t){const r=e.steps.map((a,s)=>s===t?{...a,active:!a.active}:a);return{...e,steps:r}}function lc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,note:Math.max(0,Math.min(127,r))}:s);return{...e,steps:a}}function cc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,velocity:Math.max(0,Math.min(127,r))}:s);return{...e,steps:a}}function dc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,gate:Math.max(0,Math.min(1,r))}:s);return{...e,steps:a}}function uc(e,t,r){const a=e.steps.map((s,i)=>i===t?{...s,probability:Math.max(0,Math.min(1,r))}:s);return{...e,steps:a}}function hc(e,t){const r=e.steps.map((a,s)=>s===t?{...a,slide:!a.slide}:a);return{...e,steps:r}}function pc(e,t){const r=e.steps.map(a=>a.active?{...a,note:Math.max(0,Math.min(127,a.note+t))}:a);return{...e,steps:r,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function fc(e){return{...e,steps:[...e.steps].reverse()}}function mc(e,t){const r=e.steps.length,a=(t%r+r)%r,s=[...e.steps.slice(a),...e.steps.slice(0,a)];return{...e,steps:s}}function gc(e,t=60,r=127){const a=e.steps.map(s=>s.active?{...s,velocity:Math.floor(t+Math.random()*(r-t+1))}:s);return{...e,steps:a}}function yc(e){return{...e,steps:e.steps.map(()=>hs(e.rootNote))}}function ps(e,t=4){return 60/e/t}function bc(e,t,r=0,a=4){const s=ps(t,a),i=e*s;return e%2===1&&r>0?i+s*r*.5:i}function vc(e){return e.active&&Math.random()<e.probability}function Vm(){const e=Yt("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function Hm(){const e=Yt("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function Km(){const e=Yt("Hi-Hat",16);for(let t=0;t<16;t+=2)e.steps[t]={...e.steps[t],active:!0,note:42,velocity:80};return e}function Ym(e=60){const t=Yt("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!0,note:e+a,velocity:90,gate:.5}}),{...t,rootNote:e}}function Xm(e=36){const t=Yt("Bassline",16,120),r=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],a=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return r.forEach((s,i)=>{t.steps[i]={...t.steps[i],active:!!a[i],note:e+s,velocity:100,gate:.7}}),{...t,rootNote:e}}function Zm(e){return JSON.stringify(e,null,2)}function Qm(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Jm(e={}){const{onTrigger:t,onLFOOutput:r,initialPattern:a}=e,[s,i]=u.useState(()=>a??Yt()),[o,l]=u.useState(-1),[c,d]=u.useState(!1),[h,f]=u.useState([]),p=u.useRef(s);p.current=s;const y=u.useRef(h);y.current=h;const m=u.useRef(c);m.current=c;const x=u.useRef(t);x.current=t;const v=u.useRef(r);v.current=r;const g=u.useRef(null),S=u.useRef(0),b=u.useRef(0),k=u.useCallback(()=>{var H,X;if(!m.current)return;const F=p.current,D=S.current%F.length,C=F.steps[D];if(vc(C)){const oe=bc(S.current,F.bpm,F.swing);(H=x.current)==null||H.call(x,C,D,oe)}const L=(Date.now()-b.current)/1e3;for(let oe=0;oe<y.current.length;oe++){const le=y.current[oe];if(le.enabled&&le.targetCC!==void 0){const ne=Ia(le,L,F.bpm);(X=v.current)==null||X.call(v,oe,le.targetCC,ne)}}l(D),S.current++;const B=ps(F.bpm)*1e3,G=D%2===0?0:B*F.swing*.5;g.current=setTimeout(k,B+G)},[]),j=u.useCallback(()=>{m.current||(S.current=0,b.current=Date.now(),d(!0),m.current=!0,k())},[k]),N=u.useCallback(()=>{d(!1),m.current=!1,l(-1),g.current&&(clearTimeout(g.current),g.current=null)},[]),R=u.useCallback(()=>{m.current?N():j()},[j,N]);u.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const w=u.useCallback(F=>i(D=>oc(D,F)),[]),M=u.useCallback((F,D)=>i(C=>lc(C,F,D)),[]),I=u.useCallback((F,D)=>i(C=>cc(C,F,D)),[]),A=u.useCallback((F,D)=>i(C=>dc(C,F,D)),[]),T=u.useCallback((F,D)=>i(C=>uc(C,F,D)),[]),O=u.useCallback(F=>i(D=>hc(D,F)),[]),E=u.useCallback(F=>i(D=>pc(D,F)),[]),V=u.useCallback(()=>i(F=>fc(F)),[]),ee=u.useCallback(F=>i(D=>mc(D,F)),[]),z=u.useCallback((F,D)=>i(C=>gc(C,F,D)),[]),q=u.useCallback(()=>i(F=>yc(F)),[]),K=u.useCallback(F=>i(D=>({...D,bpm:Math.max(20,Math.min(300,F))})),[]),re=u.useCallback(F=>i(D=>({...D,swing:Math.max(0,Math.min(1,F))})),[]),_=u.useCallback(F=>{i(D=>{if(D.length===F)return D;const C=Array.from({length:F},(L,B)=>B<D.steps.length?D.steps[B]:{active:!1,note:D.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{...D,length:F,steps:C}})},[]),U=u.useCallback(F=>{f(D=>[...D,F??Dr()])},[]),$=u.useCallback(F=>{f(D=>D.filter((C,L)=>L!==F))},[]),P=u.useCallback((F,D)=>{f(C=>C.map((L,B)=>B===F?{...L,...D}:L))},[]);return{pattern:s,currentStep:o,playing:c,lfos:h,play:j,stop:N,togglePlayback:R,toggle:w,setNote:M,setVelocity:I,setGate:A,setProbability:T,toggleSlide:O,transpose:E,reverse:V,shift:ee,randomizeVel:z,clear:q,setPattern:i,setBpm:K,setSwing:re,setLength:_,addLFO:U,removeLFO:$,updateLFO:P}}function fs(e){const t=u.useRef(null),r=u.useRef(new Map),a=u.useRef(1),s=u.useCallback(()=>{if(!t.current){const o=e();o.onmessage=l=>{const{id:c}=l.data,d=r.current.get(c);d&&(r.current.delete(c),d.resolve(l.data))},o.onerror=l=>{console.error("[useWorker] Worker error:",l.message);for(const[c,d]of r.current)d.reject(new Error(`Worker error: ${l.message}`));r.current.clear(),o.terminate(),t.current=null},t.current=o}return t.current},[e]);return u.useEffect(()=>{const o=r.current;return()=>{var l;(l=t.current)==null||l.terminate(),t.current=null;for(const[,c]of o)c.reject(new Error("Worker terminated on unmount"));o.clear()}},[]),u.useCallback((o,l)=>{const c=a.current++,d=s();return new Promise((h,f)=>{r.current.set(c,{resolve:h,reject:f}),d.postMessage({...o,id:c},l??[])})},[s])}function e0(){const e=fs(u.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(r,a,s=.01)=>(await e({buffer:r,sampleRate:a,rmsThreshold:s})).hz,[e])}function t0(){const e=fs(u.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:xt&&xt.tagName.toUpperCase()==="SCRIPT"&&xt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return u.useCallback(async(r,a,s)=>(await e({notes:r,points:a,params:s})).result,[e])}const n0={fftSize:2048,smoothingTimeConstant:.8,enablePitchDetection:!0,enableBeatDetection:!0,enableLevelMeter:!0,beatThreshold:.15};function xc(){return`
71
71
  /**
72
72
  * NiceAudioProcessor — Main audio analysis processor.
73
73
  */
@@ -403,7 +403,7 @@ registerProcessor('nice-audio-processor', NiceAudioProcessor);
403
403
  registerProcessor('nice-gain-processor', NiceGainProcessor);
404
404
  registerProcessor('nice-compressor-processor', NiceCompressorProcessor);
405
405
  registerProcessor('nice-vocoder-processor', NiceVocoderProcessor);
406
- `}let ji=!1,or=null;async function bc(e){if(!ji)return or||(or=(async()=>{const t=yc(),n=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(n);try{await e.audioWorklet.addModule(a),ji=!0}finally{URL.revokeObjectURL(a)}})(),or)}function xc(e,t,n){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...Ym,...t}});return n&&(a.port.onmessage=s=>{s.data.type==="analysis"&&n(s.data.payload)}),a}function vc(e,t=1){const n=new AudioWorkletNode(e,"nice-gain-processor");return n.parameters.get("gain").value=t,n}function Sc(e,t){const n=new AudioWorkletNode(e,"nice-compressor-processor");return(t==null?void 0:t.threshold)!==void 0&&(n.parameters.get("threshold").value=t.threshold),(t==null?void 0:t.ratio)!==void 0&&(n.parameters.get("ratio").value=t.ratio),(t==null?void 0:t.attack)!==void 0&&(n.parameters.get("attack").value=t.attack),(t==null?void 0:t.release)!==void 0&&(n.parameters.get("release").value=t.release),(t==null?void 0:t.makeupGain)!==void 0&&(n.parameters.get("makeupGain").value=t.makeupGain),n}function kc(e,t){const n=new AudioWorkletNode(e,"nice-vocoder-processor");return(t==null?void 0:t.pitchShift)!==void 0&&(n.parameters.get("pitchShift").value=t.pitchShift),(t==null?void 0:t.formantShift)!==void 0&&(n.parameters.get("formantShift").value=t.formantShift),(t==null?void 0:t.mix)!==void 0&&(n.parameters.get("mix").value=t.mix),n}function Zm(e={}){const{enableAnalysis:t=!0,analysisOptions:n,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:u}=e,[h,p]=d.useState(!1),[f,y]=d.useState(null),[m,v]=d.useState(null),x=d.useRef(null),g=d.useRef(null),k=d.useRef(null),b=d.useRef(null),S=d.useRef(null),M=d.useRef(null),R=d.useRef(null),N=d.useRef(null);d.useEffect(()=>{let L=!0;return(async()=>{try{const Z=new AudioContext;if(x.current=Z,await bc(Z),!L){Z.close();return}const A=[];if(t){const q=xc(Z,n,H=>{L&&(v(H),u==null||u(H))});g.current=q,A.push(q)}if(a){const q=vc(Z,s);k.current=q,A.push(q)}if(i){const q=Sc(Z,o);b.current=q,A.push(q)}if(l){const q=kc(Z,c);S.current=q,A.push(q)}if(A.length>0){R.current=A[0],N.current=A[A.length-1];for(let q=0;q<A.length-1;q++)A[q].connect(A[q+1])}p(!0)}catch(Z){L&&y(Z)}})(),()=>{var Z,A,q,H,re;L=!1,(Z=g.current)==null||Z.disconnect(),(A=k.current)==null||A.disconnect(),(q=b.current)==null||q.disconnect(),(H=S.current)==null||H.disconnect(),(re=x.current)==null||re.close()}},[t,a,i,l]);const C=d.useCallback(L=>{M.current&&M.current.disconnect(),M.current=L,R.current&&L.connect(R.current)},[]),w=d.useCallback(()=>{M.current&&(M.current.disconnect(),M.current=null)},[]),O=d.useCallback(()=>N.current,[]),$=d.useCallback(L=>{var Z;const U=(Z=k.current)==null?void 0:Z.parameters.get("gain");U&&(U.value=Math.max(0,Math.min(2,L)))},[]),E=d.useCallback((L,U)=>{var A;const Z=(A=b.current)==null?void 0:A.parameters.get(L);Z&&(Z.value=U)},[]),_=d.useCallback((L,U)=>{var A;const Z=(A=S.current)==null?void 0:A.parameters.get(L);Z&&(Z.value=U)},[]);return{isReady:h,error:f,analysis:m,connectSource:C,disconnectSource:w,getOutputNode:O,setGain:$,setCompressorParam:E,setVocoderParam:_,audioContext:x.current}}function Xm(e,t,n){const i={id:`${t}-${n}-${Date.now()}`,type:n,bypass:!1,params:{eq3:{lowGain:0,midGain:0,highGain:0,lowFreq:250,highFreq:4e3},compressor:{threshold:-24,ratio:4,attack:.003,release:.25,knee:30},delay:{time:.25,feedback:.3,mix:.3},reverb:{decay:2,mix:.3},distortion:{amount:20,mix:.5}}[n]};e(o=>{var l;return{...o,[t]:{...o[t],effectChain:[...((l=o[t])==null?void 0:l.effectChain)||[],i]}}})}function Qm(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.filter(o=>o.id!==n))||[]}}})}function Jm(e,t,n){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.map(o=>o.id===n?{...o,bypass:!o.bypass}:o))||[]}}})}function e0(e,t,n,a){e(s=>{var i,o;return{...s,[t]:{...s[t],effectChain:((o=(i=s[t])==null?void 0:i.effectChain)==null?void 0:o.map(l=>l.id===n?{...l,params:{...l.params,...a}}:l))||[]}}})}function t0(e,t,n,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(u=>({...u,[a]:[...u[a]||[],c]})),n({layerId:a,noteId:c.id})}function n0(e,t,n,a){e(s=>({...s,[n]:(s[n]||[]).filter(i=>i.id!==a)})),t(null)}function r0(e,t,n){e(a=>({...a,[n]:[]})),t(null)}function a0(e,t,n){e(a=>({...a,[t]:n}))}function s0(e,t,n,a,s){const i={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:a,time:s};e(o=>({...o,[t]:[...o[t]||[],i]}))}function i0(e,t,n,a,s,i){e(o=>({...o,[t]:(o[t]||[]).map(l=>l.id===n?{...l,value:a,time:s,handleType:i??l.handleType}:l)}))}function o0(e,t,n){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==n)}))}function lr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function l0(e){if(e.length===0)return[];const t=[];let n=e[0];for(let a=1;a<e.length;a++){const s=e[a];s.pitch===n.pitch&&Math.abs(s.freq-n.freq)<1?n.duration+=s.duration:(t.push(n),n=s)}return t.push(n),t}function c0(e,t,n=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<n)return 0;let l=1;for(let c=50;c<a;c++){let u=0;for(let h=0;h<a;h++)u+=Math.abs(e[h]-e[h+c]);u=1-u/a,u>i&&u>.9&&u>l&&(i=u,s=c),l=u}return s===-1?0:t/s}async function d0(e,t,n){const{signal:a,onProgress:s,rmsThreshold:i,useHanning:o,postPitch:l,postLibrosaPitchTrack:c}=n||{},u=await e.arrayBuffer();if(a!=null&&a.aborted)throw new Error("aborted");const p=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(u),f=p.getChannelData(0),y=p.sampleRate,m=Math.floor(y*.1),v=m,x=[];if(t==="pitchy"){const g=ra.PitchDetector.forFloat32Array(m),k=Math.max(1,Math.floor((f.length-m)/v));let b=0;for(let S=0;S<f.length-m;S+=v){if(a!=null&&a.aborted)throw new Error("aborted");const M=f.slice(S,S+m);if(o)for(let $=0;$<M.length;$++)M[$]*=.5*(1-Math.cos(2*Math.PI*$/(M.length-1)));const[R,N]=g.findPitch(M,y),C=lr(R);let w=0;for(let $=0;$<M.length;$++)w+=M[$]*M[$];w=Math.sqrt(w/M.length);const O=typeof i=="number"?i:.01;C&&R>50&&R<2e3&&N>.7&&w>O&&x.push({start:S/y,duration:m/y,pitch:C,freq:R}),b++,s&&s(b/k)}}else if(t==="crepe"){if(s&&s(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const g=await l(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(g.track)?g.track:[];k.length>0&&k.forEach((b,S)=>{var R;const M=lr(b.hz);if(M&&b.hz>50&&b.hz<2e3){const N=((R=k[S+1])==null?void 0:R.t)??b.t+.1;x.push({start:b.t,duration:S<k.length-1?N-b.t:.1,pitch:M,freq:b.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const g=Math.max(1,Math.floor((f.length-m)/v));let k=0;for(let b=0;b<f.length-m;b+=v){if(a!=null&&a.aborted)throw new Error("aborted");const S=f.slice(b,b+m);if(o)for(let C=0;C<S.length;C++)S[C]*=.5*(1-Math.cos(2*Math.PI*C/(S.length-1)));const R=c0(S,y,typeof i=="number"?i:.01),N=lr(R);N&&R>50&&R<2e3&&x.push({start:b/y,duration:m/y,pitch:N,freq:R}),k++,s&&s(k/g)}}if(t==="librosa"){if(s&&s(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const g=await c(e);if(a!=null&&a.aborted)throw new Error("aborted");const k=Array.isArray(g.track)?g.track:[];k.length>0&&k.forEach((b,S)=>{var R;const M=lr(b.hz);if(M&&b.hz>50&&b.hz<2e3){const N=((R=k[S+1])==null?void 0:R.t)??b.t+.1;x.push({start:b.t,duration:S<k.length-1?N-b.t:.1,pitch:M,freq:b.hz})}}),s&&s(1)}return l0(x)}function u0(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
406
+ `}let Ci=!1,cr=null;async function Sc(e){if(!Ci)return cr||(cr=(async()=>{const t=xc(),r=new Blob([t],{type:"application/javascript"}),a=URL.createObjectURL(r);try{await e.audioWorklet.addModule(a),Ci=!0}finally{URL.revokeObjectURL(a)}})(),cr)}function kc(e,t,r){const a=new AudioWorkletNode(e,"nice-audio-processor",{processorOptions:{...n0,...t}});return r&&(a.port.onmessage=s=>{s.data.type==="analysis"&&r(s.data.payload)}),a}function wc(e,t=1){const r=new AudioWorkletNode(e,"nice-gain-processor");return r.parameters.get("gain").value=t,r}function Cc(e,t){const r=new AudioWorkletNode(e,"nice-compressor-processor");return(t==null?void 0:t.threshold)!==void 0&&(r.parameters.get("threshold").value=t.threshold),(t==null?void 0:t.ratio)!==void 0&&(r.parameters.get("ratio").value=t.ratio),(t==null?void 0:t.attack)!==void 0&&(r.parameters.get("attack").value=t.attack),(t==null?void 0:t.release)!==void 0&&(r.parameters.get("release").value=t.release),(t==null?void 0:t.makeupGain)!==void 0&&(r.parameters.get("makeupGain").value=t.makeupGain),r}function jc(e,t){const r=new AudioWorkletNode(e,"nice-vocoder-processor");return(t==null?void 0:t.pitchShift)!==void 0&&(r.parameters.get("pitchShift").value=t.pitchShift),(t==null?void 0:t.formantShift)!==void 0&&(r.parameters.get("formantShift").value=t.formantShift),(t==null?void 0:t.mix)!==void 0&&(r.parameters.get("mix").value=t.mix),r}function r0(e={}){const{enableAnalysis:t=!0,analysisOptions:r,enableGain:a=!1,initialGain:s=1,enableCompressor:i=!1,compressorOptions:o,enableVocoder:l=!1,vocoderOptions:c,onAnalysis:d}=e,[h,f]=u.useState(!1),[p,y]=u.useState(null),[m,x]=u.useState(null),v=u.useRef(null),g=u.useRef(null),S=u.useRef(null),b=u.useRef(null),k=u.useRef(null),j=u.useRef(null),N=u.useRef(null),R=u.useRef(null);u.useEffect(()=>{let E=!0;return(async()=>{try{const ee=new AudioContext;if(v.current=ee,await Sc(ee),!E){ee.close();return}const z=[];if(t){const q=kc(ee,r,K=>{E&&(x(K),d==null||d(K))});g.current=q,z.push(q)}if(a){const q=wc(ee,s);S.current=q,z.push(q)}if(i){const q=Cc(ee,o);b.current=q,z.push(q)}if(l){const q=jc(ee,c);k.current=q,z.push(q)}if(z.length>0){N.current=z[0],R.current=z[z.length-1];for(let q=0;q<z.length-1;q++)z[q].connect(z[q+1])}f(!0)}catch(ee){E&&y(ee)}})(),()=>{var ee,z,q,K,re;E=!1,(ee=g.current)==null||ee.disconnect(),(z=S.current)==null||z.disconnect(),(q=b.current)==null||q.disconnect(),(K=k.current)==null||K.disconnect(),(re=v.current)==null||re.close()}},[t,a,i,l]);const w=u.useCallback(E=>{j.current&&j.current.disconnect(),j.current=E,N.current&&E.connect(N.current)},[]),M=u.useCallback(()=>{j.current&&(j.current.disconnect(),j.current=null)},[]),I=u.useCallback(()=>R.current,[]),A=u.useCallback(E=>{var ee;const V=(ee=S.current)==null?void 0:ee.parameters.get("gain");V&&(V.value=Math.max(0,Math.min(2,E)))},[]),T=u.useCallback((E,V)=>{var z;const ee=(z=b.current)==null?void 0:z.parameters.get(E);ee&&(ee.value=V)},[]),O=u.useCallback((E,V)=>{var z;const ee=(z=k.current)==null?void 0:z.parameters.get(E);ee&&(ee.value=V)},[]);return{isReady:h,error:p,analysis:m,connectSource:w,disconnectSource:M,getOutputNode:I,setGain:A,setCompressorParam:T,setVocoderParam:O,audioContext:v.current}}function a0(e,t,r){const i={id:`${t}-${r}-${Date.now()}`,type:r,bypass:!1,params:{eq3:{lowGain:0,midGain:0,highGain:0,lowFreq:250,highFreq:4e3},compressor:{threshold:-24,ratio:4,attack:.003,release:.25,knee:30},delay:{time:.25,feedback:.3,mix:.3},reverb:{decay:2,mix:.3},distortion:{amount:20,mix:.5}}[r]};e(o=>{var l;return{...o,[t]:{...o[t],effectChain:[...((l=o[t])==null?void 0:l.effectChain)||[],i]}}})}function s0(e,t,r){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.filter(o=>o.id!==r))||[]}}})}function i0(e,t,r){e(a=>{var s,i;return{...a,[t]:{...a[t],effectChain:((i=(s=a[t])==null?void 0:s.effectChain)==null?void 0:i.map(o=>o.id===r?{...o,bypass:!o.bypass}:o))||[]}}})}function o0(e,t,r,a){e(s=>{var i,o;return{...s,[t]:{...s[t],effectChain:((o=(i=s[t])==null?void 0:i.effectChain)==null?void 0:o.map(l=>l.id===r?{...l,params:{...l.params,...a}}:l))||[]}}})}function l0(e,t,r,a,s,i,o=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:s,start:i,duration:o,velocity:l};t(d=>({...d,[a]:[...d[a]||[],c]})),r({layerId:a,noteId:c.id})}function c0(e,t,r,a){e(s=>({...s,[r]:(s[r]||[]).filter(i=>i.id!==a)})),t(null)}function d0(e,t,r){e(a=>({...a,[r]:[]})),t(null)}function u0(e,t,r){e(a=>({...a,[t]:r}))}function h0(e,t,r,a,s){const i={id:Date.now()+Math.floor(Math.random()*1e3),cc:r,value:a,time:s};e(o=>({...o,[t]:[...o[t]||[],i]}))}function p0(e,t,r,a,s,i){e(o=>({...o,[t]:(o[t]||[]).map(l=>l.id===r?{...l,value:a,time:s,handleType:i??l.handleType}:l)}))}function f0(e,t,r){e(a=>({...a,[t]:(a[t]||[]).filter(s=>s.id!==r)}))}function dr(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function m0(e){if(e.length===0)return[];const t=[];let r=e[0];for(let a=1;a<e.length;a++){const s=e[a];s.pitch===r.pitch&&Math.abs(s.freq-r.freq)<1?r.duration+=s.duration:(t.push(r),r=s)}return t.push(r),t}function g0(e,t,r=.01){const a=Math.floor(t/50);let s=-1,i=0,o=0;for(let c=0;c<e.length;c++)o+=e[c]*e[c];if(o=Math.sqrt(o/e.length),o<r)return 0;let l=1;for(let c=50;c<a;c++){let d=0;for(let h=0;h<a;h++)d+=Math.abs(e[h]-e[h+c]);d=1-d/a,d>i&&d>.9&&d>l&&(i=d,s=c),l=d}return s===-1?0:t/s}async function y0(e,t,r){const{signal:a,onProgress:s,rmsThreshold:i,useHanning:o,postPitch:l,postLibrosaPitchTrack:c}=r||{},d=await e.arrayBuffer();if(a!=null&&a.aborted)throw new Error("aborted");const f=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),p=f.getChannelData(0),y=f.sampleRate,m=Math.floor(y*.1),x=m,v=[];if(t==="pitchy"){const g=ia.PitchDetector.forFloat32Array(m),S=Math.max(1,Math.floor((p.length-m)/x));let b=0;for(let k=0;k<p.length-m;k+=x){if(a!=null&&a.aborted)throw new Error("aborted");const j=p.slice(k,k+m);if(o)for(let A=0;A<j.length;A++)j[A]*=.5*(1-Math.cos(2*Math.PI*A/(j.length-1)));const[N,R]=g.findPitch(j,y),w=dr(N);let M=0;for(let A=0;A<j.length;A++)M+=j[A]*j[A];M=Math.sqrt(M/j.length);const I=typeof i=="number"?i:.01;w&&N>50&&N<2e3&&R>.7&&M>I&&v.push({start:k/y,duration:m/y,pitch:w,freq:N}),b++,s&&s(b/S)}}else if(t==="crepe"){if(s&&s(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const g=await l(e);if(a!=null&&a.aborted)throw new Error("aborted");const S=Array.isArray(g.track)?g.track:[];S.length>0&&S.forEach((b,k)=>{var N;const j=dr(b.hz);if(j&&b.hz>50&&b.hz<2e3){const R=((N=S[k+1])==null?void 0:N.t)??b.t+.1;v.push({start:b.t,duration:k<S.length-1?R-b.t:.1,pitch:j,freq:b.hz})}}),s&&s(1)}else if(t==="ultrastar-wp"){const g=Math.max(1,Math.floor((p.length-m)/x));let S=0;for(let b=0;b<p.length-m;b+=x){if(a!=null&&a.aborted)throw new Error("aborted");const k=p.slice(b,b+m);if(o)for(let w=0;w<k.length;w++)k[w]*=.5*(1-Math.cos(2*Math.PI*w/(k.length-1)));const N=g0(k,y,typeof i=="number"?i:.01),R=dr(N);R&&N>50&&N<2e3&&v.push({start:b/y,duration:m/y,pitch:R,freq:N}),S++,s&&s(S/g)}}if(t==="librosa"){if(s&&s(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const g=await c(e);if(a!=null&&a.aborted)throw new Error("aborted");const S=Array.isArray(g.track)?g.track:[];S.length>0&&S.forEach((b,k)=>{var N;const j=dr(b.hz);if(j&&b.hz>50&&b.hz<2e3){const R=((N=S[k+1])==null?void 0:N.t)??b.t+.1;v.push({start:b.t,duration:k<S.length-1?R-b.t:.1,pitch:j,freq:b.hz})}}),s&&s(1)}return m0(v)}function b0(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
407
407
  #ARTIST:AI
408
408
  #ALGO:Pitchy
409
409
  : 0 4 40 Pitchy
@@ -426,4 +426,4 @@ E`;case"ultrastarws":return`#TITLE:Analyzed Song
426
426
  E`;default:return`#TITLE:Analyzed Song
427
427
  #ARTIST:AI
428
428
  : 0 2 40 Test
429
- E`}}function h0(e,t){return`${e}:${t}`}function p0(e,t,n,a=1){if(t==="off")return e;const s=60/n;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function f0(e){return e.length===0?[]:e.flat()}function m0(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ps=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function g0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function wc(e,t){return t.amount===0?e:e.map(n=>{const a=n.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...n,time:n.time+o}}return{...n}})}function jc(e,t){const n=t.seed!=null?g0(t.seed):Math.random;return e.map(a=>{const s=(n()-.5)*2*t.timingAmount,i=Math.round((n()-.5)*2*t.velocityAmount),o=(n()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function Cc(e,t,n=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*n,c=1+(t.velocityScales[o]-1)*n,u=1+(t.durationScales[o]-1)*n;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*u)}})}function y0(e,t){let n=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(n=Cc(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=wc(n,t.swing)),t.humanize&&(n=jc(n,t.humanize)),n}function b0(e){return ps.find(t=>t.id===e)}function x0(){return ps.map(({id:e,name:t})=>({id:e,name:t}))}function Mc(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function fs(e,t){return Mc(e)*60/t}function ja(e,t,n){const a=fs(t,n);return Math.round(e/a)*a}function v0(e,t){const{value:n,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=fs(n,a);return e.map(c=>{let{start:u,duration:h}=c;if(i){const p=Math.round(u/l)*l;u=u+(p-u)*s}if(o){const p=Math.max(l,Math.round(h/l)*l);h=h+(p-h)*s}return u===c.start&&h===c.duration?c:{...c,start:u,duration:h}})}function S0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function k0(e,t={}){const{timingRange:n=.02,velocityRange:a=10,seed:s}=t,i=s!=null?S0(s):Math.random;return e.map(o=>{const l=(i()*2-1)*n,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function w0(){return{start:0,end:0,enabled:!1}}function j0(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function C0(e,t,n){return{start:ja(e.start,t,n),end:ja(e.end,t,n),enabled:e.enabled}}function M0(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function R0(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const n=t.end-t.start;return t.start+(e-t.start)%n}return e}function Ca(e){return e.length===1?e.toLowerCase():e}function kr(e){var n,a,s,i;const t=[];return(n=e.modifiers)!=null&&n.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ca(e.key)),t.join("+")}function N0(e,t){var l,c,u,h;const n=Ca(e.key)===Ca(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((u=t.modifiers)!=null&&u.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return n&&a&&s&&i&&o}class Rc{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,n){const a=this.actions.get(t);a&&(a.binding=n)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const n of t)this.activeScopes.add(n)}setEnabled(t){this.enabled=t}setActionEnabled(t,n){const a=this.actions.get(t);a&&(a.enabled=n)}findConflicts(){const t=[],n=[...this.actions.values()];for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){const i=n[a],o=n[s];kr(i.binding)===kr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const n of this.actions.values())t[n.group]||(t[n.group]=[]),t[n.group].push(n);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const n of t)this.rebind(n.id,n.binding)}formatBinding(t){const n=this.actions.get(t);return n?kr(n.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const n of this.actions.values())if(n.enabled&&this.activeScopes.has(n.scope)&&N0(t,n.binding))return t.preventDefault(),t.stopPropagation(),n.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const n=t.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function T0(e={}){const t=new Rc,n=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??n});return t}function $0(e){return kr(e)}const P0=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],A0=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],E0=500*1024*1024,I0=20;function Ot(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function L0(e,t){return!!(e.type&&t.some(n=>e.type.startsWith(n.replace("*","")))||e.type.startsWith("audio/"))}function D0(e,t){const n=Ot(e.name);return n!==""&&t.includes(n)}function ms(e,t={}){const n=t.maxSize??E0,a=t.allowedTypes??P0,s=t.allowedExtensions??A0,i=t.maxFiles??I0,o=[],l=[];for(let c=0;c<e.length;c++){const u=e[c];if(c>=i){l.push({file:u,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(u.size>n){l.push({file:u,reason:"size",message:`File exceeds ${Math.round(n/1024/1024)}MB limit`});continue}if(!L0(u,a)&&!D0(u,s)){l.push({file:u,reason:"type",message:`Unsupported file type: ${u.type||Ot(u.name)}`});continue}o.push(u)}return{valid:o,errors:l}}async function Nc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Ot(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Ot(e.name)}`};try{const n=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(n);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function _0(e){let t=0;return{onDragEnter:n=>{var a;n.preventDefault(),n.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:n=>{n.preventDefault(),n.stopPropagation(),(n instanceof DragEvent&&n.dataTransfer||"dataTransfer"in n&&n.dataTransfer)&&(n.dataTransfer.dropEffect="copy")},onDragLeave:n=>{var a;n.preventDefault(),n.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async n=>{var u,h;n.preventDefault(),n.stopPropagation(),t=0,(u=e.onDragLeave)==null||u.call(e);const a="dataTransfer"in n?n.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=ms(s,e.validation),l=[],c=[...o];for(const p of i)if(e.probe)try{l.push(await Nc(p))}catch{c.push({file:p,reason:"decode",message:"Failed to decode audio"})}else l.push({file:p,name:p.name.replace(/\.[^.]+$/,""),extension:Ot(p.name),sizeBytes:p.size,mimeType:p.type||`audio/${Ot(p.name)}`});e.onDrop({accepted:l,rejected:c})}}}function F0(e={}){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept="audio/*,.mid,.midi",n.multiple=e.multiple??!0,n.onchange=async()=>{var l;if(!((l=n.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(n.files),{valid:s,errors:i}=ms(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Ot(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Ot(c.name)}`}));t({accepted:o,rejected:i})},n.click()})}var Ft=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ft||{}),Tc=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(Tc||{}),$c=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))($c||{});const z0=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Ar=["off","no function","brak"],O0=e=>e.segments.some(t=>t.isOff||Ar.some(n=>t.name.toLowerCase().includes(n))),B0=e=>e.segments.find(t=>t.isOff||Ar.some(n=>t.name.toLowerCase().includes(n))),Pc=e=>Math.floor((e.valueFrom+e.valueTo)/2),G0=e=>{const t=B0(e);return t?Pc(t):0},W0=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),jn=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Gn=({channel:e,value:t,onChange:n,onCommit:a,showDirectionHint:s})=>{const[i,o]=d.useState(jn(t)),l=d.useMemo(()=>W0(e,i),[e,i]);d.useEffect(()=>o(jn(t)),[t]);const c=u=>{const h=jn(u);o(h),n(h),a==null||a(h)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&l&&r.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),r.jsx("input",{type:"range",min:0,max:255,value:i,onChange:u=>{const h=jn(Number(u.target.value));o(h),n(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),r.jsx("div",{style:{marginTop:6},children:r.jsx("input",{type:"number",min:0,max:255,value:i,onChange:u=>{const h=jn(Number(u.target.value));o(h),n(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),O0(e)&&r.jsx("button",{type:"button",onClick:()=>c(G0(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},gs=({channel:e,value:t,onChange:n,onCommit:a})=>{const s=d.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const u=(l.isOff?-1:0)+(Ar.some(p=>l.name.toLowerCase().includes(p))?-1:0),h=(c.isOff?-1:0)+(Ar.some(p=>c.name.toLowerCase().includes(p))?-1:0);return u!==h?u-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=Pc(o);n(l),a==null||a(l)};return r.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[r.jsxs("strong",{children:[e.channel,". ",e.name]}),r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return r.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},ys=e=>{switch(e.channel.type){case Ft.Dimmer:case Ft.DimmerWithOff:return r.jsx(Gn,{...e});case Ft.RotationWithOff:case Ft.RotationWithOffAndCcw:return r.jsx(Gn,{...e,showDirectionHint:!0});case Ft.Options:return r.jsx(gs,{...e});default:return r.jsx(Gn,{...e})}},na=e=>Math.max(0,Math.min(255,Math.round(e))),U0=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function Ac({service:e,pollInterval:t=500,className:n,style:a,channels:s,onChannelChange:i,fixtures:o,tutorial:l}){if(!e)return r.jsx("div",{className:n,style:a,children:r.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})});const[c,u]=d.useState([]),[h,p]=d.useState(null),[f,y]=d.useState(()=>Array(513).fill(0)),[m,v]=d.useState(30),[x,g]=d.useState(0),[k,b]=d.useState(!1),S=d.useRef(null);d.useEffect(()=>{let _=!1;return e.getDevices().then(L=>{_||(u(L),L.length>0&&p(L[0]))}).catch(()=>{}),()=>{_=!0}},[e]),d.useEffect(()=>{if(S.current&&window.clearInterval(S.current),!(t<=0))return S.current=window.setInterval(async()=>{try{const _=await e.getState();Array.isArray(_.frontSnapshot)&&_.frontSnapshot.length>=513&&y(_.frontSnapshot.slice(0,513)),typeof _.fps=="number"&&v(_.fps),typeof _.startCode=="number"&&g(_.startCode)}catch{}},t),()=>{S.current&&window.clearInterval(S.current)}},[e,t]);const M=async()=>{h&&(await e.openPort(h.serialNumber||h.description),b(!0))},R=async()=>{await e.closePort(),b(!1)},N=async()=>{await e.blackout(),y(_=>{const L=[..._];for(let U=1;U<L.length;U++)L[U]=0;return L})},C=()=>e.configure(m,x),w=(_,L)=>{const U=na(L);y(Z=>{const A=[...Z];return A[_]=U,A})},O=(_,L)=>e.setChannel(_,na(L)),$=(h==null?void 0:h.deviceInfo)??null,E=d.useMemo(()=>{var _;return(_=$==null?void 0:$.channels)!=null&&_.length?$.channels:Array.from({length:16},(L,U)=>({channel:U+1,name:`Channel ${U+1}`,type:Ft.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[$]);return r.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[r.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:r.jsx(aa.NiceTutorialButton,{steps:aa.resolveTutorial(l,U0)})}),r.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),r.jsx("select",{value:(h==null?void 0:h.serialNumber)||"",onChange:_=>p(c.find(L=>L.serialNumber===_.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:c.map(_=>{var L,U;return r.jsxs("option",{value:_.serialNumber,children:[((L=_.deviceInfo)==null?void 0:L.manufacturer)??""," ",((U=_.deviceInfo)==null?void 0:U.model)??_.description," (",_.serialNumber||_.description,")"]},_.serialNumber||_.description)})}),$&&r.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",r.jsx("b",{children:$.modeName}),", footprint: ",r.jsx("b",{children:$.footprint})]})]}),r.jsx("button",{onClick:M,disabled:!h||k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),r.jsx("button",{onClick:R,disabled:!k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),r.jsx("button",{onClick:N,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-text-secondary, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),r.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),r.jsx("input",{type:"number",min:10,max:44,value:m,onChange:_=>v(Number(_.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsxs("div",{children:[r.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),r.jsx("input",{type:"number",min:0,max:255,value:x,onChange:_=>g(na(Number(_.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),r.jsx("div",{children:r.jsx("button",{onClick:C,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),r.jsxs("section",{children:[r.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),r.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:E.map(_=>r.jsx(ys,{channel:_,value:f[_.channel]??0,onChange:L=>w(_.channel,L),onCommit:L=>O(_.channel,L)},_.channel))})]})]})}const Ec=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class Ic{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Ec.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,n){const a={id:String(t),name:n,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,n,a){const s=this.universes.get(t);s&&n>=1&&n<=512&&(s.channels[n-1]=Math.max(0,Math.min(255,a)))}getChannel(t,n){const a=this.universes.get(t);return a&&n>=1&&n<=512?a.channels[n-1]:0}setFixtureValues(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(n.length,s.channelCount);i++)a.values[i]=n[i],this.setChannel(a.universe,a.startChannel+i,n[i])}setFixtureColor(t,n,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((u,h)=>{u.name.toLowerCase().includes("red")?c[h]=n:u.name.toLowerCase().includes("green")?c[h]=a:u.name.toLowerCase().includes("blue")?c[h]=s:u.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,n){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(n*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,n,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),u=()=>{const h=performance.now()-c,p=Math.min(1,h/a);let f=p;switch(s){case"ease-in":f=p*p;break;case"ease-out":f=1-(1-p)*(1-p);break;case"ease-in-out":f=p<.5?2*p*p:1-Math.pow(-2*p+2,2)/2;break}const y=l.map((m,v)=>{const x=n[v]??m;return Math.round(m+(x-m)*f)});this.setFixtureValues(t,y),p<1?requestAnimationFrame(u):i()};u()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,n)=>{this.outputCallback(n,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const q0=6454,V0=new Uint8Array([65,114,116,45,78,101,116,0]);function H0(e,t){const n=new Uint8Array(18+t.length);return n.set(V0,0),n[8]=0,n[9]=80,n[10]=0,n[11]=14,n[12]=0,n[13]=0,n[14]=e&255,n[15]=e>>8&255,n[16]=t.length>>8&255,n[17]=t.length&255,n.set(t.slice(0,512),18),n}const K0=5568;function Y0(e,t,n,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const u=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<u.length;m++)l[4+m]=u[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const p=o-38;c.setUint16(38,28672|p&4095,!1),c.setUint32(40,2,!1);const f=new TextEncoder().encode(s.slice(0,63));l.set(f,44),l[108]=a,c.setUint16(109,0,!1),l[111]=n&255,l[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),l[125]=0,l.set(t.slice(0,i),126),l}function Z0(e){const t=e>>8&255,n=e&255;return`239.255.${t}.${n}`}class X0{constructor(t,n){this.config=t,this.scenes=n,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const n=this.scenes.get(t.sceneId);if(!n){this.advanceStep();return}const a=new Uint8Array(512);if(n.channels)for(const l of n.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,n){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let u=0;u<512;u++)s[u]=Math.round(this.fadeFromValues[u]+(this.fadeToValues[u]-this.fadeFromValues[u])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):n()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:n,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!n){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!n){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const Q0=({engine:e,tracks:t=[],scenes:n=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:u,onTrackAdd:h,onTrackUpdate:p,onPlay:f,onPause:y,onStop:m,className:v=""})=>{const[x,g]=d.useState(1),[k,b]=d.useState(0),[S,M]=d.useState(!1),[R,N]=d.useState(null),[C,w]=d.useState(null),[O,$]=d.useState(!0),[E,_]=d.useState(1e3),L=d.useRef(null),U=d.useRef(null),Z=d.useRef(0),A=d.useMemo(()=>.1*x,[x]),q=d.useCallback(T=>T*A,[A]),H=d.useCallback(T=>T/A,[A]),re=d.useCallback(T=>{if(!O)return T;const z=6e4/i;return Math.round(T/z)*z},[O,i]);d.useEffect(()=>{if(S){const T=performance.now(),z=s,B=()=>{const G=performance.now()-T,Y=z+G;if(Y>=a){M(!1),o==null||o(0),m==null||m();return}D(Y),o==null||o(Y),U.current=requestAnimationFrame(B)};U.current=requestAnimationFrame(B),f==null||f()}else U.current!==null&&(cancelAnimationFrame(U.current),U.current=null),y==null||y();return()=>{U.current!==null&&cancelAnimationFrame(U.current)}},[S,s,a,o,f,y,m]);const D=d.useCallback(T=>{t.forEach(z=>{z.muted||z.cues.forEach(B=>{const G=B.startTime,Y=G+B.duration;if(T>=G&&T<Y&&Z.current<G){const X=n.find(ie=>ie.id===B.sceneId);X&&X.fixtures.forEach(ie=>{B.fadeIn&&B.fadeIn>0?e.fadeFixture(ie.fixtureId,ie.values,B.fadeIn):e.setFixtureValues(ie.fixtureId,ie.values)})}if(Z.current<Y&&T>=Y){const X=n.find(ie=>ie.id===B.sceneId);X&&X.fixtures.forEach(ie=>{if(e.getFixture(ie.fixtureId)&&B.fadeOut&&B.fadeOut>0){const te=new Array(ie.values.length).fill(0);e.fadeFixture(ie.fixtureId,te,B.fadeOut)}})}})}),Z.current=T},[t,n,e]),W=T=>{const z=Math.floor(T/1e3),B=Math.floor(z/60),G=z%60,Y=Math.floor(T%1e3/(1e3/30));return`${B}:${G.toString().padStart(2,"0")}:${Y.toString().padStart(2,"0")}`},j=d.useCallback(T=>{if(!L.current)return;const z=L.current.getBoundingClientRect(),B=T.clientX-z.left+k,G=re(H(B));o==null||o(Math.max(0,Math.min(a,G)))},[k,H,re,a,o]),F=d.useCallback((T,z,B)=>{const G=t.find(ie=>ie.id===z),Y=G==null?void 0:G.cues.find(ie=>ie.id===T);if(!Y)return;const X=re(Math.max(0,Y.startTime+H(B)));c==null||c({...Y,startTime:X})},[t,H,re,c]),I=()=>{const T=6e4/i,z=Math.ceil(a/T),B=[];for(let G=0;G<=z;G++){const Y=G*T,X=q(Y),ie=G%4===0;B.push(r.jsx("div",{className:`nice-dmx-timeline__beat ${ie?"nice-dmx-timeline__beat--measure":""}`,style:{left:X},children:ie&&r.jsx("span",{className:"nice-dmx-timeline__beat-label",children:G/4+1})},G))}return B},P=(T,z)=>{const B=q(T.startTime),G=q(T.duration),Y=n.find(X=>X.id===T.sceneId);return r.jsxs("div",{className:`nice-dmx-timeline__cue ${R===T.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:B,width:G,backgroundColor:(Y==null?void 0:Y.color)||z.color||"var(--nice-accent, #8b5cf6)"},onClick:X=>{X.stopPropagation(),N(T.id)},draggable:!z.locked,onDragEnd:X=>{var le;const ie=(le=X.target.parentElement)==null?void 0:le.getBoundingClientRect();ie&&F(T.id,z.id,X.clientX-ie.left-B)},children:[r.jsx("span",{className:"nice-dmx-timeline__cue-name",children:T.name||(Y==null?void 0:Y.name)}),T.fadeIn&&T.fadeIn>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:q(T.fadeIn)}}),T.fadeOut&&T.fadeOut>0&&r.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:q(T.fadeOut)}})]},T.id)};return r.jsxs("div",{className:`nice-dmx-timeline ${v}`,children:[r.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[r.jsxs("div",{className:"nice-dmx-timeline__transport",children:[r.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(0),title:"Go to start","aria-label":"Go to start",children:r.jsx(se.NtdSkipBack,{size:14})}),r.jsx("button",{type:"button",onClick:()=>M(!S),title:S?"Pause":"Play","aria-label":S?"Pause":"Play",children:S?r.jsx(se.NtdPause,{size:14}):r.jsx(se.NtdPlay,{size:14})}),r.jsx("button",{type:"button",onClick:()=>{M(!1),o==null||o(0),e.blackout(),m==null||m()},title:"Stop","aria-label":"Stop",children:r.jsx(se.NtdStop,{size:14})})]}),r.jsx("div",{className:"nice-dmx-timeline__time",children:W(s)}),r.jsxs("div",{className:"nice-dmx-timeline__tools",children:[r.jsx("button",{type:"button",className:O?"active":"",onClick:()=>$(!O),title:"Snap to grid","aria-label":"Snap to grid",children:r.jsx(se.NtdGrid,{size:14})}),r.jsx("button",{type:"button",onClick:()=>g(Math.max(.25,x-.25)),title:"Zoom out",children:"−"}),r.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(x*100),"%"]}),r.jsx("button",{type:"button",onClick:()=>g(Math.min(4,x+.25)),title:"Zoom in",children:"+"})]}),r.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[r.jsx("label",{children:"BPM:"}),r.jsx("span",{children:i})]}),r.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout","aria-label":"Blackout",children:r.jsx(se.NtdMoon,{size:14})})]}),r.jsxs("div",{className:"nice-dmx-timeline__content",children:[r.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(T=>r.jsxs("div",{className:`nice-dmx-timeline__header ${C===T.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>w(T.id),children:[r.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:T.color||"var(--nice-accent, #8b5cf6)"}}),r.jsx("span",{className:"nice-dmx-timeline__track-name",children:T.name}),r.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[r.jsx("button",{type:"button",className:T.muted?"active":"",onClick:z=>{z.stopPropagation(),p==null||p({...T,muted:!T.muted})},title:"Mute",children:"M"}),r.jsx("button",{type:"button",className:T.locked?"active":"",onClick:z=>{z.stopPropagation(),p==null||p({...T,locked:!T.locked})},title:"Lock","aria-label":"Lock",children:r.jsx(se.NtdLock,{size:14})})]})]},T.id)),r.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),r.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:L,onClick:j,onScroll:T=>b(T.currentTarget.scrollLeft),children:[r.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:q(a)},children:I()}),t.map(T=>r.jsx("div",{className:`nice-dmx-timeline__track ${T.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:q(a)},children:T.cues.map(z=>P(z,T))},T.id)),r.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:q(s)}})]})]})]})};function J0(){const[e]=d.useState(()=>new Ic);return d.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function eg(e,t,n=120){const[a,s]=d.useState(0),i=d.useRef(0);return d.useEffect(()=>{if(!t)return;const o=60/n,l=()=>{const c=t.currentTime,u=Math.floor(c/o);u!==i.current&&(i.current=u,s(u))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,n]),{currentBeat:a}}const tg=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function Lc(){const[e,t]=d.useState(!1),[n,a]=d.useState(.8),[s,i]=d.useState(!1),[o,l]=d.useState(null),[c,u]=d.useState(null),[h,p]=d.useState(null),f=d.useRef(null),y=d.useRef(null),m=d.useRef(null),v=d.useRef(null),x=d.useRef([]),g=d.useRef(null),k=d.useRef(null),b=d.useCallback(()=>{if(y.current)return;const L=new AudioContext;y.current=L;const U=L.createGain();U.gain.value=n,v.current=U;const Z=L.createAnalyser();Z.fftSize=256,g.current=Z,U.connect(Z).connect(L.destination)},[]),S=d.useCallback(()=>{const L=f.current,U=y.current,Z=v.current;if(!L||!U||!Z||m.current)return;const A=U.createMediaElementSource(L);m.current=A,x.current.length>0?(A.connect(x.current[0]),x.current[x.current.length-1].connect(Z)):A.connect(Z)},[]),M=d.useCallback(()=>{var U;const L=f.current;!L||!k.current||(Bt(),b(),S(),((U=y.current)==null?void 0:U.state)==="suspended"&&y.current.resume(),L.play().catch(Z=>u(String(Z))))},[b,S]),R=d.useCallback(()=>{var L;(L=f.current)==null||L.pause()},[]),N=d.useCallback(()=>{e?R():M()},[e,M,R]),C=d.useCallback(L=>{const U=Math.max(0,Math.min(1,L));a(U),v.current&&(v.current.gain.value=U),f.current&&(f.current.volume=U)},[]),w=d.useCallback(L=>{k.current=L,u(null),l(null),i(!0),m.current&&(m.current.disconnect(),m.current=null),f.current||(f.current=new Audio,f.current.crossOrigin="anonymous",f.current.addEventListener("playing",()=>{t(!0),i(!1)}),f.current.addEventListener("pause",()=>t(!1)),f.current.addEventListener("waiting",()=>i(!0)),f.current.addEventListener("canplay",()=>i(!1)),f.current.addEventListener("error",()=>u("Failed to load stream"))),f.current.src=L.streamUrl,f.current.load(),l({genre:L.genre,bitrate:L.bitrate})},[]),O=d.useCallback(L=>{y.current||b();const Z=y.current;x.current.forEach(q=>q.disconnect());const A=L.bands.map(q=>{const H=Z.createBiquadFilter();return H.type="peaking",H.frequency.value=q.frequency,H.gain.value=q.gain,H.Q.value=q.Q??1.4,H});for(let q=0;q<A.length-1;q++)A[q].connect(A[q+1]);x.current=A,m.current&&v.current&&(m.current.disconnect(),m.current.connect(A[0]),A[A.length-1].connect(v.current)),p(L.name)},[b]),$=d.useCallback(()=>{x.current.forEach(L=>L.disconnect()),x.current=[],m.current&&v.current&&(m.current.disconnect(),m.current.connect(v.current)),p(null)},[]);return d.useEffect(()=>()=>{var L,U,Z;(L=f.current)==null||L.pause(),f.current=null,x.current.forEach(A=>A.disconnect()),(U=m.current)==null||U.disconnect(),(Z=y.current)==null||Z.close()},[]),[{isPlaying:e,volume:n,isBuffering:s,metadata:o,error:c,activePreset:h},{play:M,pause:R,toggle:N,setVolume:C,setStation:w,applyEQPreset:O,clearEQ:$}]}function Dc({stations:e,activeStationId:t,onSelect:n,onToggleFavorite:a,className:s}){const{t:i}=Te(),[o,l]=d.useState(""),[c,u]=d.useState(null),[h,p]=d.useState(!1),f=d.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=d.useMemo(()=>e.filter(m=>{var v,x;if(h&&!m.isFavorite||c&&m.genre!==c)return!1;if(o){const g=o.toLowerCase();return m.name.toLowerCase().includes(g)||(((v=m.genre)==null?void 0:v.toLowerCase().includes(g))??!1)||(((x=m.country)==null?void 0:x.toLowerCase().includes(g))??!1)}return!0}),[e,o,c,h]);return r.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[r.jsxs("div",{className:"nice-station-browser__toolbar",children:[r.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(i==null?void 0:i("search_stations"))??"Search stations...",value:o,onChange:m=>l(m.target.value)}),r.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:m=>u(m.target.value||null),children:[r.jsx("option",{value:"",children:(i==null?void 0:i("all_genres"))??"All Genres"}),f.map(m=>r.jsx("option",{value:m,children:m},m))]}),r.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>p(!h),title:(i==null?void 0:i("favorites"))??"Favorites","aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(se.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),r.jsxs("div",{className:"nice-station-browser__list",children:[y.map(m=>r.jsxs("div",{className:`nice-station-browser__item${m.id===t?" nice-station-browser__item--active":""}`,onClick:()=>n(m),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&n(m)},children:[m.logoUrl&&r.jsx("img",{className:"nice-station-browser__logo",src:m.logoUrl,alt:m.name,loading:"lazy"}),r.jsxs("div",{className:"nice-station-browser__info",children:[r.jsx("span",{className:"nice-station-browser__name",children:m.name}),m.genre&&r.jsx("span",{className:"nice-station-browser__genre",children:m.genre}),m.country&&r.jsx("span",{className:"nice-station-browser__country",children:m.country})]}),m.bitrate&&r.jsxs("span",{className:"nice-station-browser__bitrate",children:[m.bitrate,"kbps"]}),a&&r.jsx("button",{className:`nice-station-browser__fav${m.isFavorite?" nice-station-browser__fav--active":""}`,onClick:v=>{v.stopPropagation(),a(m.id)},"aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:r.jsx(se.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--text-muted)"}})})]},m.id)),y.length===0&&r.jsx("div",{className:"nice-station-browser__empty",children:(i==null?void 0:i("no_stations_found"))??"No stations found"})]})]})}function ng({stations:e,initialStationId:t,autoPlay:n=!1,eqPresets:a=tg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:u,showBrowser:h=!0,showEqualizer:p=!1,showVisualizer:f=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:v=!1,className:x,style:g}){var P,T;const{t:k}=Te(),[b,S]=Lc(),[M,R]=d.useState(()=>t?e.find(z=>z.id===t)??null:null),[N,C]=d.useState(p),w=d.useRef(null),O=d.useRef(0),[$,E]=d.useState([]),[_,L]=d.useState(!1),U=d.useRef(null),Z=d.useRef([]),[A,q]=d.useState(0),H=d.useRef(null),[re,D]=d.useState(0),[W,j]=d.useState(null),F=d.useRef(null);d.useEffect(()=>{i==null||i(b.isPlaying)},[b.isPlaying,i]),d.useEffect(()=>{b.metadata&&(o==null||o(b.metadata),(b.metadata.title||b.metadata.artist)&&E(z=>[{time:new Date,meta:b.metadata},...z.slice(0,49)]))},[b.metadata,o]);const I=d.useCallback(z=>{R(z),S.setStation(z),s==null||s(z),n&&setTimeout(()=>S.play(),100)},[S,s,n]);return d.useEffect(()=>{if(t&&!M){const z=e.find(B=>B.id===t);z&&I(z)}},[t,e]),d.useEffect(()=>{if(!f||!w.current)return;const z=w.current,B=z.getContext("2d");if(!B)return;const G=()=>{O.current=requestAnimationFrame(G),B.clearRect(0,0,z.width,z.height);const Y=B.createLinearGradient(0,z.height,0,0);if(Y.addColorStop(0,"var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))"),Y.addColorStop(.5,"rgba(168,85,247,0.6)"),Y.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const te=z.width/32;for(let V=0;V<32;V++){const K=4+Math.sin(Date.now()/1e3+V*.3)*3;B.fillStyle=Y,B.fillRect(V*te+1,z.height-K,te-2,K)}return}const X=32,ie=z.width/X;for(let le=0;le<X;le++){const te=le/X,K=(Math.sin(Date.now()/200+le*.5)*.3+.5)*z.height*(1-te*.5)*(.5+Math.random()*.5);B.fillStyle=Y,B.fillRect(le*ie+1,z.height-K,ie-2,K)}};return G(),()=>cancelAnimationFrame(O.current)},[f,b.isPlaying]),d.useCallback(()=>{if(b.isPlaying)try{const B=new AudioContext().createMediaStreamDestination();Z.current=[];const G=new MediaRecorder(B.stream,{mimeType:"audio/webm"});G.ondataavailable=Y=>{Y.data.size>0&&Z.current.push(Y.data)},G.onstop=()=>{const Y=new Blob(Z.current,{type:"audio/webm"});u==null||u(Y),q(0),H.current&&window.clearInterval(H.current)},G.start(1e3),U.current=G,L(!0),q(0),H.current=window.setInterval(()=>{q(Y=>Y+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,u]),d.useCallback(()=>{U.current&&_&&(U.current.stop(),L(!1),H.current&&window.clearInterval(H.current))},[_]),d.useCallback(z=>{F.current&&window.clearInterval(F.current),D(z),j(z*60),F.current=window.setInterval(()=>{j(B=>!B||B<=1?(F.current&&window.clearInterval(F.current),F.current=null,S.pause(),null):B-1)},1e3)},[S]),d.useCallback(()=>{F.current&&window.clearInterval(F.current),F.current=null,j(null),D(0)},[]),d.useEffect(()=>()=>{H.current&&window.clearInterval(H.current),F.current&&window.clearInterval(F.current),cancelAnimationFrame(O.current)},[]),r.jsxs("div",{className:`nice-radio-player${x?` ${x}`:""}`,style:g,children:[r.jsx("div",{className:"nice-radio-player__now-playing",children:M?r.jsxs(r.Fragment,{children:[M.logoUrl&&r.jsx("img",{className:"nice-radio-player__cover",src:M.logoUrl,alt:M.name}),r.jsxs("div",{className:"nice-radio-player__info",children:[r.jsx("span",{className:"nice-radio-player__station-name",children:M.name}),((P=b.metadata)==null?void 0:P.title)&&r.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((T=b.metadata)==null?void 0:T.genre)&&r.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&r.jsx("span",{className:"nice-radio-player__buffering",children:(k==null?void 0:k("buffering"))??"Buffering..."})]})]}):r.jsx("div",{className:"nice-radio-player__placeholder",children:(k==null?void 0:k("select_station"))??"Select a station"})}),r.jsxs("div",{className:"nice-radio-player__controls",children:[r.jsx("button",{className:"nice-radio-player__play-btn",onClick:S.toggle,disabled:!M,"aria-label":b.isPlaying?"Pause":"Play",children:b.isPlaying?r.jsx(se.NtdPause,{size:16}):r.jsx(se.NtdPlay,{size:16})}),r.jsxs("div",{className:"nice-radio-player__volume",children:[r.jsx("span",{className:"nice-radio-player__volume-icon","aria-hidden":"true",children:r.jsx(se.NtdVolume,{size:16})}),r.jsx("input",{type:"range",min:0,max:1,step:.01,value:b.volume,onChange:z=>S.setVolume(parseFloat(z.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),r.jsx("button",{className:`nice-radio-player__eq-btn${N?" nice-radio-player__eq-btn--active":""}`,onClick:()=>C(!N),title:"Equalizer",children:"EQ"})]}),b.error&&r.jsx("div",{className:"nice-radio-player__error",children:b.error}),N&&r.jsx("div",{className:"nice-radio-player__equalizer",children:r.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(z=>r.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===z.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>S.applyEQPreset(z),children:z.name},z.name)),b.activePreset&&r.jsx("button",{className:"nice-radio-player__eq-preset",onClick:S.clearEQ,children:(k==null?void 0:k("clear"))??"Clear"})]})}),h&&r.jsx(Dc,{stations:e,activeStationId:M==null?void 0:M.id,onSelect:I})]})}const rg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],ag={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class _c{constructor(t,n={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:n.iceServers??rg,audioConstraints:{...ag,echoCancellation:n.echoCancellation??!0,noiseSuppression:n.noiseSuppression??!0,autoGainControl:n.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var n;return((n=this.peers.get(t))==null?void 0:n.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const n=this.createPeerConnection(t),a=await n.createOffer();await n.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const n=this.peers.get(t);n&&(n.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(n=>{n.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const n=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:n,remoteStream:null,state:n.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{n.addTrack(s,this.localStream)}),n.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},n.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},n.onconnectionstatechange=()=>{var s;a.state=n.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,n.connectionState),(n.connectionState==="failed"||n.connectionState==="disconnected")&&this.removePeer(t)},n}async handleOffer(t,n){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(n));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,n){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(n))}async handleIceCandidate(t,n){const a=this.peers.get(t);a&&n&&await a.pc.addIceCandidate(new RTCIceCandidate(n))}sendSignalingMessage(t){var n;(n=this.onSignalingMessage)==null||n.call(this,t)}}function sg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function ig(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function og(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const bs=d.forwardRef(function(t,n){const{mode:a="bars",width:s=300,height:i=100,barCount:o=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:u=256,smoothing:h=.8,minDecibels:p=-90,maxDecibels:f=-10,deviceId:y,autoStart:m=!1,onStart:v,onStop:x,onAudioLevel:g,onError:k,className:b,style:S,barBorderRadius:M=2,barGap:R=2,lineWidth:N=2}=t,C=d.useRef(null),w=d.useRef(null),O=d.useRef(null),$=d.useRef(null),E=d.useRef(0),_=d.useRef(null),L=d.useRef(0),[U,Z]=d.useState(!1),A=d.useCallback((I,P,T=!0)=>{const z=T?I.createLinearGradient(0,i,0,0):I.createLinearGradient(0,0,s,0);return P.forEach((B,G)=>{z.addColorStop(G/(P.length-1),B)}),z},[s,i]),q=d.useCallback((I,P)=>{const z=(s-(o-1)*R)/o,B=Math.floor(P.length/o),G=Array.isArray(l)?l:[l],Y=G.length>1?A(I,G):G[0];I.fillStyle=Y;for(let X=0;X<o;X++){const le=P[X*B]/255*i,te=X*(z+R),V=i-le;M>0?(I.beginPath(),I.roundRect(te,V,z,le,M),I.fill()):I.fillRect(te,V,z,le)}},[o,l,R,M,s,i,A]),H=d.useCallback((I,P)=>{const T=i/2,B=(s-(o-1)*R)/o,G=Math.floor(P.length/o),Y=Array.isArray(l)?l:[l],X=Y.length>1?A(I,Y):Y[0];I.fillStyle=X;for(let ie=0;ie<o;ie++){const te=P[ie*G]/255*T,V=ie*(B+R);M>0?(I.beginPath(),I.roundRect(V,T-te,B,te,M),I.fill(),I.beginPath(),I.roundRect(V,T,B,te,M),I.fill()):(I.fillRect(V,T-te,B,te),I.fillRect(V,T,B,te))}},[o,l,R,M,s,i,A]),re=d.useCallback((I,P)=>{const T=Array.isArray(l)?l:[l];I.strokeStyle=T.length>1?A(I,T,!1):T[0],I.lineWidth=N,I.lineCap="round",I.lineJoin="round",I.beginPath();const z=s/P.length;let B=0;for(let G=0;G<P.length;G++){const X=P[G]/128*i/2;G===0?I.moveTo(B,X):I.lineTo(B,X),B+=z}I.stroke()},[l,N,s,i,A]),D=d.useCallback((I,P)=>{const T=s/2,z=i/2,B=Math.min(s,i)/3,G=Array.isArray(l)?l:[l];I.strokeStyle=G.length>1?A(I,G):G[0],I.lineWidth=N;const Y=Math.floor(P.length/64),X=Math.PI*2/64;I.beginPath();for(let ie=0;ie<64;ie++){const le=P[ie*Y]/255,te=B+le*B*.5,V=ie*X-Math.PI/2,K=T+Math.cos(V)*te,oe=z+Math.sin(V)*te;ie===0?I.moveTo(K,oe):I.lineTo(K,oe)}I.closePath(),I.stroke()},[l,N,s,i,A]),W=d.useCallback(()=>{const I=C.current,P=O.current,T=_.current;if(!I||!P||!T)return;const z=I.getContext("2d");if(!z)return;a==="waveform"?P.getByteTimeDomainData(T):P.getByteFrequencyData(T);let B=0;for(let G=0;G<T.length;G++)B+=T[G];switch(L.current=B/(T.length*255),g==null||g(L.current),z.clearRect(0,0,s,i),c!=="transparent"&&(z.fillStyle=c,z.fillRect(0,0,s,i)),a){case"bars":q(z,T);break;case"mirror-bars":H(z,T);break;case"waveform":re(z,T);break;case"circle":D(z,T);break}E.current=requestAnimationFrame(W)},[a,s,i,c,q,H,re,D,g]),j=d.useCallback(async()=>{try{if(U)return;const I=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});$.current=I;const P=new AudioContext;w.current=P;const T=P.createMediaStreamSource(I),z=P.createAnalyser();z.fftSize=u,z.smoothingTimeConstant=h,z.minDecibels=p,z.maxDecibels=f,T.connect(z),O.current=z,_.current=new Uint8Array(z.frequencyBinCount),Z(!0),v==null||v(),W()}catch(I){k==null||k(I instanceof Error?I:new Error(String(I)))}},[U,y,u,h,p,f,v,k,W]),F=d.useCallback(()=>{cancelAnimationFrame(E.current),$.current&&($.current.getTracks().forEach(P=>P.stop()),$.current=null),w.current&&(w.current.close(),w.current=null),O.current=null,_.current=null,L.current=0,Z(!1),x==null||x();const I=C.current;if(I){const P=I.getContext("2d");P&&(P.clearRect(0,0,s,i),c!=="transparent"&&(P.fillStyle=c,P.fillRect(0,0,s,i)))}},[s,i,c,x]);return d.useImperativeHandle(n,()=>({start:j,stop:F,isCapturing:()=>U,getAudioLevel:()=>L.current}),[j,F,U]),d.useEffect(()=>(m&&j(),()=>{F()}),[m]),r.jsx("canvas",{ref:C,width:s,height:i,className:b,style:{display:"block",...S},"aria-label":"Audio visualizer"})}),Ci=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},lg={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},cg={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-bg, #1a1a1a)",textSecondary:"var(--nice-text-secondary, #666)",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},dg={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-bg, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-bg, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Fc=d.forwardRef(function(t,n){const{userId:a,userName:s,userAvatarUrl:i,participants:o=[],rtcConfig:l,position:c="bottom-right",expanded:u=!0,onSignalingMessage:h,onMuteToggle:p,onLeave:f,onSpeakingChange:y,speakingThreshold:m=.1,theme:v="auto",className:x,style:g,zIndex:k=1e3}=t,b=d.useRef(null),S=d.useRef(null),M=d.useRef(new Map);d.useRef(new Map);const[R,N]=d.useState(!1),[C,w]=d.useState(!1),[O,$]=d.useState(!1),[E,_]=d.useState(u),U=d.useMemo(()=>v==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":v,[v])==="dark"?dg:cg;d.useEffect(()=>{const W=new _c(a,l);return W.onRemoteStream=(j,F)=>{let I=M.current.get(j);I||(I=new Audio,I.autoplay=!0,M.current.set(j,I)),I.srcObject=F},W.onSignalingMessage=j=>{h==null||h(j)},W.onPeerStateChange=(j,F)=>{F==="connected"&&w(!0)},b.current=W,W.initialize().then(()=>{var j;(j=S.current)==null||j.start()}),()=>{W.disconnect();const j=M.current;j.forEach(F=>{F.srcObject=null}),j.clear()}},[a,l,h]);const Z=d.useCallback(()=>{var j;const W=!R;N(W),(j=b.current)==null||j.setMuted(W),p==null||p(W)},[R,p]),A=d.useCallback(()=>{var W,j;(W=b.current)==null||W.disconnect(),(j=S.current)==null||j.stop(),w(!1),f==null||f()},[f]),q=d.useCallback(W=>{const j=W>m;j!==O&&($(j),y==null||y(a,j))},[m,O,a,y]),H=d.useCallback(async W=>{var j;await((j=b.current)==null?void 0:j.createOffer(W))},[]),re=d.useCallback(async W=>{var j;await((j=b.current)==null?void 0:j.handleSignalingMessage(W))},[]);d.useImperativeHandle(n,()=>({connectToPeer:H,handleSignalingMessage:re,toggleMute:Z,isMuted:()=>R,leave:A,getManager:()=>b.current}),[H,re,Z,R,A]);const D=({participant:W,isLocal:j,isSpeaking:F})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[r.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:U.hoverBg,border:`2px solid ${F?U.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:U.text,transition:"border-color 0.15s ease"},children:W.avatarUrl?r.jsx("img",{src:W.avatarUrl,alt:W.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):W.name.charAt(0).toUpperCase()}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsxs("div",{style:{color:U.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[W.name,j&&r.jsx("span",{style:{color:U.textSecondary,fontWeight:400},children:" (You)"})]})}),W.isMuted&&r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.mutedIcon,strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return E?r.jsxs("div",{className:x,style:{...lg,...Ci(c),backgroundColor:U.background,border:`1px solid ${U.border}`,zIndex:k,...g},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${U.border}`},children:[r.jsx("span",{style:{color:U.text,fontWeight:600},children:"Voice Chat"}),r.jsx("button",{onClick:()=>_(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:U.textSecondary,strokeWidth:"2",children:[r.jsx("polyline",{points:"4 14 10 14 10 20"}),r.jsx("polyline",{points:"20 10 14 10 14 4"}),r.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),r.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[r.jsx(D,{participant:{id:a,name:s,avatarUrl:i,isMuted:R},isLocal:!0,isSpeaking:O&&!R}),o.map(W=>r.jsx(D,{participant:W,isSpeaking:W.isSpeaking},W.id))]}),r.jsx(bs,{ref:S,mode:"bars",width:256,height:32,barCount:24,barColor:R?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:q,style:{borderRadius:4,opacity:R?.5:1}}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx("button",{onClick:Z,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:R?U.mutedBg:U.activeBg,color:R?U.mutedIcon:U.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":R?"Unmute":"Mute",children:R?r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),r.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),r.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):r.jsxs(r.Fragment,{children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),r.jsx("button",{onClick:A,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("polyline",{points:"16 17 21 12 16 7"}),r.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):r.jsx("div",{className:x,style:{position:"fixed",...Ci(c),zIndex:k,...g},children:r.jsxs("button",{onClick:()=>_(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:U.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:U.text,strokeWidth:"2",children:[r.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),r.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),o.length>0&&r.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:U.speakingRing,color:"var(--nice-bg, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:o.length+1})]})})});function ug(e,t){const n={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(n),{...e,operations:a,undoIndex:a.length-1}}function hg(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function pg(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function fg(e,t,n){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*n,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,u=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+u))}})}function mg(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],n=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of n){const i=n.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const zc={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function gg(e,t,n){const a=zc[n],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const u=Math.min(Math.abs(s-c),12-Math.abs(s-c));u<o&&(o=u,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function yg(e,t){switch(t.type){case"transpose":return e.map(n=>({...n,pitch:Math.max(0,Math.min(127,n.pitch+(t.params.semitones??0)))}));case"invert":{const n=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*n-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const n=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:n-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(n=>({...n,velocity:Math.max(1,Math.min(127,n.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function bg(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const xg={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},vg={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Bn;exports.ALL_EFFECTS=Al;exports.ALL_TEXTURES=po;exports.ARTNET_PORT=q0;exports.ASYMMETRIC_CAPS=ao;exports.ArpeggiatorPanel=Ui;exports.AudioEffectType=Tc;exports.AudioPitchAnalyzer=mo;exports.AudioPlaybackEngine=xm;exports.AudioRecorder=Ea;exports.AudioTimeline=Ta;exports.AutoSavePanel=Pi;exports.BarFillEditor=fo;exports.CCAutomationLaneEditor=zi;exports.CCLane=Ri;exports.CONTROLLER_PROFILES=Ul;exports.ChaseRunner=X0;exports.CollaboratorPermission=$c;exports.DEFAULT_ARP_CONFIG=ia;exports.DEFAULT_AUDIO_INPUT_SETTINGS=Il;exports.DEFAULT_BAR_FILL=Vt;exports.DEFAULT_CAP_STYLE=io;exports.DEFAULT_EMPTY_BAR_FILL=Lr;exports.DEFAULT_FONT_SETTINGS=Fr;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Dr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=_r;exports.DEFAULT_KARAOKE_SETTINGS=oo;exports.DEFAULT_PLAYER_BAR_STYLE=un;exports.DEFAULT_SEED_CONFIG=Dl;exports.DMXEngine=Ic;exports.DRUM_PATTERN_NAMES=Em;exports.DefaultScoringPresets=_a;exports.DmxChannelControl=ys;exports.DmxChannelType=Ft;exports.DmxEditor=Ac;exports.DmxOptionsControl=gs;exports.DmxSliderControl=Gn;exports.DynamicRuleEditor=hl;exports.DynamicRuleField=ot;exports.DynamicRuleOperator=lt;exports.EditorTrackProvider=Ia;exports.EditorUndoManager=gu;exports.FIXTURE_PROFILES=Ec;exports.GENERIC_PROFILE=cs;exports.GM_DRUM_MAP=vg;exports.GRADIENT_PRESETS=Yo;exports.GROOVE_TEMPLATES=ps;exports.GenericPlayer=Ya;exports.GenericPlayerControls=el;exports.GenericPlayerStage=tl;exports.GenericPlayerStageVisualizer=nl;exports.GenericPlaylist=sl;exports.GenericPlaylistItem=ns;exports.KARAOKE_FONT_OPTIONS=Jh;exports.KEY_MAPS=No;exports.KaraokeEditorManager=Qo;exports.KaraokeFormat=Xa;exports.KaraokeLyrics=Da;exports.KaraokePhaserRenderer=Jo;exports.KaraokeSummaryOverlay=Ka;exports.KaraokeTimeline=Va;exports.LANE_COLORS=An;exports.LAUNCH_CONTROL_PROFILE=Wl;exports.LAYER_COLORS=z0;exports.LFOPanel=qi;exports.MINILAB_PROFILE=Gl;exports.MPK_MINI_PROFILE=Bl;exports.MasterFXPanel=Ei;exports.MidiCCMapper=Lm;exports.ModeSwitcher=es;exports.NOTE_NAMES=Rm;exports.NiceArpeggiatorPanel=Ui;exports.NiceAudioEffectsRack=fm;exports.NiceAudioErrorBoundary=Zc;exports.NiceAudioInputPicker=bm;exports.NiceAudioPitchAnalyzer=mo;exports.NiceAudioStudio=Vd;exports.NiceAudioTimeline=Ta;exports.NiceAutoSavePanel=Pi;exports.NiceBarFillEditor=fo;exports.NiceCCAutomationLaneEditor=zi;exports.NiceCCLane=Ri;exports.NiceDMXTimeline=Q0;exports.NiceDmxChannelControl=ys;exports.NiceDmxEditor=Ac;exports.NiceDmxOptionsControl=gs;exports.NiceDmxSliderControl=Gn;exports.NiceDynamicRuleEditor=hl;exports.NiceEditorTrackProvider=Ia;exports.NiceGenericPlayer=Ya;exports.NiceGenericPlayerControls=el;exports.NiceGenericPlayerStage=tl;exports.NiceGenericPlayerStageVisualizer=nl;exports.NiceGenericPlaylist=sl;exports.NiceGenericPlaylistItem=ns;exports.NiceI18nProvider=Yc;exports.NiceKaraokeEditorManager=Qo;exports.NiceKaraokeLyrics=Da;exports.NiceKaraokeManager=_h;exports.NiceKaraokePhaserRenderer=Jo;exports.NiceKaraokeSelectionMode=Ko;exports.NiceKaraokeSessionJoin=Xh;exports.NiceKaraokeSetupPanel=Ho;exports.NiceKaraokeSongBrowser=Wh;exports.NiceKaraokeSummaryOverlay=Ka;exports.NiceKaraokeTimeline=Va;exports.NiceKaraokeUploader=Mo;exports.NiceLFOPanel=qi;exports.NiceLatencyCalibrator=qh;exports.NiceMasterFXPanel=Ei;exports.NiceModeSwitcher=es;exports.NiceMusicLibraryExplorer=Vp;exports.NiceNoteParticles=Tl;exports.NiceNoteRiver=Nl;exports.NicePadKaraokeOverlay=Ro;exports.NicePianoRoll=Na;exports.NicePlaylistBrowser=gl;exports.NicePlaylistDualPane=pl;exports.NicePlaylistGridView=xl;exports.NicePlaylistImportWizard=wl;exports.NicePlaylistList=is;exports.NicePlaylistOverview=vl;exports.NicePlaylistSearchBar=Sl;exports.NicePlaylistSidebar=bl;exports.NicePlaylistTagEditor=il;exports.NicePlaylistTrackList=as;exports.NiceRadioPlayer=ng;exports.NiceRecordingOptionsPanel=Ii;exports.NiceStageVisualizer=ts;exports.NiceStationBrowser=Dc;exports.NiceStepSequencerPanel=Vi;exports.NiceStreamingVisualizer=bs;exports.NiceUndoRedoPanel=Ai;exports.NiceVocalEffectsRack=gm;exports.NiceVocalPerformanceReport=Oh;exports.NiceVoiceChatOverlay=Fc;exports.NiceWaveform=Ra;exports.NiceYouTubePlayer=rl;exports.NiceZoomSnapControls=$a;exports.NoteParticles=Tl;exports.NoteRiver=Nl;exports.OVERLAY_PATTERNS=Nr;exports.OXYGEN25_PROFILE=Ol;exports.PLAYER_COLORS=Je;exports.PLAYER_COLOR_VARS=cr;exports.PROGRESSION_NAMES=Am;exports.PadNotePlayer=Ao;exports.PaneSide=ll;exports.PianoRoll=Na;exports.PlaylistBrowser=gl;exports.PlaylistDualPane=pl;exports.PlaylistGridView=xl;exports.PlaylistImportWizard=wl;exports.PlaylistList=is;exports.PlaylistOverview=vl;exports.PlaylistSearchBar=Sl;exports.PlaylistSidebar=bl;exports.PlaylistTagEditor=il;exports.PlaylistTrackList=as;exports.PlaylistType=rs;exports.RecordingOptionsPanel=Ii;exports.SACN_PORT=K0;exports.SCALE_INTERVALS=zc;exports.SCALE_NAMES=Pm;exports.SKEW_CAPS=so;exports.STANDARD_TUNINGS=xg;exports.SYMMETRIC_CAPS=Wa;exports.ShortcutManager=Rc;exports.SimpleSynth=Ll;exports.SortDirection=sn;exports.SortField=cl;exports.StageVisualizer=ts;exports.StepSequencerPanel=Vi;exports.StreamingVisualizer=bs;exports.TEXTURE_CATEGORIES=Ha;exports.TrackSource=kt;exports.UndoRedoPanel=Ai;exports.ViewMode=ol;exports.VocalEffectsEngine=El;exports.VoiceChatOverlay=Fc;exports.Waveform=Ra;exports.WebRTCAudioManager=_c;exports.YouTubePlayer=rl;exports.ZoomSnapControls=$a;exports.addEffectToLayer=Xm;exports.addMidiNote=t0;exports.analyzeAudioFileWithAlgorithm=d0;exports.applyGroove=y0;exports.applyGrooveTemplate=Cc;exports.applyHumanize=jc;exports.applyKaraokeDisplayVars=Ja;exports.applyMidiTransform=yg;exports.applySwing=wc;exports.arrow_L=zt;exports.arrow_R=Tt;exports.autoCorrelate=xo;exports.bracket_L=za;exports.bracket_R=no;exports.buildArpSequence=Bi;exports.buildLanes=To;exports.buildNoteDescriptors=Za;exports.buildPadNoteEvents=Po;exports.buildSegmentScores=vo;exports.canRedo=Zl;exports.canUndo=Yl;exports.chamfer_L=jr;exports.chamfer_R=dn;exports.clearMidiNotes=r0;exports.clearPattern=fc;exports.computeGrade=bg;exports.computeTheoreticalMax=Fo;exports.computeVocalPerformanceReport=Wo;exports.convertBrowserSongToKaraokeSongFile=Mh;exports.copyCCEvents=wa;exports.createAnalyserNode=xc;exports.createArpPattern=Gm;exports.createArtNetPacket=H0;exports.createBasslinePattern=Wm;exports.createCCHistory=ql;exports.createCompressorNode=Sc;exports.createDefaultLFO=Er;exports.createDefaultShortcuts=T0;exports.createDropZoneHandlers=_0;exports.createEmptyPattern=Ht;exports.createEmptyStep=ds;exports.createGainNode=vc;exports.createHiHatPattern=Bm;exports.createKickPattern=zm;exports.createLoopRegion=w0;exports.createSACNPacket=Y0;exports.createSnarePattern=Om;exports.createVocoderNode=kc;exports.createVoiceChatAudioContext=og;exports.cutCCEvents=Ql;exports.deleteCCEventsInRange=Jl;exports.deserializeLFO=nu;exports.deserializePattern=qm;exports.detectChord=mg;exports.downsampleAndQuantizePitchPoints=So;exports.drawGlossyBarOnCanvas=Rn;exports.drawTimeline=ua;exports.estimateLatencyMs=ko;exports.estimateLatencyMsFromRecording=Vo;exports.evaluateLFO=Pa;exports.evaluateLFOAsCC=Aa;exports.exportCCLane=nc;exports.extractBpmFromNotes=Xi;exports.findTextureByUrl=ih;exports.formatShortcut=$0;exports.generateArpEvents=su;exports.generatePlaceholderWaveform=m0;exports.generateSeed=zl;exports.generateUltrastarText=u0;exports.getActiveGradient=Xo;exports.getActiveLyrics=ku;exports.getActiveWords=wu;exports.getAlgorithmColor=jh;exports.getAlgorithmCssVar=Ch;exports.getAlgorithmLabel=wh;exports.getArpModes=Gi;exports.getArpRates=Wi;exports.getAudioContext=mn;exports.getAudioInputDevices=ig;exports.getAudioWorkletProcessorCode=yc;exports.getBackgroundUrl=kh;exports.getCachedImage=rh;exports.getCapStyleByName=Cn;exports.getComboMultiplier=Do;exports.getCoverUrl=Sh;exports.getGrooveTemplate=b0;exports.getGrooveTemplateNames=x0;exports.getLaneForPitch=$o;exports.getNextPlayerColor=pd;exports.getNextPlayerColorCss=fd;exports.getOverlayCanvasPattern=Pn;exports.getPatternByName=Mn;exports.getSACNMulticastAddress=Z0;exports.getScoringPreset=Ir;exports.getTexturePattern=Tn;exports.getVerseRatingLabel=Lo;exports.handleAddCCEvent=s0;exports.handleRedo=mu;exports.handleRemoveCCEvent=o0;exports.handleSelectCCLane=a0;exports.handleUndo=fu;exports.handleUpdateCCEvent=i0;exports.hexToHsl=Tr;exports.humanizeMidiNotes=k0;exports.hydrateKaraokeDisplayFromBackend=ep;exports.hydratePlayerKaraokeSettingsFromBackend=Lu;exports.hzToUltrastarPitch=Qi;exports.importCCLane=rc;exports.initKaraokeDisplaySettings=np;exports.instrumentPresets=vm;exports.isAudioContextRunning=Ni;exports.isInLoopRegion=M0;exports.isWebRTCSupported=sg;exports.loadAllKaraokeSettings=Du;exports.loadAudioWorkletModule=bc;exports.loadKaraokeDisplaySettings=Zo;exports.loadKaraokeSettings=Ua;exports.loadPlayerBarStyle=lo;exports.loadPlayerBarStyles=Fu;exports.loadRemoteScoringPresets=Pu;exports.makeClickReference=qo;exports.makeClipSelectionId=h0;exports.mergeWaveforms=f0;exports.midiSeedGenerator=Im;exports.midiToHz=ha;exports.normalizeHex=$r;exports.openAudioFilePicker=F0;exports.ornate_L=Ba;exports.ornate_R=Rr;exports.parseLyrics=vu;exports.parseNotes=qn;exports.parseUltraStarText=Co;exports.parseVersesWithSyllables=Zi;exports.parseVersesWithWords=Su;exports.parseVideoMetadata=bo;exports.pasteCCEvents=Xl;exports.pill_L=Ut;exports.pill_R=_t;exports.preloadTexture=qa;exports.preloadTextures=ah;exports.probeAudioFile=Nc;exports.pushCCState=Vl;exports.pushOperation=ug;exports.quantizeMidiNotes=v0;exports.quantizeNotes=fg;exports.quantizeStepInBeats=Mc;exports.quantizeStepInSeconds=fs;exports.randomizeVelocity=pc;exports.recordCCEvent=ec;exports.redoCC=Kl;exports.redoOperation=pg;exports.removeEffectFromLayer=Qm;exports.removeMidiNote=n0;exports.renderGlossyBarSvg=co;exports.resumeAudioContext=Bt;exports.reversePattern=uc;exports.sampleLFOForDisplay=Fi;exports.sampleLFOToCCEvents=_i;exports.saveKaraokeDisplaySettings=tp;exports.saveKaraokeSettings=Iu;exports.savePlayerBarStyle=_u;exports.scaleResult=Oo;exports.scaleTo10k=zo;exports.scoreNotesWithPitchPoints=_o;exports.selectCCEventsInRange=Dm;exports.serializeLFO=tu;exports.serializePattern=Um;exports.setLoopFromSelection=j0;exports.setProjectWithUndo=Ki;exports.setStepGate=oc;exports.setStepNote=sc;exports.setStepProbability=lc;exports.setStepVelocity=ic;exports.sharp_L=ln;exports.sharp_R=cn;exports.shield_L=Cr;exports.shield_R=to;exports.shiftPattern=hc;exports.shouldTrigger=gc;exports.skewTL_L=dr;exports.skewTL_R=da;exports.skewTR_L=ca;exports.skewTR_R=ur;exports.snapLoopToGrid=C0;exports.snapTimeToQuantize=ja;exports.snapToGrid=p0;exports.snapToScale=gg;exports.soft_L=Fa;exports.soft_R=eo;exports.stepDuration=us;exports.stepTimeOffset=mc;exports.syncDivisionToHz=Li;exports.tab_L=Oa;exports.tab_R=ro;exports.thinCCEvents=tc;exports.toTrack=jo;exports.toggleEffectBypass=Jm;exports.toggleStep=ac;exports.toggleStepSlide=cc;exports.transposePattern=dc;exports.undoCC=Hl;exports.undoOperation=hg;exports.updateEffectParams=e0;exports.useAudioWorklet=Zm;exports.useAutoSave=du;exports.useCCAutomation=Fm;exports.useCanPickSong=Zh;exports.useDMXAudioSync=eg;exports.useDMXEngine=J0;exports.useEditorTrack=xu;exports.useKaraokePitch=Io;exports.useKaraokeScoring=Bo;exports.useLocalPlaylists=ss;exports.useMPE=jm;exports.useMidiLearn=km;exports.useNiceTranslation=Te;exports.useOxygen25=Mm;exports.usePitchWorker=Hm;exports.usePlaybackEngine=uu;exports.useProjectCRUD=bu;exports.useRadioStream=Lc;exports.useRecording=hu;exports.useScoringWorker=Km;exports.useStepSequencer=Vm;exports.useWebMidi=Br;exports.useWorker=hs;exports.validateAudioFiles=ms;exports.wave_L=Mr;exports.wave_R=Ga;exports.waveformValue=Di;exports.wrapTimeInLoop=R0;
429
+ E`}}function v0(e,t){return`${e}:${t}`}function x0(e,t,r,a=1){if(t==="off")return e;const s=60/r;if(t==="beat")return Math.round(e/(s/a))*(s/a);if(t==="bar"){const i=s*4;return Math.round(e/i)*i}return e}function S0(e){return e.length===0?[]:e.flat()}function k0(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const ms=[{id:"mpc-60-tight",name:"MPC 60 Tight",stepsPerBar:16,timingOffsets:[0,.02,0,.01,0,.03,0,.01,0,.02,0,.01,0,.03,0,.01],velocityScales:[1.1,.85,.95,.8,1.05,.85,.9,.8,1.1,.85,.95,.8,1.05,.85,.9,.8],durationScales:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},{id:"mpc-60-swing",name:"MPC 60 Swing",stepsPerBar:16,timingOffsets:[0,.06,0,.04,0,.07,0,.04,0,.06,0,.04,0,.07,0,.04],velocityScales:[1.15,.7,.9,.75,1.1,.7,.85,.75,1.15,.7,.9,.75,1.1,.7,.85,.75],durationScales:[1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95,1.05,.9,1,.95]},{id:"hip-hop-lazy",name:"Hip-Hop Lazy",stepsPerBar:16,timingOffsets:[0,.04,.01,.05,0,.04,.02,.06,0,.04,.01,.05,0,.04,.02,.06],velocityScales:[1.2,.65,.85,.6,1.1,.65,.8,.6,1.2,.65,.85,.6,1.1,.65,.8,.6],durationScales:[1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9,1.1,1,1,.9]},{id:"funk-pocket",name:"Funk Pocket",stepsPerBar:16,timingOffsets:[0,-.01,.03,0,0,-.01,.04,0,0,-.01,.03,0,0,-.01,.04,0],velocityScales:[1.2,.9,.7,1.05,.85,.9,.7,1,1.15,.9,.7,1.05,.85,.9,.7,1],durationScales:[1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1,1,.95,1.1,1]},{id:"shuffle-blues",name:"Shuffle / Blues",stepsPerBar:8,timingOffsets:[0,.11,0,.11,0,.11,0,.11],velocityScales:[1.2,.8,1.1,.8,1.2,.8,1.1,.8],durationScales:[1.1,.8,1.1,.8,1.1,.8,1.1,.8]},{id:"reggaeton",name:"Reggaeton",stepsPerBar:16,timingOffsets:[0,0,0,.03,0,0,0,.03,0,0,0,.03,0,0,0,.03],velocityScales:[1.3,.6,.9,1.1,.7,.6,.9,1.1,1.3,.6,.9,1.1,.7,.6,.9,1.1],durationScales:[1,1,1,.9,1,1,1,.9,1,1,1,.9,1,1,1,.9]}];function w0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function Mc(e,t){return t.amount===0?e:e.map(r=>{const a=r.time/t.grid;if(Math.round(a)%2===1){const o=t.grid*t.amount*.5;return{...r,time:r.time+o}}return{...r}})}function Rc(e,t){const r=t.seed!=null?w0(t.seed):Math.random;return e.map(a=>{const s=(r()-.5)*2*t.timingAmount,i=Math.round((r()-.5)*2*t.velocityAmount),o=(r()-.5)*2*t.durationAmount;return{...a,time:Math.max(0,a.time+s),velocity:Math.max(1,Math.min(127,a.velocity+i)),duration:Math.max(.01,a.duration+o)}})}function Nc(e,t,r=1){const a=4/t.stepsPerBar;return e.map(s=>{const i=s.time/a,o=Math.round(i)%t.stepsPerBar,l=t.timingOffsets[o]*a*r,c=1+(t.velocityScales[o]-1)*r,d=1+(t.durationScales[o]-1)*r;return{...s,time:Math.max(0,s.time+l),velocity:Math.max(1,Math.min(127,Math.round(s.velocity*c))),duration:Math.max(.01,s.duration*d)}})}function C0(e,t){let r=[...e.map(a=>({...a}))];return t.template&&t.grooveStrength>0&&(r=Nc(r,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(r=Mc(r,t.swing)),t.humanize&&(r=Rc(r,t.humanize)),r}function j0(e){return ms.find(t=>t.id===e)}function M0(){return ms.map(({id:e,name:t})=>({id:e,name:t}))}function Tc(e){switch(e){case"1/4":return 1;case"1/8":return .5;case"1/16":return .25;case"1/32":return .125;case"1/4T":return 2/3;case"1/8T":return 1/3;case"1/16T":return 1/6}}function gs(e,t){return Tc(e)*60/t}function Ma(e,t,r){const a=gs(t,r);return Math.round(e/a)*a}function R0(e,t){const{value:r,bpm:a,strength:s=1,quantizeStarts:i=!0,quantizeDurations:o=!1}=t,l=gs(r,a);return e.map(c=>{let{start:d,duration:h}=c;if(i){const f=Math.round(d/l)*l;d=d+(f-d)*s}if(o){const f=Math.max(l,Math.round(h/l)*l);h=h+(f-h)*s}return d===c.start&&h===c.duration?c:{...c,start:d,duration:h}})}function N0(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function T0(e,t={}){const{timingRange:r=.02,velocityRange:a=10,seed:s}=t,i=s!=null?N0(s):Math.random;return e.map(o=>{const l=(i()*2-1)*r,c=Math.round((i()*2-1)*a);return{...o,start:Math.max(0,o.start+l),velocity:o.velocity!=null?Math.max(1,Math.min(127,(o.velocity??100)+c)):void 0}})}function $0(){return{start:0,end:0,enabled:!1}}function P0(e,t){return{...e<t?{start:e,end:t}:{start:t,end:e},enabled:!0}}function A0(e,t,r){return{start:Ma(e.start,t,r),end:Ma(e.end,t,r),enabled:e.enabled}}function E0(e,t){return t.enabled?e>=t.start&&e<=t.end:!1}function I0(e,t){if(!t.enabled||t.end<=t.start||e<t.start)return e;if(e>=t.end){const r=t.end-t.start;return t.start+(e-t.start)%r}return e}function Ra(e){return e.length===1?e.toLowerCase():e}function Cr(e){var r,a,s,i;const t=[];return(r=e.modifiers)!=null&&r.ctrl&&t.push("Ctrl"),(a=e.modifiers)!=null&&a.shift&&t.push("Shift"),(s=e.modifiers)!=null&&s.alt&&t.push("Alt"),(i=e.modifiers)!=null&&i.meta&&t.push("Meta"),t.push(Ra(e.key)),t.join("+")}function L0(e,t){var l,c,d,h;const r=Ra(e.key)===Ra(t.key),a=!!e.ctrlKey==!!((l=t.modifiers)!=null&&l.ctrl),s=!!e.shiftKey==!!((c=t.modifiers)!=null&&c.shift),i=!!e.altKey==!!((d=t.modifiers)!=null&&d.alt),o=!!e.metaKey==!!((h=t.modifiers)!=null&&h.meta);return r&&a&&s&&i&&o}class $c{constructor(){this.actions=new Map,this.activeScopes=new Set(["global"]),this.enabled=!0,this.listener=null}register(t){this.actions.set(t.id,{...t,enabled:t.enabled??!0})}unregister(t){this.actions.delete(t)}rebind(t,r){const a=this.actions.get(t);a&&(a.binding=r)}setActiveScopes(t){this.activeScopes.clear(),this.activeScopes.add("global");for(const r of t)this.activeScopes.add(r)}setEnabled(t){this.enabled=t}setActionEnabled(t,r){const a=this.actions.get(t);a&&(a.enabled=r)}findConflicts(){const t=[],r=[...this.actions.values()];for(let a=0;a<r.length;a++)for(let s=a+1;s<r.length;s++){const i=r[a],o=r[s];Cr(i.binding)===Cr(o.binding)&&(i.scope===o.scope||i.scope==="global"||o.scope==="global")&&t.push([i,o])}return t}getGrouped(){const t={};for(const r of this.actions.values())t[r.group]||(t[r.group]=[]),t[r.group].push(r);return t}getAll(){return[...this.actions.values()]}exportConfig(){return[...this.actions.values()].map(t=>({id:t.id,binding:t.binding}))}importConfig(t){for(const r of t)this.rebind(r.id,r.binding)}formatBinding(t){const r=this.actions.get(t);return r?Cr(r.binding):""}handleKeyDown(t){if(!this.enabled)return!1;for(const r of this.actions.values())if(r.enabled&&this.activeScopes.has(r.scope)&&L0(t,r.binding))return t.preventDefault(),t.stopPropagation(),r.callback(),!0;return!1}attach(){this.listener||(this.listener=t=>{const r=t.target;r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable||this.handleKeyDown(t)},window.addEventListener("keydown",this.listener,!0))}detach(){this.listener&&(window.removeEventListener("keydown",this.listener,!0),this.listener=null)}destroy(){this.detach(),this.actions.clear()}}function D0(e={}){const t=new $c,r=()=>{},a=[{id:"transport.play",label:"Play / Pause",group:"Transport",scope:"global",binding:{key:" "}},{id:"transport.stop",label:"Stop",group:"Transport",scope:"global",binding:{key:"Escape"}},{id:"transport.record",label:"Record",group:"Transport",scope:"global",binding:{key:"r",modifiers:{ctrl:!0}}},{id:"transport.rewind",label:"Rewind",group:"Transport",scope:"global",binding:{key:"Home"}},{id:"transport.forward",label:"Forward",group:"Transport",scope:"global",binding:{key:"End"}},{id:"transport.loopToggle",label:"Toggle Loop",group:"Transport",scope:"global",binding:{key:"l"}},{id:"edit.undo",label:"Undo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0}}},{id:"edit.redo",label:"Redo",group:"Edit",scope:"global",binding:{key:"z",modifiers:{ctrl:!0,shift:!0}}},{id:"edit.cut",label:"Cut",group:"Edit",scope:"editor",binding:{key:"x",modifiers:{ctrl:!0}}},{id:"edit.copy",label:"Copy",group:"Edit",scope:"editor",binding:{key:"c",modifiers:{ctrl:!0}}},{id:"edit.paste",label:"Paste",group:"Edit",scope:"editor",binding:{key:"v",modifiers:{ctrl:!0}}},{id:"edit.delete",label:"Delete",group:"Edit",scope:"editor",binding:{key:"Delete"}},{id:"edit.selectAll",label:"Select All",group:"Edit",scope:"editor",binding:{key:"a",modifiers:{ctrl:!0}}},{id:"edit.duplicate",label:"Duplicate",group:"Edit",scope:"editor",binding:{key:"d",modifiers:{ctrl:!0}}},{id:"view.zoomIn",label:"Zoom In",group:"View",scope:"global",binding:{key:"=",modifiers:{ctrl:!0}}},{id:"view.zoomOut",label:"Zoom Out",group:"View",scope:"global",binding:{key:"-",modifiers:{ctrl:!0}}},{id:"view.zoomFit",label:"Zoom to Fit",group:"View",scope:"global",binding:{key:"0",modifiers:{ctrl:!0}}},{id:"view.toggleMixer",label:"Toggle Mixer",group:"View",scope:"global",binding:{key:"m"}},{id:"view.togglePianoRoll",label:"Toggle Piano Roll",group:"View",scope:"global",binding:{key:"p"}},{id:"pianoRoll.quantize",label:"Quantize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"q"}},{id:"pianoRoll.humanize",label:"Humanize Selection",group:"Piano Roll",scope:"piano-roll",binding:{key:"h"}},{id:"pianoRoll.velocityUp",label:"Velocity +10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{shift:!0}}},{id:"pianoRoll.velocityDown",label:"Velocity -10",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{shift:!0}}},{id:"pianoRoll.octaveUp",label:"Octave Up",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowUp",modifiers:{ctrl:!0,shift:!0}}},{id:"pianoRoll.octaveDown",label:"Octave Down",group:"Piano Roll",scope:"piano-roll",binding:{key:"ArrowDown",modifiers:{ctrl:!0,shift:!0}}},{id:"timeline.split",label:"Split at Cursor",group:"Timeline",scope:"timeline",binding:{key:"s"}},{id:"timeline.mute",label:"Mute Track",group:"Timeline",scope:"timeline",binding:{key:"m",modifiers:{ctrl:!0}}},{id:"timeline.solo",label:"Solo Track",group:"Timeline",scope:"timeline",binding:{key:"s",modifiers:{ctrl:!0}}},{id:"timeline.addTrack",label:"Add Track",group:"Timeline",scope:"timeline",binding:{key:"t",modifiers:{ctrl:!0}}},{id:"mixer.resetFader",label:"Reset Fader",group:"Mixer",scope:"mixer",binding:{key:"0"}},{id:"mixer.bypassFx",label:"Bypass All FX",group:"Mixer",scope:"mixer",binding:{key:"b"}}];for(const s of a)t.register({...s,callback:e[s.id]??r});return t}function z0(e){return Cr(e)}const _0=["audio/mpeg","audio/wav","audio/ogg","audio/flac","audio/aac","audio/webm","audio/mp4","audio/x-m4a","audio/x-wav","audio/x-aiff","audio/aiff","audio/midi","audio/x-midi"],F0=["mp3","wav","ogg","flac","aac","m4a","webm","wma","aiff","aif","mid","midi","opus"],O0=500*1024*1024,B0=20;function Bt(e){const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""}function G0(e,t){return!!(e.type&&t.some(r=>e.type.startsWith(r.replace("*","")))||e.type.startsWith("audio/"))}function W0(e,t){const r=Bt(e.name);return r!==""&&t.includes(r)}function ys(e,t={}){const r=t.maxSize??O0,a=t.allowedTypes??_0,s=t.allowedExtensions??F0,i=t.maxFiles??B0,o=[],l=[];for(let c=0;c<e.length;c++){const d=e[c];if(c>=i){l.push({file:d,reason:"limit",message:`Exceeded maximum of ${i} files`});continue}if(d.size>r){l.push({file:d,reason:"size",message:`File exceeds ${Math.round(r/1024/1024)}MB limit`});continue}if(!G0(d,a)&&!W0(d,s)){l.push({file:d,reason:"type",message:`Unsupported file type: ${d.type||Bt(d.name)}`});continue}o.push(d)}return{valid:o,errors:l}}async function Pc(e){const t={file:e,name:e.name.replace(/\.[^.]+$/,""),extension:Bt(e.name),sizeBytes:e.size,mimeType:e.type||`audio/${Bt(e.name)}`};try{const r=await e.arrayBuffer(),s=await new OfflineAudioContext(1,1,44100).decodeAudioData(r);t.duration=s.duration,t.sampleRate=s.sampleRate,t.channels=s.numberOfChannels}catch{}return t}function U0(e){let t=0;return{onDragEnter:r=>{var a;r.preventDefault(),r.stopPropagation(),t++,t===1&&((a=e.onDragEnter)==null||a.call(e))},onDragOver:r=>{r.preventDefault(),r.stopPropagation(),(r instanceof DragEvent&&r.dataTransfer||"dataTransfer"in r&&r.dataTransfer)&&(r.dataTransfer.dropEffect="copy")},onDragLeave:r=>{var a;r.preventDefault(),r.stopPropagation(),t--,t===0&&((a=e.onDragLeave)==null||a.call(e))},onDrop:async r=>{var d,h;r.preventDefault(),r.stopPropagation(),t=0,(d=e.onDragLeave)==null||d.call(e);const a="dataTransfer"in r?r.dataTransfer:null;if(!((h=a==null?void 0:a.files)!=null&&h.length))return;const s=Array.from(a.files),{valid:i,errors:o}=ys(s,e.validation),l=[],c=[...o];for(const f of i)if(e.probe)try{l.push(await Pc(f))}catch{c.push({file:f,reason:"decode",message:"Failed to decode audio"})}else l.push({file:f,name:f.name.replace(/\.[^.]+$/,""),extension:Bt(f.name),sizeBytes:f.size,mimeType:f.type||`audio/${Bt(f.name)}`});e.onDrop({accepted:l,rejected:c})}}}function q0(e={}){return new Promise(t=>{const r=document.createElement("input");r.type="file",r.accept="audio/*,.mid,.midi",r.multiple=e.multiple??!0,r.onchange=async()=>{var l;if(!((l=r.files)!=null&&l.length)){t({accepted:[],rejected:[]});return}const a=Array.from(r.files),{valid:s,errors:i}=ys(a,e.validation),o=s.map(c=>({file:c,name:c.name.replace(/\.[^.]+$/,""),extension:Bt(c.name),sizeBytes:c.size,mimeType:c.type||`audio/${Bt(c.name)}`}));t({accepted:o,rejected:i})},r.click()})}var Ft=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(Ft||{}),Ac=(e=>(e[e.Equalizer=0]="Equalizer",e[e.Compressor=1]="Compressor",e[e.Reverb=2]="Reverb",e[e.Delay=3]="Delay",e[e.Distortion=4]="Distortion",e[e.Chorus=5]="Chorus",e[e.Flanger=6]="Flanger",e[e.Phaser=7]="Phaser",e))(Ac||{}),Ec=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(Ec||{});const V0=["var(--nice-success, #4caf50)","var(--nice-primary, #2196f3)","var(--nice-warning, #ff9800)","var(--nice-color-accent-pink, #e91e63)","var(--nice-accent, #9c27b0)","var(--nice-info, #00bcd4)","var(--nice-success, #8bc34a)","var(--nice-warning, #ffc107)"],Lr=["off","no function","brak"],H0=e=>e.segments.some(t=>t.isOff||Lr.some(r=>t.name.toLowerCase().includes(r))),K0=e=>e.segments.find(t=>t.isOff||Lr.some(r=>t.name.toLowerCase().includes(r))),Ic=e=>Math.floor((e.valueFrom+e.valueTo)/2),Y0=e=>{const t=K0(e);return t?Ic(t):0},X0=(e,t)=>e.segments.find(r=>t>=r.valueFrom&&t<=r.valueTo),Mn=(e,t=0,r=255)=>Math.max(t,Math.min(r,Math.round(e))),Un=({channel:e,value:t,onChange:r,onCommit:a,showDirectionHint:s})=>{const[i,o]=u.useState(Mn(t)),l=u.useMemo(()=>X0(e,i),[e,i]);u.useEffect(()=>o(Mn(t)),[t]);const c=d=>{const h=Mn(d);o(h),r(h),a==null||a(h)};return n.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[n.jsxs("strong",{children:[e.channel,". ",e.name]}),s&&l&&n.jsx("span",{style:{fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:l.name})]}),n.jsx("input",{type:"range",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),r(h)},onMouseUp:()=>a==null?void 0:a(i),onTouchEnd:()=>a==null?void 0:a(i),style:{width:"100%"}}),n.jsx("div",{style:{marginTop:6},children:n.jsx("input",{type:"number",min:0,max:255,value:i,onChange:d=>{const h=Mn(Number(d.target.value));o(h),r(h)},onBlur:()=>a==null?void 0:a(i),style:{width:80,padding:6,border:"1px solid var(--nice-border, #d1d5db)",borderRadius:6}})}),H0(e)&&n.jsx("button",{type:"button",onClick:()=>c(Y0(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)",background:"var(--nice-bg-secondary, #f9fafb)",cursor:"pointer"},children:"OFF"})]})},bs=({channel:e,value:t,onChange:r,onCommit:a})=>{const s=u.useMemo(()=>{const o=[...e.segments];return o.sort((l,c)=>{const d=(l.isOff?-1:0)+(Lr.some(f=>l.name.toLowerCase().includes(f))?-1:0),h=(c.isOff?-1:0)+(Lr.some(f=>c.name.toLowerCase().includes(f))?-1:0);return d!==h?d-h:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),o},[e]),i=o=>{const l=Ic(o);r(l),a==null||a(l)};return n.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid var(--nice-border, #e5e7eb)",borderRadius:8,padding:12},children:[n.jsxs("strong",{children:[e.channel,". ",e.name]}),n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:s.map((o,l)=>{const c=t>=o.valueFrom&&t<=o.valueTo;return n.jsx("button",{type:"button",onClick:()=>i(o),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid var(--nice-primary-hover, #2563eb)":"1px solid var(--nice-border, #d1d5db)",background:c?"var(--nice-primary-bg, #eff6ff)":"var(--nice-bg, #fff)",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${o.name} [${o.valueFrom}..${o.valueTo}]`,children:o.name},`${o.name}-${l}`)})})]})},vs=e=>{switch(e.channel.type){case Ft.Dimmer:case Ft.DimmerWithOff:return n.jsx(Un,{...e});case Ft.RotationWithOff:case Ft.RotationWithOffAndCcw:return n.jsx(Un,{...e,showDirectionHint:!0});case Ft.Options:return n.jsx(bs,{...e});default:return n.jsx(Un,{...e})}},sa=e=>Math.max(0,Math.min(255,Math.round(e))),Z0=[{target:".ntd-dmx-editor",titleKey:"tutorial.dmxEditor.intro.title",title:"DMX editor",contentKey:"tutorial.dmxEditor.intro.content",content:"Pick the FTDI device and port, then set each DMX channel’s value with the sliders to control your lighting fixtures live.",placement:"auto"}];function Lc({service:e,channels:t,onChannelChange:r,fixtures:a,...s}){return e?n.jsx(Q0,{service:e,...s}):n.jsx("div",{className:s.className,style:s.style,children:n.jsx("small",{children:"Provide a `service` prop (DmxService) to control hardware."})})}function Q0({service:e,pollInterval:t=500,className:r,style:a,tutorial:s}){const[i,o]=u.useState([]),[l,c]=u.useState(null),[d,h]=u.useState(()=>Array(513).fill(0)),[f,p]=u.useState(30),[y,m]=u.useState(0),[x,v]=u.useState(!1),g=u.useRef(null);u.useEffect(()=>{let I=!1;return e.getDevices().then(A=>{I||(o(A),A.length>0&&c(A[0]))}).catch(()=>{}),()=>{I=!0}},[e]),u.useEffect(()=>{if(g.current&&window.clearInterval(g.current),!(t<=0))return g.current=window.setInterval(async()=>{try{const I=await e.getState();Array.isArray(I.frontSnapshot)&&I.frontSnapshot.length>=513&&h(I.frontSnapshot.slice(0,513)),typeof I.fps=="number"&&p(I.fps),typeof I.startCode=="number"&&m(I.startCode)}catch{}},t),()=>{g.current&&window.clearInterval(g.current)}},[e,t]);const S=async()=>{l&&(await e.openPort(l.serialNumber||l.description),v(!0))},b=async()=>{await e.closePort(),v(!1)},k=async()=>{await e.blackout(),h(I=>{const A=[...I];for(let T=1;T<A.length;T++)A[T]=0;return A})},j=()=>e.configure(f,y),N=(I,A)=>{const T=sa(A);h(O=>{const E=[...O];return E[I]=T,E})},R=(I,A)=>e.setChannel(I,sa(A)),w=(l==null?void 0:l.deviceInfo)??null,M=u.useMemo(()=>{var I;return(I=w==null?void 0:w.channels)!=null&&I.length?w.channels:Array.from({length:16},(A,T)=>({channel:T+1,name:`Channel ${T+1}`,type:Ft.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[w]);return n.jsxs("div",{className:`ntd-dmx-editor ${r??""}`,style:{position:"relative",padding:16,display:"grid",gap:16,...a},children:[n.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:n.jsx(Se.NiceTutorialButton,{steps:Se.resolveTutorial(s,Z0)})}),n.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),n.jsx("select",{value:(l==null?void 0:l.serialNumber)||"",onChange:I=>c(i.find(A=>A.serialNumber===I.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"},children:i.map(I=>{var A,T;return n.jsxs("option",{value:I.serialNumber,children:[((A=I.deviceInfo)==null?void 0:A.manufacturer)??""," ",((T=I.deviceInfo)==null?void 0:T.model)??I.description," (",I.serialNumber||I.description,")"]},I.serialNumber||I.description)})}),w&&n.jsxs("div",{style:{marginTop:6,fontSize:12,color:"var(--nice-text-secondary, #6b7280)"},children:["Mode: ",n.jsx("b",{children:w.modeName}),", footprint: ",n.jsx("b",{children:w.footprint})]})]}),n.jsx("button",{onClick:S,disabled:!l||x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-success, #10b981)",background:"var(--nice-success-bg, #ecfdf5)",cursor:"pointer"},children:"Open port"}),n.jsx("button",{onClick:b,disabled:!x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-danger, #ef4444)",background:"var(--nice-danger-bg, #fef2f2)",cursor:"pointer"},children:"Close port"}),n.jsx("button",{onClick:k,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-border-color, #4b5563)",background:"var(--nice-bg-secondary, #f3f4f6)",cursor:"pointer"},children:"Blackout"})]}),n.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),n.jsx("input",{type:"number",min:10,max:44,value:f,onChange:I=>p(Number(I.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),n.jsxs("div",{children:[n.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),n.jsx("input",{type:"number",min:0,max:255,value:y,onChange:I=>m(sa(Number(I.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid var(--nice-border, #d1d5db)"}})]}),n.jsx("div",{children:n.jsx("button",{onClick:j,style:{padding:"10px 14px",borderRadius:8,border:"1px solid var(--nice-primary, #3b82f6)",background:"var(--nice-primary-bg, #eff6ff)",cursor:"pointer"},children:"Apply configuration"})})]}),n.jsxs("section",{children:[n.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),n.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:M.map(I=>n.jsx(vs,{channel:I,value:d[I.channel]??0,onChange:A=>N(I.channel,A),onCommit:A=>R(I.channel,A)},I.channel))})]})]})}const Dc=[{id:"generic-dimmer-1ch",name:"Generic Dimmer",manufacturer:"Generic",type:"dimmer",channelCount:1,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0}]},{id:"generic-rgb-3ch",name:"Generic RGB",manufacturer:"Generic",type:"rgb",channelCount:3,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0}]},{id:"generic-rgbw-4ch",name:"Generic RGBW",manufacturer:"Generic",type:"rgbw",channelCount:4,channels:[{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-rgbw-dimmer-5ch",name:"Generic RGBW+D",manufacturer:"Generic",type:"rgbw",channelCount:5,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0}]},{id:"generic-par-7ch",name:"Generic PAR 7ch",manufacturer:"Generic",type:"par",channelCount:7,channels:[{name:"Dimmer",type:"dimmer",defaultValue:255},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-moving-head-16ch",name:"Generic Moving Head 16ch",manufacturer:"Generic",type:"moving_head",channelCount:16,channels:[{name:"Pan",type:"pan",defaultValue:128,min:0,max:255},{name:"Pan Fine",type:"pan",defaultValue:0},{name:"Tilt",type:"tilt",defaultValue:128,min:0,max:255},{name:"Tilt Fine",type:"tilt",defaultValue:0},{name:"Pan/Tilt Speed",type:"speed",defaultValue:0},{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe",type:"strobe",defaultValue:0},{name:"Red",type:"color",defaultValue:0},{name:"Green",type:"color",defaultValue:0},{name:"Blue",type:"color",defaultValue:0},{name:"White",type:"color",defaultValue:0},{name:"Color Wheel",type:"function",defaultValue:0},{name:"Gobo",type:"gobo",defaultValue:0},{name:"Gobo Rotation",type:"speed",defaultValue:128},{name:"Prism",type:"function",defaultValue:0},{name:"Function",type:"function",defaultValue:0}]},{id:"generic-strobe-2ch",name:"Generic Strobe",manufacturer:"Generic",type:"strobe",channelCount:2,channels:[{name:"Dimmer",type:"dimmer",defaultValue:0},{name:"Strobe Speed",type:"strobe",defaultValue:0}]},{id:"generic-fog-2ch",name:"Generic Fog Machine",manufacturer:"Generic",type:"fog",channelCount:2,channels:[{name:"Output",type:"dimmer",defaultValue:0},{name:"Fan",type:"speed",defaultValue:128}]}];class zc{constructor(){this.universes=new Map,this.fixtures=new Map,this.profiles=new Map,this.outputCallback=null,this.running=!1,this.frameRate=44,this.intervalId=null,Dc.forEach(t=>this.profiles.set(t.id,t)),this.createUniverse(1,"Universe 1")}createUniverse(t,r){const a={id:String(t),name:r,channels:new Uint8Array(512)};return this.universes.set(t,a),a}getUniverse(t){return this.universes.get(t)}addFixture(t){this.fixtures.set(t.id,t)}removeFixture(t){this.fixtures.delete(t)}getFixture(t){return this.fixtures.get(t)}getAllFixtures(){return Array.from(this.fixtures.values())}getProfile(t){return this.profiles.get(t)}registerProfile(t){this.profiles.set(t.id,t)}setChannel(t,r,a){const s=this.universes.get(t);s&&r>=1&&r<=512&&(s.channels[r-1]=Math.max(0,Math.min(255,a)))}getChannel(t,r){const a=this.universes.get(t);return a&&r>=1&&r<=512?a.channels[r-1]:0}setFixtureValues(t,r){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);if(s)for(let i=0;i<Math.min(r.length,s.channelCount);i++)a.values[i]=r[i],this.setChannel(a.universe,a.startChannel+i,r[i])}setFixtureColor(t,r,a,s,i=0){const o=this.fixtures.get(t);if(!o)return;const l=this.profiles.get(o.profileId);if(!l)return;const c=[...o.values];l.channels.forEach((d,h)=>{d.name.toLowerCase().includes("red")?c[h]=r:d.name.toLowerCase().includes("green")?c[h]=a:d.name.toLowerCase().includes("blue")?c[h]=s:d.name.toLowerCase().includes("white")&&(c[h]=i)}),this.setFixtureValues(t,c)}setFixtureDimmer(t,r){const a=this.fixtures.get(t);if(!a)return;const s=this.profiles.get(a.profileId);s&&s.channels.forEach((i,o)=>{i.type==="dimmer"&&(a.values[o]=Math.max(0,Math.min(255,Math.round(r*255))),this.setChannel(a.universe,a.startChannel+o,a.values[o]))})}fadeFixture(t,r,a,s="linear"){return new Promise(i=>{const o=this.fixtures.get(t);if(!o){i();return}const l=[...o.values],c=performance.now(),d=()=>{const h=performance.now()-c,f=Math.min(1,h/a);let p=f;switch(s){case"ease-in":p=f*f;break;case"ease-out":p=1-(1-f)*(1-f);break;case"ease-in-out":p=f<.5?2*f*f:1-Math.pow(-2*f+2,2)/2;break}const y=l.map((m,x)=>{const v=r[x]??m;return Math.round(m+(v-m)*p)});this.setFixtureValues(t,y),f<1?requestAnimationFrame(d):i()};d()})}setOutputCallback(t){this.outputCallback=t}start(){this.running||(this.running=!0,this.intervalId=window.setInterval(()=>{this.sendOutput()},1e3/this.frameRate))}stop(){this.running=!1,this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}sendOutput(){this.outputCallback&&this.universes.forEach((t,r)=>{this.outputCallback(r,t.channels)})}blackout(){this.universes.forEach(t=>{t.channels.fill(0)}),this.fixtures.forEach(t=>{t.values.fill(0)})}fullOn(){this.fixtures.forEach(t=>{this.setFixtureDimmer(t.id,1)})}}const J0=6454,eg=new Uint8Array([65,114,116,45,78,101,116,0]);function tg(e,t){const r=new Uint8Array(18+t.length);return r.set(eg,0),r[8]=0,r[9]=80,r[10]=0,r[11]=14,r[12]=0,r[13]=0,r[14]=e&255,r[15]=e>>8&255,r[16]=t.length>>8&255,r[17]=t.length&255,r.set(t.slice(0,512),18),r}const ng=5568;function rg(e,t,r,a=100,s="Nice2Dev DMX"){const i=Math.min(t.length,512),o=126+i,l=new Uint8Array(o),c=new DataView(l.buffer);c.setUint16(0,16,!1),c.setUint16(2,0,!1);const d=[65,83,67,45,69,49,46,49,55,0,0,0];for(let m=0;m<d.length;m++)l[4+m]=d[m];const h=o-16;c.setUint16(16,28672|h&4095,!1),c.setUint32(18,4,!1);for(let m=0;m<16;m++)l[22+m]=m+1;const f=o-38;c.setUint16(38,28672|f&4095,!1),c.setUint32(40,2,!1);const p=new TextEncoder().encode(s.slice(0,63));l.set(p,44),l[108]=a,c.setUint16(109,0,!1),l[111]=r&255,l[112]=0,c.setUint16(113,e,!1);const y=i+11;return c.setUint16(115,28672|y&4095,!1),l[117]=2,l[118]=161,c.setUint16(119,0,!1),c.setUint16(121,1,!1),c.setUint16(123,i+1,!1),l[125]=0,l.set(t.slice(0,i),126),l}function ag(e){const t=e>>8&255,r=e&255;return`239.255.${t}.${r}`}class sg{constructor(t,r){this.config=t,this.scenes=r,this.currentStep=0,this.direction=1,this.isRunning=!1,this.timer=null,this.fadeStartTime=0,this.fadeFromValues=new Uint8Array(512),this.fadeToValues=new Uint8Array(512),this.onOutput=null}setOutputCallback(t){this.onOutput=t}start(){this.isRunning||(this.isRunning=!0,this.currentStep=this.config.direction==="backward"?this.config.steps.length-1:0,this.direction=this.config.direction==="backward"?-1:1,this.executeStep())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}executeStep(){var o;if(!this.isRunning)return;const t=this.config.steps[this.currentStep];if(!t)return;const r=this.scenes.get(t.sceneId);if(!r){this.advanceStep();return}const a=new Uint8Array(512);if(r.channels)for(const l of r.channels)l.channel>=1&&l.channel<=512&&(a[l.channel-1]=l.value);this.fadeFromValues.set(this.fadeToValues),this.fadeToValues.set(a),this.fadeStartTime=performance.now();const s=t.fadeTime/this.config.speed,i=t.holdTime/this.config.speed;s>0?this.runFade(s,()=>{var l;(l=this.onOutput)==null||l.call(this,this.fadeToValues),this.timer=setTimeout(()=>this.advanceStep(),i)}):((o=this.onOutput)==null||o.call(this,a),this.timer=setTimeout(()=>this.advanceStep(),i))}runFade(t,r){const a=performance.now(),s=new Uint8Array(512),i=()=>{var c;if(!this.isRunning)return;const o=performance.now()-a,l=Math.min(o/t,1);for(let d=0;d<512;d++)s[d]=Math.round(this.fadeFromValues[d]+(this.fadeToValues[d]-this.fadeFromValues[d])*l);(c=this.onOutput)==null||c.call(this,s),l<1?requestAnimationFrame(i):r()};requestAnimationFrame(i)}advanceStep(){if(!this.isRunning)return;const{steps:t,loop:r,direction:a}=this.config;if(this.currentStep+=this.direction,a==="bounce"){if(this.currentStep>=t.length?(this.direction=-1,this.currentStep=t.length-2):this.currentStep<0&&(this.direction=1,this.currentStep=1),this.currentStep<0||this.currentStep>=t.length){if(!r){this.stop();return}this.currentStep=0,this.direction=1}}else if(this.currentStep>=t.length||this.currentStep<0){if(!r){this.stop();return}this.currentStep=a==="backward"?t.length-1:0}this.executeStep()}}const ig=({engine:e,tracks:t=[],scenes:r=[],duration:a=3e5,currentTime:s=0,bpm:i=120,onTimeChange:o,onCueAdd:l,onCueUpdate:c,onCueDelete:d,onTrackAdd:h,onTrackUpdate:f,onPlay:p,onPause:y,onStop:m,className:x=""})=>{const[v,g]=u.useState(1),[S,b]=u.useState(0),[k,j]=u.useState(!1),[N,R]=u.useState(null),[w,M]=u.useState(null),[I,A]=u.useState(!0),[T,O]=u.useState(1e3),E=u.useRef(null),V=u.useRef(null),ee=u.useRef(0),z=u.useMemo(()=>.1*v,[v]),q=u.useCallback(C=>C*z,[z]),K=u.useCallback(C=>C/z,[z]),re=u.useCallback(C=>{if(!I)return C;const L=6e4/i;return Math.round(C/L)*L},[I,i]);u.useEffect(()=>{if(k){const C=performance.now(),L=s,B=()=>{const G=performance.now()-C,H=L+G;if(H>=a){j(!1),o==null||o(0),m==null||m();return}_(H),o==null||o(H),V.current=requestAnimationFrame(B)};V.current=requestAnimationFrame(B),p==null||p()}else V.current!==null&&(cancelAnimationFrame(V.current),V.current=null),y==null||y();return()=>{V.current!==null&&cancelAnimationFrame(V.current)}},[k,s,a,o,p,y,m]);const _=u.useCallback(C=>{t.forEach(L=>{L.muted||L.cues.forEach(B=>{const G=B.startTime,H=G+B.duration;if(C>=G&&C<H&&ee.current<G){const X=r.find(oe=>oe.id===B.sceneId);X&&X.fixtures.forEach(oe=>{B.fadeIn&&B.fadeIn>0?e.fadeFixture(oe.fixtureId,oe.values,B.fadeIn):e.setFixtureValues(oe.fixtureId,oe.values)})}if(ee.current<H&&C>=H){const X=r.find(oe=>oe.id===B.sceneId);X&&X.fixtures.forEach(oe=>{if(e.getFixture(oe.fixtureId)&&B.fadeOut&&B.fadeOut>0){const ne=new Array(oe.values.length).fill(0);e.fadeFixture(oe.fixtureId,ne,B.fadeOut)}})}})}),ee.current=C},[t,r,e]),U=C=>{const L=Math.floor(C/1e3),B=Math.floor(L/60),G=L%60,H=Math.floor(C%1e3/(1e3/30));return`${B}:${G.toString().padStart(2,"0")}:${H.toString().padStart(2,"0")}`},$=u.useCallback(C=>{if(!E.current)return;const L=E.current.getBoundingClientRect(),B=C.clientX-L.left+S,G=re(K(B));o==null||o(Math.max(0,Math.min(a,G)))},[S,K,re,a,o]),P=u.useCallback((C,L,B)=>{const G=t.find(oe=>oe.id===L),H=G==null?void 0:G.cues.find(oe=>oe.id===C);if(!H)return;const X=re(Math.max(0,H.startTime+K(B)));c==null||c({...H,startTime:X})},[t,K,re,c]),F=()=>{const C=6e4/i,L=Math.ceil(a/C),B=[];for(let G=0;G<=L;G++){const H=G*C,X=q(H),oe=G%4===0;B.push(n.jsx("div",{className:`nice-dmx-timeline__beat ${oe?"nice-dmx-timeline__beat--measure":""}`,style:{left:X},children:oe&&n.jsx("span",{className:"nice-dmx-timeline__beat-label",children:G/4+1})},G))}return B},D=(C,L)=>{const B=q(C.startTime),G=q(C.duration),H=r.find(X=>X.id===C.sceneId);return n.jsxs("div",{className:`nice-dmx-timeline__cue ${N===C.id?"nice-dmx-timeline__cue--selected":""}`,style:{left:B,width:G,backgroundColor:(H==null?void 0:H.color)||L.color||"var(--nice-accent, #8b5cf6)"},onClick:X=>{X.stopPropagation(),R(C.id)},draggable:!L.locked,onDragEnd:X=>{var le;const oe=(le=X.target.parentElement)==null?void 0:le.getBoundingClientRect();oe&&P(C.id,L.id,X.clientX-oe.left-B)},children:[n.jsx("span",{className:"nice-dmx-timeline__cue-name",children:C.name||(H==null?void 0:H.name)}),C.fadeIn&&C.fadeIn>0&&n.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--in",style:{width:q(C.fadeIn)}}),C.fadeOut&&C.fadeOut>0&&n.jsx("div",{className:"nice-dmx-timeline__cue-fade nice-dmx-timeline__cue-fade--out",style:{width:q(C.fadeOut)}})]},C.id)};return n.jsxs("div",{className:`nice-dmx-timeline ${x}`,children:[n.jsxs("div",{className:"nice-dmx-timeline__toolbar",children:[n.jsxs("div",{className:"nice-dmx-timeline__transport",children:[n.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(0),title:"Go to start","aria-label":"Go to start",children:n.jsx(W.NtdSkipBack,{size:14})}),n.jsx("button",{type:"button",onClick:()=>j(!k),title:k?"Pause":"Play","aria-label":k?"Pause":"Play",children:k?n.jsx(W.NtdPause,{size:14}):n.jsx(W.NtdPlay,{size:14})}),n.jsx("button",{type:"button",onClick:()=>{j(!1),o==null||o(0),e.blackout(),m==null||m()},title:"Stop","aria-label":"Stop",children:n.jsx(W.NtdStop,{size:14})})]}),n.jsx("div",{className:"nice-dmx-timeline__time",children:U(s)}),n.jsxs("div",{className:"nice-dmx-timeline__tools",children:[n.jsx("button",{type:"button",className:I?"active":"",onClick:()=>A(!I),title:"Snap to grid","aria-label":"Snap to grid",children:n.jsx(W.NtdGrid,{size:14})}),n.jsx("button",{type:"button",onClick:()=>g(Math.max(.25,v-.25)),title:"Zoom out",children:"−"}),n.jsxs("span",{className:"nice-dmx-timeline__zoom",children:[Math.round(v*100),"%"]}),n.jsx("button",{type:"button",onClick:()=>g(Math.min(4,v+.25)),title:"Zoom in",children:"+"})]}),n.jsxs("div",{className:"nice-dmx-timeline__bpm",children:[n.jsx("label",{children:"BPM:"}),n.jsx("span",{children:i})]}),n.jsx("button",{type:"button",className:"nice-dmx-timeline__blackout",onClick:()=>e.blackout(),title:"Blackout","aria-label":"Blackout",children:n.jsx(W.NtdMoon,{size:14})})]}),n.jsxs("div",{className:"nice-dmx-timeline__content",children:[n.jsxs("div",{className:"nice-dmx-timeline__headers",children:[t.map(C=>n.jsxs("div",{className:`nice-dmx-timeline__header ${w===C.id?"nice-dmx-timeline__header--selected":""}`,onClick:()=>M(C.id),children:[n.jsx("span",{className:"nice-dmx-timeline__track-color",style:{backgroundColor:C.color||"var(--nice-accent, #8b5cf6)"}}),n.jsx("span",{className:"nice-dmx-timeline__track-name",children:C.name}),n.jsxs("div",{className:"nice-dmx-timeline__track-controls",children:[n.jsx("button",{type:"button",className:C.muted?"active":"",onClick:L=>{L.stopPropagation(),f==null||f({...C,muted:!C.muted})},title:"Mute",children:"M"}),n.jsx("button",{type:"button",className:C.locked?"active":"",onClick:L=>{L.stopPropagation(),f==null||f({...C,locked:!C.locked})},title:"Lock","aria-label":"Lock",children:n.jsx(W.NtdLock,{size:14})})]})]},C.id)),n.jsx("button",{type:"button",className:"nice-dmx-timeline__add-track",onClick:()=>{h==null||h({id:`track-${Date.now()}`,name:`Track ${t.length+1}`,fixtureIds:[],cues:[]})},children:"+ Add Track"})]}),n.jsxs("div",{className:"nice-dmx-timeline__tracks",ref:E,onClick:$,onScroll:C=>b(C.currentTarget.scrollLeft),children:[n.jsx("div",{className:"nice-dmx-timeline__ruler",style:{width:q(a)},children:F()}),t.map(C=>n.jsx("div",{className:`nice-dmx-timeline__track ${C.muted?"nice-dmx-timeline__track--muted":""}`,style:{width:q(a)},children:C.cues.map(L=>D(L,C))},C.id)),n.jsx("div",{className:"nice-dmx-timeline__playhead",style:{left:q(s)}})]})]})]})};function og(){const[e]=u.useState(()=>new zc);return u.useEffect(()=>(e.start(),()=>e.stop()),[e]),e}function lg(e,t,r=120){const[a,s]=u.useState(0),i=u.useRef(0);return u.useEffect(()=>{if(!t)return;const o=60/r,l=()=>{const c=t.currentTime,d=Math.floor(c/o);d!==i.current&&(i.current=d,s(d))};return t.addEventListener("timeupdate",l),()=>t.removeEventListener("timeupdate",l)},[t,r]),{currentBeat:a}}const cg=[],dg=[{name:"Flat",bands:[{frequency:60,gain:0},{frequency:250,gain:0},{frequency:1e3,gain:0},{frequency:4e3,gain:0},{frequency:16e3,gain:0}]},{name:"Bass Boost",bands:[{frequency:60,gain:8},{frequency:250,gain:4},{frequency:1e3,gain:0},{frequency:4e3,gain:-2},{frequency:16e3,gain:-4}]},{name:"Treble Boost",bands:[{frequency:60,gain:-4},{frequency:250,gain:-2},{frequency:1e3,gain:0},{frequency:4e3,gain:4},{frequency:16e3,gain:8}]},{name:"Voice",bands:[{frequency:60,gain:-6},{frequency:250,gain:2},{frequency:1e3,gain:6},{frequency:4e3,gain:4},{frequency:16e3,gain:-2}]},{name:"Rock",bands:[{frequency:60,gain:4},{frequency:250,gain:2},{frequency:1e3,gain:-2},{frequency:4e3,gain:4},{frequency:16e3,gain:6}]}];function _c(){const[e,t]=u.useState(!1),[r,a]=u.useState(.8),[s,i]=u.useState(!1),[o,l]=u.useState(null),[c,d]=u.useState(null),[h,f]=u.useState(null),p=u.useRef(null),y=u.useRef(null),m=u.useRef(null),x=u.useRef(null),v=u.useRef([]),g=u.useRef(null),S=u.useRef(null),b=u.useCallback(()=>{if(y.current)return;const E=new AudioContext;y.current=E;const V=E.createGain();V.gain.value=r,x.current=V;const ee=E.createAnalyser();ee.fftSize=256,g.current=ee,V.connect(ee).connect(E.destination)},[]),k=u.useCallback(()=>{const E=p.current,V=y.current,ee=x.current;if(!E||!V||!ee||m.current)return;const z=V.createMediaElementSource(E);m.current=z,v.current.length>0?(z.connect(v.current[0]),v.current[v.current.length-1].connect(ee)):z.connect(ee)},[]),j=u.useCallback(()=>{var V;const E=p.current;!E||!S.current||(Gt(),b(),k(),((V=y.current)==null?void 0:V.state)==="suspended"&&y.current.resume(),E.play().catch(ee=>d(String(ee))))},[b,k]),N=u.useCallback(()=>{var E;(E=p.current)==null||E.pause()},[]),R=u.useCallback(()=>{e?N():j()},[e,j,N]),w=u.useCallback(E=>{const V=Math.max(0,Math.min(1,E));a(V),x.current&&(x.current.gain.value=V),p.current&&(p.current.volume=V)},[]),M=u.useCallback(E=>{S.current=E,d(null),l(null),i(!0),m.current&&(m.current.disconnect(),m.current=null),p.current||(p.current=new Audio,p.current.crossOrigin="anonymous",p.current.addEventListener("playing",()=>{t(!0),i(!1)}),p.current.addEventListener("pause",()=>t(!1)),p.current.addEventListener("waiting",()=>i(!0)),p.current.addEventListener("canplay",()=>i(!1)),p.current.addEventListener("error",()=>d("Failed to load stream"))),p.current.src=E.streamUrl,p.current.load(),l({genre:E.genre,bitrate:E.bitrate})},[]),I=u.useCallback(E=>{y.current||b();const ee=y.current;v.current.forEach(q=>q.disconnect());const z=E.bands.map(q=>{const K=ee.createBiquadFilter();return K.type="peaking",K.frequency.value=q.frequency,K.gain.value=q.gain,K.Q.value=q.Q??1.4,K});for(let q=0;q<z.length-1;q++)z[q].connect(z[q+1]);v.current=z,m.current&&x.current&&(m.current.disconnect(),m.current.connect(z[0]),z[z.length-1].connect(x.current)),f(E.name)},[b]),A=u.useCallback(()=>{v.current.forEach(E=>E.disconnect()),v.current=[],m.current&&x.current&&(m.current.disconnect(),m.current.connect(x.current)),f(null)},[]);return u.useEffect(()=>()=>{var E,V,ee;(E=p.current)==null||E.pause(),p.current=null,v.current.forEach(z=>z.disconnect()),(V=m.current)==null||V.disconnect(),(ee=y.current)==null||ee.close()},[]),[{isPlaying:e,volume:r,isBuffering:s,metadata:o,error:c,activePreset:h},{play:j,pause:N,toggle:R,setVolume:w,setStation:M,applyEQPreset:I,clearEQ:A}]}function Fc({stations:e,activeStationId:t,onSelect:r,onToggleFavorite:a,className:s}){const{t:i}=Te(),[o,l]=u.useState(""),[c,d]=u.useState(null),[h,f]=u.useState(!1),p=u.useMemo(()=>[...new Set(e.map(m=>m.genre).filter(Boolean))],[e]),y=u.useMemo(()=>e.filter(m=>{var x,v;if(h&&!m.isFavorite||c&&m.genre!==c)return!1;if(o){const g=o.toLowerCase();return m.name.toLowerCase().includes(g)||(((x=m.genre)==null?void 0:x.toLowerCase().includes(g))??!1)||(((v=m.country)==null?void 0:v.toLowerCase().includes(g))??!1)}return!0}),[e,o,c,h]);return n.jsxs("div",{className:`nice-station-browser${s?` ${s}`:""}`,children:[n.jsxs("div",{className:"nice-station-browser__toolbar",children:[n.jsx("input",{type:"text",className:"nice-station-browser__search",placeholder:(i==null?void 0:i("search_stations"))??"Search stations...",value:o,onChange:m=>l(m.target.value)}),n.jsxs("select",{className:"nice-station-browser__genre-filter",value:c??"",onChange:m=>d(m.target.value||null),children:[n.jsx("option",{value:"",children:(i==null?void 0:i("all_genres"))??"All Genres"}),p.map(m=>n.jsx("option",{value:m,children:m},m))]}),n.jsx("button",{className:`nice-station-browser__fav-toggle${h?" nice-station-browser__fav-toggle--active":""}`,onClick:()=>f(!h),title:(i==null?void 0:i("favorites"))??"Favorites","aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:n.jsx(W.NtdStar,{size:14,style:{color:"var(--nice-warning, #facc15)"}})})]}),n.jsxs("div",{className:"nice-station-browser__list",children:[y.map(m=>n.jsxs("div",{className:`nice-station-browser__item${m.id===t?" nice-station-browser__item--active":""}`,onClick:()=>r(m),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&r(m)},children:[m.logoUrl&&n.jsx("img",{className:"nice-station-browser__logo",src:m.logoUrl,alt:m.name,loading:"lazy"}),n.jsxs("div",{className:"nice-station-browser__info",children:[n.jsx("span",{className:"nice-station-browser__name",children:m.name}),m.genre&&n.jsx("span",{className:"nice-station-browser__genre",children:m.genre}),m.country&&n.jsx("span",{className:"nice-station-browser__country",children:m.country})]}),m.bitrate&&n.jsxs("span",{className:"nice-station-browser__bitrate",children:[m.bitrate,"kbps"]}),a&&n.jsx("button",{className:`nice-station-browser__fav${m.isFavorite?" nice-station-browser__fav--active":""}`,onClick:x=>{x.stopPropagation(),a(m.id)},"aria-label":(i==null?void 0:i("favorites"))??"Favorites",children:n.jsx(W.NtdStar,{size:14,style:{color:m.isFavorite?"var(--nice-warning, #facc15)":"var(--nice-text-muted)"}})})]},m.id)),y.length===0&&n.jsx("div",{className:"nice-station-browser__empty",children:(i==null?void 0:i("no_stations_found"))??"No stations found"})]})]})}function ug({stations:e=cg,initialStationId:t,autoPlay:r=!1,eqPresets:a=dg,onStationChange:s,onPlayingChange:i,onMetadata:o,onToggleFavorite:l,onRecordingStart:c,onRecordingStop:d,showBrowser:h=!0,showEqualizer:f=!1,showVisualizer:p=!1,showMetadataHistory:y=!1,showRecording:m=!1,showSleepTimer:x=!1,className:v,style:g}){var D,C;const{t:S}=Te(),[b,k]=_c(),[j,N]=u.useState(()=>t?e.find(L=>L.id===t)??null:null),[R,w]=u.useState(f),M=u.useRef(null),I=u.useRef(0),[A,T]=u.useState([]),[O,E]=u.useState(!1),V=u.useRef(null),ee=u.useRef([]),[z,q]=u.useState(0),K=u.useRef(null),[re,_]=u.useState(0),[U,$]=u.useState(null),P=u.useRef(null);u.useEffect(()=>{i==null||i(b.isPlaying)},[b.isPlaying,i]),u.useEffect(()=>{b.metadata&&(o==null||o(b.metadata),(b.metadata.title||b.metadata.artist)&&T(L=>[{time:new Date,meta:b.metadata},...L.slice(0,49)]))},[b.metadata,o]);const F=u.useCallback(L=>{N(L),k.setStation(L),s==null||s(L),r&&setTimeout(()=>k.play(),100)},[k,s,r]);return u.useEffect(()=>{if(t&&!j){const L=e.find(B=>B.id===t);L&&F(L)}},[t,e]),u.useEffect(()=>{if(!p||!M.current)return;const L=M.current,B=L.getContext("2d");if(!B)return;const G=()=>{I.current=requestAnimationFrame(G),B.clearRect(0,0,L.width,L.height);const H=B.createLinearGradient(0,L.height,0,0);if(H.addColorStop(0,Se.resolveCssColor("var(--nice-accent-tint-80, rgba(99, 102, 241, 0.8))",B.canvas)),H.addColorStop(.5,"rgba(168,85,247,0.6)"),H.addColorStop(1,"rgba(236,72,153,0.4)"),!b.isPlaying){const ne=L.width/32;for(let Z=0;Z<32;Z++){const Y=4+Math.sin(Date.now()/1e3+Z*.3)*3;B.fillStyle=H,B.fillRect(Z*ne+1,L.height-Y,ne-2,Y)}return}const X=32,oe=L.width/X;for(let le=0;le<X;le++){const ne=le/X,Y=(Math.sin(Date.now()/200+le*.5)*.3+.5)*L.height*(1-ne*.5)*(.5+Math.random()*.5);B.fillStyle=H,B.fillRect(le*oe+1,L.height-Y,oe-2,Y)}};return G(),()=>cancelAnimationFrame(I.current)},[p,b.isPlaying]),u.useCallback(()=>{if(b.isPlaying)try{const B=new AudioContext().createMediaStreamDestination();ee.current=[];const G=new MediaRecorder(B.stream,{mimeType:"audio/webm"});G.ondataavailable=H=>{H.data.size>0&&ee.current.push(H.data)},G.onstop=()=>{const H=new Blob(ee.current,{type:"audio/webm"});d==null||d(H),q(0),K.current&&window.clearInterval(K.current)},G.start(1e3),V.current=G,E(!0),q(0),K.current=window.setInterval(()=>{q(H=>H+1)},1e3),c==null||c()}catch{}},[b.isPlaying,c,d]),u.useCallback(()=>{V.current&&O&&(V.current.stop(),E(!1),K.current&&window.clearInterval(K.current))},[O]),u.useCallback(L=>{P.current&&window.clearInterval(P.current),_(L),$(L*60),P.current=window.setInterval(()=>{$(B=>!B||B<=1?(P.current&&window.clearInterval(P.current),P.current=null,k.pause(),null):B-1)},1e3)},[k]),u.useCallback(()=>{P.current&&window.clearInterval(P.current),P.current=null,$(null),_(0)},[]),u.useEffect(()=>()=>{K.current&&window.clearInterval(K.current),P.current&&window.clearInterval(P.current),cancelAnimationFrame(I.current)},[]),n.jsxs("div",{className:`nice-radio-player${v?` ${v}`:""}`,style:g,children:[n.jsx("div",{className:"nice-radio-player__now-playing",children:j?n.jsxs(n.Fragment,{children:[j.logoUrl&&n.jsx("img",{className:"nice-radio-player__cover",src:j.logoUrl,alt:j.name}),n.jsxs("div",{className:"nice-radio-player__info",children:[n.jsx("span",{className:"nice-radio-player__station-name",children:j.name}),((D=b.metadata)==null?void 0:D.title)&&n.jsx("span",{className:"nice-radio-player__track",children:b.metadata.artist?`${b.metadata.artist} — ${b.metadata.title}`:b.metadata.title}),((C=b.metadata)==null?void 0:C.genre)&&n.jsx("span",{className:"nice-radio-player__genre",children:b.metadata.genre}),b.isBuffering&&n.jsx("span",{className:"nice-radio-player__buffering",children:(S==null?void 0:S("buffering"))??"Buffering..."})]})]}):n.jsx("div",{className:"nice-radio-player__placeholder",children:(S==null?void 0:S("select_station"))??"Select a station"})}),n.jsxs("div",{className:"nice-radio-player__controls",children:[n.jsx("button",{className:"nice-radio-player__play-btn",onClick:k.toggle,disabled:!j,"aria-label":b.isPlaying?"Pause":"Play",children:b.isPlaying?n.jsx(W.NtdPause,{size:16}):n.jsx(W.NtdPlay,{size:16})}),n.jsxs("div",{className:"nice-radio-player__volume",children:[n.jsx("span",{className:"nice-radio-player__volume-icon","aria-hidden":"true",children:n.jsx(W.NtdVolume,{size:16})}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:b.volume,onChange:L=>k.setVolume(parseFloat(L.target.value)),className:"nice-radio-player__volume-slider","aria-label":"Volume"})]}),n.jsx("button",{className:`nice-radio-player__eq-btn${R?" nice-radio-player__eq-btn--active":""}`,onClick:()=>w(!R),title:"Equalizer",children:"EQ"})]}),b.error&&n.jsx("div",{className:"nice-radio-player__error",children:b.error}),R&&n.jsx("div",{className:"nice-radio-player__equalizer",children:n.jsxs("div",{className:"nice-radio-player__eq-presets",children:[a.map(L=>n.jsx("button",{className:`nice-radio-player__eq-preset${b.activePreset===L.name?" nice-radio-player__eq-preset--active":""}`,onClick:()=>k.applyEQPreset(L),children:L.name},L.name)),b.activePreset&&n.jsx("button",{className:"nice-radio-player__eq-preset",onClick:k.clearEQ,children:(S==null?void 0:S("clear"))??"Clear"})]})}),h&&n.jsx(Fc,{stations:e,activeStationId:j==null?void 0:j.id,onSelect:F})]})}const hg=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],pg={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,channelCount:1};class Oc{constructor(t,r={}){this.localStream=null,this.peers=new Map,this.onRemoteStream=null,this.onPeerStateChange=null,this.onSignalingMessage=null,this.localUserId=t,this.config={iceServers:r.iceServers??hg,audioConstraints:{...pg,echoCancellation:r.echoCancellation??!0,noiseSuppression:r.noiseSuppression??!0,autoGainControl:r.autoGainControl??!0}}}async initialize(){return this.localStream?this.localStream:(this.localStream=await navigator.mediaDevices.getUserMedia({audio:this.config.audioConstraints,video:!1}),this.localStream)}getLocalStream(){return this.localStream}getPeerIds(){return Array.from(this.peers.keys())}getPeerState(t){var r;return((r=this.peers.get(t))==null?void 0:r.state)??null}async createOffer(t){if(!this.localStream)throw new Error("WebRTCAudioManager not initialized. Call initialize() first.");const r=this.createPeerConnection(t),a=await r.createOffer();await r.setLocalDescription(a),this.sendSignalingMessage({type:"offer",from:this.localUserId,to:t,payload:a})}async handleSignalingMessage(t){if(t.to===this.localUserId)switch(t.type){case"offer":await this.handleOffer(t.from,t.payload);break;case"answer":await this.handleAnswer(t.from,t.payload);break;case"ice-candidate":await this.handleIceCandidate(t.from,t.payload);break;case"leave":this.removePeer(t.from);break}}removePeer(t){const r=this.peers.get(t);r&&(r.pc.close(),this.peers.delete(t))}disconnect(){for(const t of this.peers.keys())this.sendSignalingMessage({type:"leave",from:this.localUserId,to:t,payload:null});for(const t of this.peers.values())t.pc.close();this.peers.clear(),this.localStream&&(this.localStream.getTracks().forEach(t=>t.stop()),this.localStream=null)}setMuted(t){this.localStream&&this.localStream.getAudioTracks().forEach(r=>{r.enabled=!t})}isMuted(){if(!this.localStream)return!0;const t=this.localStream.getAudioTracks()[0];return t?!t.enabled:!0}createPeerConnection(t){const r=new RTCPeerConnection({iceServers:this.config.iceServers}),a={id:t,pc:r,remoteStream:null,state:r.connectionState};return this.peers.set(t,a),this.localStream&&this.localStream.getTracks().forEach(s=>{r.addTrack(s,this.localStream)}),r.onicecandidate=s=>{s.candidate&&this.sendSignalingMessage({type:"ice-candidate",from:this.localUserId,to:t,payload:s.candidate.toJSON()})},r.ontrack=s=>{var o;const[i]=s.streams;i&&(a.remoteStream=i,(o=this.onRemoteStream)==null||o.call(this,t,i))},r.onconnectionstatechange=()=>{var s;a.state=r.connectionState,(s=this.onPeerStateChange)==null||s.call(this,t,r.connectionState),(r.connectionState==="failed"||r.connectionState==="disconnected")&&this.removePeer(t)},r}async handleOffer(t,r){this.localStream||await this.initialize();const a=this.createPeerConnection(t);await a.setRemoteDescription(new RTCSessionDescription(r));const s=await a.createAnswer();await a.setLocalDescription(s),this.sendSignalingMessage({type:"answer",from:this.localUserId,to:t,payload:s})}async handleAnswer(t,r){const a=this.peers.get(t);a&&await a.pc.setRemoteDescription(new RTCSessionDescription(r))}async handleIceCandidate(t,r){const a=this.peers.get(t);a&&r&&await a.pc.addIceCandidate(new RTCIceCandidate(r))}sendSignalingMessage(t){var r;(r=this.onSignalingMessage)==null||r.call(this,t)}}function fg(){var e;return!!(typeof window<"u"&&window.RTCPeerConnection&&((e=navigator.mediaDevices)!=null&&e.getUserMedia))}async function mg(){return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput")}function gg(){return new AudioContext({sampleRate:48e3,latencyHint:"interactive"})}const xs=u.forwardRef(function(t,r){const{mode:a="bars",width:s=300,height:i=100,barCount:o=32,barColor:l="var(--nice-primary, #3b82f6)",backgroundColor:c="transparent",fftSize:d=256,smoothing:h=.8,minDecibels:f=-90,maxDecibels:p=-10,deviceId:y,autoStart:m=!1,onStart:x,onStop:v,onAudioLevel:g,onError:S,className:b,style:k,barBorderRadius:j=2,barGap:N=2,lineWidth:R=2}=t,w=u.useRef(null),M=u.useRef(null),I=u.useRef(null),A=u.useRef(null),T=u.useRef(0),O=u.useRef(null),E=u.useRef(0),[V,ee]=u.useState(!1),z=Array.isArray(l)?l.join("|"):l,q=u.useMemo(()=>z.split("|").map(C=>Se.resolveCssColor(C,w.current)),[z]),K=u.useCallback((C,L,B=!0)=>{const G=B?C.createLinearGradient(0,i,0,0):C.createLinearGradient(0,0,s,0);return L.forEach((H,X)=>{G.addColorStop(X/(L.length-1),H)}),G},[s,i]),re=u.useCallback((C,L)=>{const G=(s-(o-1)*N)/o,H=Math.floor(L.length/o),X=q,oe=X.length>1?K(C,X):X[0];C.fillStyle=oe;for(let le=0;le<o;le++){const Z=L[le*H]/255*i,Y=le*(G+N),se=i-Z;j>0?(C.beginPath(),C.roundRect(Y,se,G,Z,j),C.fill()):C.fillRect(Y,se,G,Z)}},[o,q,N,j,s,i,K]),_=u.useCallback((C,L)=>{const B=i/2,H=(s-(o-1)*N)/o,X=Math.floor(L.length/o),oe=q,le=oe.length>1?K(C,oe):oe[0];C.fillStyle=le;for(let ne=0;ne<o;ne++){const Y=L[ne*X]/255*B,se=ne*(H+N);j>0?(C.beginPath(),C.roundRect(se,B-Y,H,Y,j),C.fill(),C.beginPath(),C.roundRect(se,B,H,Y,j),C.fill()):(C.fillRect(se,B-Y,H,Y),C.fillRect(se,B,H,Y))}},[o,q,N,j,s,i,K]),U=u.useCallback((C,L)=>{const B=q;C.strokeStyle=B.length>1?K(C,B,!1):B[0],C.lineWidth=R,C.lineCap="round",C.lineJoin="round",C.beginPath();const G=s/L.length;let H=0;for(let X=0;X<L.length;X++){const le=L[X]/128*i/2;X===0?C.moveTo(H,le):C.lineTo(H,le),H+=G}C.stroke()},[q,R,s,i,K]),$=u.useCallback((C,L)=>{const B=s/2,G=i/2,H=Math.min(s,i)/3,X=q;C.strokeStyle=X.length>1?K(C,X):X[0],C.lineWidth=R;const oe=Math.floor(L.length/64),le=Math.PI*2/64;C.beginPath();for(let ne=0;ne<64;ne++){const Z=L[ne*oe]/255,Y=H+Z*H*.5,se=ne*le-Math.PI/2,ae=B+Math.cos(se)*Y,ue=G+Math.sin(se)*Y;ne===0?C.moveTo(ae,ue):C.lineTo(ae,ue)}C.closePath(),C.stroke()},[q,R,s,i,K]),P=u.useCallback(()=>{const C=w.current,L=I.current,B=O.current;if(!C||!L||!B)return;const G=C.getContext("2d");if(!G)return;a==="waveform"?L.getByteTimeDomainData(B):L.getByteFrequencyData(B);let H=0;for(let X=0;X<B.length;X++)H+=B[X];switch(E.current=H/(B.length*255),g==null||g(E.current),G.clearRect(0,0,s,i),c!=="transparent"&&(G.fillStyle=Se.resolveCssColor(c,G.canvas),G.fillRect(0,0,s,i)),a){case"bars":re(G,B);break;case"mirror-bars":_(G,B);break;case"waveform":U(G,B);break;case"circle":$(G,B);break}T.current=requestAnimationFrame(P)},[a,s,i,c,re,_,U,$,g]),F=u.useCallback(async()=>{try{if(V)return;const C=await navigator.mediaDevices.getUserMedia({audio:y?{deviceId:{exact:y}}:!0,video:!1});A.current=C;const L=new AudioContext;M.current=L;const B=L.createMediaStreamSource(C),G=L.createAnalyser();G.fftSize=d,G.smoothingTimeConstant=h,G.minDecibels=f,G.maxDecibels=p,B.connect(G),I.current=G,O.current=new Uint8Array(G.frequencyBinCount),ee(!0),x==null||x(),P()}catch(C){S==null||S(C instanceof Error?C:new Error(String(C)))}},[V,y,d,h,f,p,x,S,P]),D=u.useCallback(()=>{cancelAnimationFrame(T.current),A.current&&(A.current.getTracks().forEach(L=>L.stop()),A.current=null),M.current&&(M.current.close(),M.current=null),I.current=null,O.current=null,E.current=0,ee(!1),v==null||v();const C=w.current;if(C){const L=C.getContext("2d");L&&(L.clearRect(0,0,s,i),c!=="transparent"&&(L.fillStyle=Se.resolveCssColor(c,L.canvas),L.fillRect(0,0,s,i)))}},[s,i,c,v]);return u.useImperativeHandle(r,()=>({start:F,stop:D,isCapturing:()=>V,getAudioLevel:()=>E.current}),[F,D,V]),u.useEffect(()=>(m&&F(),()=>{D()}),[m]),n.jsx("canvas",{ref:w,width:s,height:i,className:b,style:{display:"block",...k},"aria-label":"Audio visualizer"})}),ji=e=>{switch(e){case"top-left":return{top:16,left:16};case"top-right":return{top:16,right:16};case"bottom-left":return{bottom:16,left:16};case"bottom-right":default:return{bottom:16,right:16}}},yg={position:"fixed",display:"flex",flexDirection:"column",gap:8,padding:12,borderRadius:12,boxShadow:"0 4px 20px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,minWidth:200,maxWidth:280,transition:"all 0.2s ease"},bg={background:"var(--nice-overlay-light-95, rgba(255, 255, 255, 0.95))",text:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",textSecondary:"var(--nice-overlay-60, rgba(0, 0, 0, 0.6))",border:"var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-bg, #fee2e2)",mutedIcon:"var(--nice-danger, #ef4444)",activeBg:"var(--nice-success-bg, #dcfce7)",activeIcon:"var(--nice-success, #22c55e)",hoverBg:"var(--nice-overlay-5, rgba(0, 0, 0, 0.05))"},vg={background:"var(--nice-overlay-90, rgba(30, 30, 30, 0.95))",text:"var(--nice-text-on-primary, #fff)",textSecondary:"var(--nice-text-muted, #a0a0a0)",border:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))",speakingRing:"var(--nice-success, #22c55e)",mutedBg:"var(--nice-danger-dark, #7f1d1d)",mutedIcon:"var(--nice-danger-light, #fca5a5)",activeBg:"var(--nice-success, #14532d)",activeIcon:"var(--nice-success-light, #86efac)",hoverBg:"var(--nice-overlay-light-10, rgba(255, 255, 255, 0.1))"},Bc=u.forwardRef(function(t,r){const{userId:a,userName:s,userAvatarUrl:i,participants:o=[],rtcConfig:l,position:c="bottom-right",expanded:d=!0,onSignalingMessage:h,onMuteToggle:f,onLeave:p,onSpeakingChange:y,speakingThreshold:m=.1,theme:x="auto",className:v,style:g,zIndex:S=1e3}=t,b=u.useRef(null),k=u.useRef(null),j=u.useRef(new Map);u.useRef(new Map);const[N,R]=u.useState(!1),[w,M]=u.useState(!1),[I,A]=u.useState(!1),[T,O]=u.useState(d),V=u.useMemo(()=>x==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":x,[x])==="dark"?vg:bg;u.useEffect(()=>{const U=new Oc(a,l);return U.onRemoteStream=($,P)=>{let F=j.current.get($);F||(F=new Audio,F.autoplay=!0,j.current.set($,F)),F.srcObject=P},U.onSignalingMessage=$=>{h==null||h($)},U.onPeerStateChange=($,P)=>{P==="connected"&&M(!0)},b.current=U,U.initialize().then(()=>{var $;($=k.current)==null||$.start()}),()=>{U.disconnect();const $=j.current;$.forEach(P=>{P.srcObject=null}),$.clear()}},[a,l,h]);const ee=u.useCallback(()=>{var $;const U=!N;R(U),($=b.current)==null||$.setMuted(U),f==null||f(U)},[N,f]),z=u.useCallback(()=>{var U,$;(U=b.current)==null||U.disconnect(),($=k.current)==null||$.stop(),M(!1),p==null||p()},[p]),q=u.useCallback(U=>{const $=U>m;$!==I&&(A($),y==null||y(a,$))},[m,I,a,y]),K=u.useCallback(async U=>{var $;await(($=b.current)==null?void 0:$.createOffer(U))},[]),re=u.useCallback(async U=>{var $;await(($=b.current)==null?void 0:$.handleSignalingMessage(U))},[]);u.useImperativeHandle(r,()=>({connectToPeer:K,handleSignalingMessage:re,toggleMute:ee,isMuted:()=>N,leave:z,getManager:()=>b.current}),[K,re,ee,N,z]);const _=({participant:U,isLocal:$,isSpeaking:P})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[n.jsx("div",{style:{width:32,height:32,borderRadius:"50%",backgroundColor:V.hoverBg,border:`2px solid ${P?V.speakingRing:"transparent"}`,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:V.text,transition:"border-color 0.15s ease"},children:U.avatarUrl?n.jsx("img",{src:U.avatarUrl,alt:U.name,style:{width:"100%",height:"100%",objectFit:"cover"}}):U.name.charAt(0).toUpperCase()}),n.jsx("div",{style:{flex:1,minWidth:0},children:n.jsxs("div",{style:{color:V.text,fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[U.name,$&&n.jsx("span",{style:{color:V.textSecondary,fontWeight:400},children:" (You)"})]})}),U.isMuted&&n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:V.mutedIcon,strokeWidth:"2",children:[n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),n.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),n.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})]});return T?n.jsxs("div",{className:v,style:{...yg,...ji(c),backgroundColor:V.background,border:`1px solid ${V.border}`,zIndex:S,...g},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:8,borderBottom:`1px solid ${V.border}`},children:[n.jsx("span",{style:{color:V.text,fontWeight:600},children:"Voice Chat"}),n.jsx("button",{onClick:()=>O(!1),style:{background:"none",border:"none",cursor:"pointer",padding:4,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:4},"aria-label":"Collapse",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:V.textSecondary,strokeWidth:"2",children:[n.jsx("polyline",{points:"4 14 10 14 10 20"}),n.jsx("polyline",{points:"20 10 14 10 14 4"}),n.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})]}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[n.jsx(_,{participant:{id:a,name:s,avatarUrl:i,isMuted:N},isLocal:!0,isSpeaking:I&&!N}),o.map(U=>n.jsx(_,{participant:U,isSpeaking:U.isSpeaking},U.id))]}),n.jsx(xs,{ref:k,mode:"bars",width:256,height:32,barCount:24,barColor:N?"var(--nice-text-muted, #9ca3af)":["var(--nice-primary, #3b82f6)","var(--nice-accent, #8b5cf6)"],barGap:3,barBorderRadius:2,autoStart:!1,onAudioLevel:q,style:{borderRadius:4,opacity:N?.5:1}}),n.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[n.jsx("button",{onClick:ee,style:{flex:1,padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:N?V.mutedBg:V.activeBg,color:N?V.mutedIcon:V.activeIcon,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":N?"Unmute":"Mute",children:N?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),n.jsx("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6"}),n.jsx("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Muted"]}):n.jsxs(n.Fragment,{children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),n.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),"Mic On"]})}),n.jsx("button",{onClick:z,style:{padding:"8px 12px",borderRadius:8,border:"none",backgroundColor:"var(--nice-danger-bg, #fef2f2)",color:"var(--nice-danger-dark, #dc2626)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:500,fontSize:13,transition:"all 0.15s ease"},"aria-label":"Leave voice chat",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]})]}):n.jsx("div",{className:v,style:{position:"fixed",...ji(c),zIndex:S,...g},children:n.jsxs("button",{onClick:()=>O(!0),style:{width:48,height:48,borderRadius:"50%",border:"none",backgroundColor:V.background,boxShadow:"0 4px 12px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},"aria-label":"Expand voice chat",children:[n.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:V.text,strokeWidth:"2",children:[n.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),n.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),n.jsx("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]}),o.length>0&&n.jsx("span",{style:{position:"absolute",top:-4,right:-4,width:20,height:20,borderRadius:"50%",backgroundColor:V.speakingRing,color:"var(--nice-text-on-primary, #fff)",fontSize:11,fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},children:o.length+1})]})})});function xg(e,t){const r={...t,id:`op_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now()},a=e.operations.slice(0,e.undoIndex+1);return a.push(r),{...e,operations:a,undoIndex:a.length-1}}function Sg(e){return e.undoIndex<0?e:{...e,undoIndex:e.undoIndex-1}}function kg(e){return e.undoIndex>=e.operations.length-1?e:{...e,undoIndex:e.undoIndex+1}}function wg(e,t,r){const s=({"1/1":4,"1/2":2,"1/4":1,"1/8":.5,"1/16":.25,"1/32":.125,"1/4T":.6666666666666666,"1/8T":.3333333333333333,"1/16T":.16666666666666666,"1/4D":1.5,"1/8D":.75}[t.grid]??1)*r,i=t.strength/100;return e.map(o=>{const l=Math.round(o.startTick/s)*s,c=o.startTick+(l-o.startTick)*i,d=(Math.random()-.5)*2*t.humanize;return{...o,startTick:Math.max(0,Math.round(c+d))}})}function Cg(e){if(e.length<2)return null;const t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],r=[...new Set(e.map(s=>s%12))].sort((s,i)=>s-i),a=[{intervals:[0,4,7],quality:"maj"},{intervals:[0,3,7],quality:"min"},{intervals:[0,4,7,11],quality:"maj7"},{intervals:[0,3,7,10],quality:"min7"},{intervals:[0,4,7,10],quality:"7"},{intervals:[0,3,6],quality:"dim"},{intervals:[0,4,8],quality:"aug"},{intervals:[0,3,6,9],quality:"dim7"},{intervals:[0,2,7],quality:"sus2"},{intervals:[0,5,7],quality:"sus4"},{intervals:[0,4,7,9],quality:"6"},{intervals:[0,3,7,9],quality:"min6"}];for(const s of r){const i=r.map(o=>(o-s+12)%12).sort((o,l)=>o-l);for(const o of a)if(o.intervals.length===i.length&&o.intervals.every((l,c)=>l===i[c])){const l=t[s],c=t[e[0]%12];return{root:l,quality:o.quality,bass:c!==l?c:void 0,symbol:`${l}${o.quality==="maj"?"":o.quality}${c!==l?`/${c}`:""}`,intervals:o.intervals}}}return null}const Gc={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],aeolian:[0,2,3,5,7,8,10],locrian:[0,1,3,5,6,8,10],"harmonic-minor":[0,2,3,5,7,8,11],"melodic-minor":[0,2,3,5,7,9,11],"pentatonic-major":[0,2,4,7,9],"pentatonic-minor":[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],"whole-tone":[0,2,4,6,8,10]};function jg(e,t,r){const a=Gc[r],s=(e-t+120)%12;let i=a[0],o=999;for(const c of a){const d=Math.min(Math.abs(s-c),12-Math.abs(s-c));d<o&&(o=d,i=c)}const l=Math.floor((e-t)/12);return t+l*12+i}function Mg(e,t){switch(t.type){case"transpose":return e.map(r=>({...r,pitch:Math.max(0,Math.min(127,r.pitch+(t.params.semitones??0)))}));case"invert":{const r=t.params.axis??60;return e.map(a=>({...a,pitch:Math.max(0,Math.min(127,Math.round(2*r-a.pitch)))}))}case"retrograde":{if(e.length===0)return e;const r=Math.max(...e.map(a=>a.startTick+a.durationTicks));return e.map(a=>({...a,startTick:r-a.startTick-a.durationTicks}))}case"randomize-velocity":return e.map(r=>({...r,velocity:Math.max(1,Math.min(127,r.velocity+Math.round((Math.random()-.5)*2*(t.params.range??20))))}));default:return e}}function Rg(e){return e>=95?"S":e>=85?"A":e>=70?"B":e>=55?"C":e>=40?"D":"F"}const Ng={"guitar-standard":{instrument:"guitar-6",stringPitches:[40,45,50,55,59,64]},"guitar-drop-d":{instrument:"guitar-6",stringPitches:[38,45,50,55,59,64]},"bass-standard":{instrument:"bass-4",stringPitches:[28,33,38,43]},"ukulele-standard":{instrument:"ukulele",stringPitches:[67,60,64,69]}},Tg={"Bass Drum":{staffLine:4,noteHead:"normal",stem:"down"},Snare:{staffLine:2,noteHead:"normal",stem:"up"},"Hi-Hat Closed":{staffLine:0,noteHead:"x",stem:"up"},"Hi-Hat Open":{staffLine:0,noteHead:"diamond",stem:"up"},Ride:{staffLine:-1,noteHead:"x",stem:"up"},Crash:{staffLine:-2,noteHead:"x",stem:"up"},"High Tom":{staffLine:1,noteHead:"normal",stem:"up"},"Mid Tom":{staffLine:2,noteHead:"normal",stem:"down"},"Low Tom":{staffLine:3,noteHead:"normal",stem:"down"}};exports.ALL_CAP_STYLES=Wn;exports.ALL_EFFECTS=Ll;exports.ALL_TEXTURES=fo;exports.ARTNET_PORT=J0;exports.ASYMMETRIC_CAPS=ao;exports.ArpeggiatorPanel=Ui;exports.AudioEffectType=Ac;exports.AudioPitchAnalyzer=go;exports.AudioPlaybackEngine=Mm;exports.AudioRecorder=La;exports.AudioTimeline=Pa;exports.AutoSavePanel=Pi;exports.BarFillEditor=mo;exports.CCAutomationLaneEditor=Fi;exports.CCLane=Ri;exports.CONTROLLER_PROFILES=Hl;exports.ChaseRunner=sg;exports.CollaboratorPermission=Ec;exports.DEFAULT_ARP_CONFIG=la;exports.DEFAULT_AUDIO_INPUT_SETTINGS=zl;exports.DEFAULT_BAR_FILL=Kt;exports.DEFAULT_CAP_STYLE=io;exports.DEFAULT_EMPTY_BAR_FILL=_r;exports.DEFAULT_FONT_SETTINGS=Br;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=Fr;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Or;exports.DEFAULT_KARAOKE_SETTINGS=oo;exports.DEFAULT_PLAYER_BAR_STYLE=pn;exports.DEFAULT_SEED_CONFIG=Fl;exports.DMXEngine=zc;exports.DRUM_PATTERN_NAMES=Om;exports.DefaultScoringPresets=Fa;exports.DmxChannelControl=vs;exports.DmxChannelType=Ft;exports.DmxEditor=Lc;exports.DmxOptionsControl=bs;exports.DmxSliderControl=Un;exports.DynamicRuleEditor=fl;exports.DynamicRuleField=lt;exports.DynamicRuleOperator=ct;exports.EditorTrackProvider=Da;exports.EditorUndoManager=xu;exports.FIXTURE_PROFILES=Dc;exports.GENERIC_PROFILE=us;exports.GM_DRUM_MAP=Tg;exports.GRADIENT_PRESETS=Xo;exports.GROOVE_TEMPLATES=ms;exports.GenericPlayer=Za;exports.GenericPlayerControls=tl;exports.GenericPlayerStage=nl;exports.GenericPlayerStageVisualizer=rl;exports.GenericPlaylist=il;exports.GenericPlaylistItem=as;exports.KARAOKE_FONT_OPTIONS=ap;exports.KEY_MAPS=To;exports.KaraokeEditorManager=Jo;exports.KaraokeFormat=Ja;exports.KaraokeLyrics=_a;exports.KaraokePhaserRenderer=el;exports.KaraokeSummaryOverlay=Xa;exports.KaraokeTimeline=Ka;exports.LANE_COLORS=In;exports.LAUNCH_CONTROL_PROFILE=Vl;exports.LAYER_COLORS=V0;exports.LFOPanel=qi;exports.MINILAB_PROFILE=ql;exports.MPK_MINI_PROFILE=Ul;exports.MasterFXPanel=Ei;exports.MidiCCMapper=Gm;exports.ModeSwitcher=ns;exports.NOTE_NAMES=Im;exports.NiceArpeggiatorPanel=Ui;exports.NiceAudioEffectsRack=Sm;exports.NiceAudioErrorBoundary=Jc;exports.NiceAudioInputPicker=jm;exports.NiceAudioPitchAnalyzer=go;exports.NiceAudioStudio=Xd;exports.NiceAudioTimeline=Pa;exports.NiceAutoSavePanel=Pi;exports.NiceBarFillEditor=mo;exports.NiceCCAutomationLaneEditor=Fi;exports.NiceCCLane=Ri;exports.NiceDMXTimeline=ig;exports.NiceDmxChannelControl=vs;exports.NiceDmxEditor=Lc;exports.NiceDmxOptionsControl=bs;exports.NiceDmxSliderControl=Un;exports.NiceDynamicRuleEditor=fl;exports.NiceEditorTrackProvider=Da;exports.NiceGenericPlayer=Za;exports.NiceGenericPlayerControls=tl;exports.NiceGenericPlayerStage=nl;exports.NiceGenericPlayerStageVisualizer=rl;exports.NiceGenericPlaylist=il;exports.NiceGenericPlaylistItem=as;exports.NiceI18nProvider=Qc;exports.NiceKaraokeEditorManager=Jo;exports.NiceKaraokeLyrics=_a;exports.NiceKaraokeManager=Gh;exports.NiceKaraokePhaserRenderer=el;exports.NiceKaraokeSelectionMode=Yo;exports.NiceKaraokeSessionJoin=np;exports.NiceKaraokeSetupPanel=Ko;exports.NiceKaraokeSongBrowser=Kh;exports.NiceKaraokeSummaryOverlay=Xa;exports.NiceKaraokeTimeline=Ka;exports.NiceKaraokeUploader=Ro;exports.NiceLFOPanel=qi;exports.NiceLatencyCalibrator=Xh;exports.NiceMasterFXPanel=Ei;exports.NiceModeSwitcher=ns;exports.NiceMusicLibraryExplorer=Zp;exports.NiceNoteParticles=Al;exports.NiceNoteRiver=Pl;exports.NicePadKaraokeOverlay=No;exports.NicePianoRoll=$a;exports.NicePlaylistBrowser=bl;exports.NicePlaylistDualPane=ml;exports.NicePlaylistGridView=Sl;exports.NicePlaylistImportWizard=jl;exports.NicePlaylistList=ls;exports.NicePlaylistOverview=kl;exports.NicePlaylistSearchBar=wl;exports.NicePlaylistSidebar=xl;exports.NicePlaylistTagEditor=ll;exports.NicePlaylistTrackList=is;exports.NiceRadioPlayer=ug;exports.NiceRecordingOptionsPanel=Ii;exports.NiceStageVisualizer=rs;exports.NiceStationBrowser=Fc;exports.NiceStepSequencerPanel=Vi;exports.NiceStreamingVisualizer=xs;exports.NiceUndoRedoPanel=Ai;exports.NiceVocalEffectsRack=wm;exports.NiceVocalPerformanceReport=qh;exports.NiceVoiceChatOverlay=Bc;exports.NiceWaveform=Ta;exports.NiceYouTubePlayer=al;exports.NiceZoomSnapControls=Aa;exports.NoteParticles=Al;exports.NoteRiver=Pl;exports.OVERLAY_PATTERNS=$r;exports.OXYGEN25_PROFILE=Wl;exports.PLAYER_COLORS=et;exports.PLAYER_COLOR_VARS=ur;exports.PROGRESSION_NAMES=Fm;exports.PadNotePlayer=Eo;exports.PaneSide=dl;exports.PianoRoll=$a;exports.PlaylistBrowser=bl;exports.PlaylistDualPane=ml;exports.PlaylistGridView=Sl;exports.PlaylistImportWizard=jl;exports.PlaylistList=ls;exports.PlaylistOverview=kl;exports.PlaylistSearchBar=wl;exports.PlaylistSidebar=xl;exports.PlaylistTagEditor=ll;exports.PlaylistTrackList=is;exports.PlaylistType=ss;exports.RecordingOptionsPanel=Ii;exports.SACN_PORT=ng;exports.SCALE_INTERVALS=Gc;exports.SCALE_NAMES=_m;exports.SKEW_CAPS=so;exports.STANDARD_TUNINGS=Ng;exports.SYMMETRIC_CAPS=qa;exports.ShortcutManager=$c;exports.SimpleSynth=_l;exports.SortDirection=ln;exports.SortField=ul;exports.StageVisualizer=rs;exports.StepSequencerPanel=Vi;exports.StreamingVisualizer=xs;exports.TEXTURE_CATEGORIES=Ya;exports.TrackSource=wt;exports.UndoRedoPanel=Ai;exports.ViewMode=cl;exports.VocalEffectsEngine=Dl;exports.VoiceChatOverlay=Bc;exports.Waveform=Ta;exports.WebRTCAudioManager=Oc;exports.YouTubePlayer=al;exports.ZoomSnapControls=Aa;exports.addEffectToLayer=a0;exports.addMidiNote=l0;exports.analyzeAudioFileWithAlgorithm=y0;exports.applyGroove=C0;exports.applyGrooveTemplate=Nc;exports.applyHumanize=Rc;exports.applyKaraokeDisplayVars=ts;exports.applyMidiTransform=Mg;exports.applySwing=Mc;exports.arrow_L=Ot;exports.arrow_R=$t;exports.autoCorrelate=xo;exports.bracket_L=Ba;exports.bracket_R=no;exports.buildArpSequence=Bi;exports.buildLanes=$o;exports.buildNoteDescriptors=Qa;exports.buildPadNoteEvents=Ao;exports.buildSegmentScores=So;exports.canRedo=Jl;exports.canUndo=Ql;exports.chamfer_L=Mr;exports.chamfer_R=hn;exports.clearMidiNotes=d0;exports.clearPattern=yc;exports.computeGrade=Rg;exports.computeTheoreticalMax=Fo;exports.computeVocalPerformanceReport=Uo;exports.convertBrowserSongToKaraokeSongFile=Ph;exports.copyCCEvents=ja;exports.createAnalyserNode=kc;exports.createArpPattern=Ym;exports.createArtNetPacket=tg;exports.createBasslinePattern=Xm;exports.createCCHistory=Kl;exports.createCompressorNode=Cc;exports.createDefaultLFO=Dr;exports.createDefaultShortcuts=D0;exports.createDropZoneHandlers=U0;exports.createEmptyPattern=Yt;exports.createEmptyStep=hs;exports.createGainNode=wc;exports.createHiHatPattern=Km;exports.createKickPattern=Vm;exports.createLoopRegion=$0;exports.createSACNPacket=rg;exports.createSnarePattern=Hm;exports.createVocoderNode=jc;exports.createVoiceChatAudioContext=gg;exports.cutCCEvents=tc;exports.deleteCCEventsInRange=nc;exports.deserializeLFO=iu;exports.deserializePattern=Qm;exports.detectChord=Cg;exports.downsampleAndQuantizePitchPoints=ko;exports.drawGlossyBarOnCanvas=Tn;exports.drawTimeline=ha;exports.estimateLatencyMs=wo;exports.estimateLatencyMsFromRecording=Ho;exports.evaluateLFO=Ea;exports.evaluateLFOAsCC=Ia;exports.exportCCLane=sc;exports.extractBpmFromNotes=Zi;exports.findTextureByUrl=ch;exports.formatShortcut=z0;exports.generateArpEvents=cu;exports.generatePlaceholderWaveform=k0;exports.generateSeed=Gl;exports.generateUltrastarText=b0;exports.getActiveGradient=Qo;exports.getActiveLyrics=Mu;exports.getActiveWords=Ru;exports.getAlgorithmColor=Th;exports.getAlgorithmCssVar=$h;exports.getAlgorithmLabel=Nh;exports.getArpModes=Gi;exports.getArpRates=Wi;exports.getAudioContext=yn;exports.getAudioInputDevices=mg;exports.getAudioWorkletProcessorCode=xc;exports.getBackgroundUrl=Rh;exports.getCachedImage=ih;exports.getCapStyleByName=Rn;exports.getComboMultiplier=zo;exports.getCoverUrl=Mh;exports.getGrooveTemplate=j0;exports.getGrooveTemplateNames=M0;exports.getLaneForPitch=Po;exports.getNextPlayerColor=yd;exports.getNextPlayerColorCss=bd;exports.getOverlayCanvasPattern=En;exports.getPatternByName=Nn;exports.getSACNMulticastAddress=ag;exports.getScoringPreset=zr;exports.getTexturePattern=Pn;exports.getVerseRatingLabel=Do;exports.handleAddCCEvent=h0;exports.handleRedo=vu;exports.handleRemoveCCEvent=f0;exports.handleSelectCCLane=u0;exports.handleUndo=bu;exports.handleUpdateCCEvent=p0;exports.hexToHsl=Pr;exports.humanizeMidiNotes=T0;exports.hydrateKaraokeDisplayFromBackend=sp;exports.hydratePlayerKaraokeSettingsFromBackend=_u;exports.hzToUltrastarPitch=Qi;exports.importCCLane=ic;exports.initKaraokeDisplaySettings=op;exports.instrumentPresets=Rm;exports.isAudioContextRunning=Ni;exports.isInLoopRegion=E0;exports.isWebRTCSupported=fg;exports.loadAllKaraokeSettings=Fu;exports.loadAudioWorkletModule=Sc;exports.loadKaraokeDisplaySettings=Zo;exports.loadKaraokeSettings=Va;exports.loadPlayerBarStyle=lo;exports.loadPlayerBarStyles=Bu;exports.loadRemoteScoringPresets=Lu;exports.makeClickReference=Vo;exports.makeClipSelectionId=v0;exports.mergeWaveforms=S0;exports.midiSeedGenerator=Bm;exports.midiToHz=pa;exports.normalizeHex=Ar;exports.openAudioFilePicker=q0;exports.ornate_L=Wa;exports.ornate_R=Tr;exports.parseLyrics=Cu;exports.parseNotes=Hn;exports.parseUltraStarText=Mo;exports.parseVersesWithSyllables=Xi;exports.parseVersesWithWords=ju;exports.parseVideoMetadata=vo;exports.pasteCCEvents=ec;exports.pill_L=qt;exports.pill_R=_t;exports.preloadTexture=Ha;exports.preloadTextures=oh;exports.probeAudioFile=Pc;exports.pushCCState=Yl;exports.pushOperation=xg;exports.quantizeMidiNotes=R0;exports.quantizeNotes=wg;exports.quantizeStepInBeats=Tc;exports.quantizeStepInSeconds=gs;exports.randomizeVelocity=gc;exports.recordCCEvent=rc;exports.redoCC=Zl;exports.redoOperation=kg;exports.removeEffectFromLayer=s0;exports.removeMidiNote=c0;exports.renderGlossyBarSvg=co;exports.resumeAudioContext=Gt;exports.reversePattern=fc;exports.sampleLFOForDisplay=_i;exports.sampleLFOToCCEvents=zi;exports.saveKaraokeDisplaySettings=ip;exports.saveKaraokeSettings=zu;exports.savePlayerBarStyle=Ou;exports.scaleResult=Bo;exports.scaleTo10k=Oo;exports.scoreNotesWithPitchPoints=_o;exports.selectCCEventsInRange=Wm;exports.serializeLFO=su;exports.serializePattern=Zm;exports.setLoopFromSelection=P0;exports.setProjectWithUndo=Ki;exports.setStepGate=dc;exports.setStepNote=lc;exports.setStepProbability=uc;exports.setStepVelocity=cc;exports.sharp_L=dn;exports.sharp_R=un;exports.shield_L=Rr;exports.shield_R=to;exports.shiftPattern=mc;exports.shouldTrigger=vc;exports.skewTL_L=hr;exports.skewTL_R=ua;exports.skewTR_L=da;exports.skewTR_R=pr;exports.snapLoopToGrid=A0;exports.snapTimeToQuantize=Ma;exports.snapToGrid=x0;exports.snapToScale=jg;exports.soft_L=Oa;exports.soft_R=eo;exports.stepDuration=ps;exports.stepTimeOffset=bc;exports.syncDivisionToHz=Li;exports.tab_L=Ga;exports.tab_R=ro;exports.thinCCEvents=ac;exports.toTrack=jo;exports.toggleEffectBypass=i0;exports.toggleStep=oc;exports.toggleStepSlide=hc;exports.transposePattern=pc;exports.undoCC=Xl;exports.undoOperation=Sg;exports.updateEffectParams=o0;exports.useAudioWorklet=r0;exports.useAutoSave=fu;exports.useCCAutomation=qm;exports.useCanPickSong=tp;exports.useDMXAudioSync=lg;exports.useDMXEngine=og;exports.useEditorTrack=wu;exports.useKaraokePitch=Lo;exports.useKaraokeScoring=Go;exports.useLocalPlaylists=os;exports.useMPE=Pm;exports.useMidiLearn=Tm;exports.useNiceTranslation=Te;exports.useOxygen25=Em;exports.usePitchWorker=e0;exports.usePlaybackEngine=mu;exports.useProjectCRUD=ku;exports.useRadioStream=_c;exports.useRecording=gu;exports.useScoringWorker=t0;exports.useStepSequencer=Jm;exports.useWebMidi=Ur;exports.useWorker=fs;exports.validateAudioFiles=ys;exports.wave_L=Nr;exports.wave_R=Ua;exports.waveformValue=Di;exports.wrapTimeInLoop=I0;