@nice2dev/ui-audio 0.1.0

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 (401) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +175 -0
  4. package/dist/assets/pitchWorker-BgAp5Z97.js +1 -0
  5. package/dist/assets/scoringWorker-B1PkYu_m.js +1 -0
  6. package/dist/config/noteSoundSets.d.ts +29 -0
  7. package/dist/config/noteSoundSets.d.ts.map +1 -0
  8. package/dist/constants/audioColors.d.ts +2 -0
  9. package/dist/constants/audioColors.d.ts.map +1 -0
  10. package/dist/constants/debugKaraoke.d.ts +20 -0
  11. package/dist/constants/debugKaraoke.d.ts.map +1 -0
  12. package/dist/constants/karaokeScoringConfig.d.ts +18 -0
  13. package/dist/constants/karaokeScoringConfig.d.ts.map +1 -0
  14. package/dist/constants/playerColors.d.ts +5 -0
  15. package/dist/constants/playerColors.d.ts.map +1 -0
  16. package/dist/constants/ui.d.ts +3 -0
  17. package/dist/constants/ui.d.ts.map +1 -0
  18. package/dist/core/i18n.d.ts +11 -0
  19. package/dist/core/i18n.d.ts.map +1 -0
  20. package/dist/dmx/DmxChannelControls.d.ts +14 -0
  21. package/dist/dmx/DmxChannelControls.d.ts.map +1 -0
  22. package/dist/dmx/DmxEditor.d.ts +13 -0
  23. package/dist/dmx/DmxEditor.d.ts.map +1 -0
  24. package/dist/dmx/dmxService.d.ts +20 -0
  25. package/dist/dmx/dmxService.d.ts.map +1 -0
  26. package/dist/editor/AudioClipBox.d.ts +9 -0
  27. package/dist/editor/AudioClipBox.d.ts.map +1 -0
  28. package/dist/editor/AudioClipInfo.d.ts +7 -0
  29. package/dist/editor/AudioClipInfo.d.ts.map +1 -0
  30. package/dist/editor/AudioEditorPianoRoll.d.ts +20 -0
  31. package/dist/editor/AudioEditorPianoRoll.d.ts.map +1 -0
  32. package/dist/editor/AudioEditorPianoRollContainer.d.ts +20 -0
  33. package/dist/editor/AudioEditorPianoRollContainer.d.ts.map +1 -0
  34. package/dist/editor/AudioLayerDetails.d.ts +10 -0
  35. package/dist/editor/AudioLayerDetails.d.ts.map +1 -0
  36. package/dist/editor/AudioLayerDetailsContainer.d.ts +10 -0
  37. package/dist/editor/AudioLayerDetailsContainer.d.ts.map +1 -0
  38. package/dist/editor/AudioLayersNavContainer.d.ts +9 -0
  39. package/dist/editor/AudioLayersNavContainer.d.ts.map +1 -0
  40. package/dist/editor/AudioMiniMap.d.ts +11 -0
  41. package/dist/editor/AudioMiniMap.d.ts.map +1 -0
  42. package/dist/editor/AudioMiniMapContainer.d.ts +10 -0
  43. package/dist/editor/AudioMiniMapContainer.d.ts.map +1 -0
  44. package/dist/editor/AudioSourceDetails.d.ts +12 -0
  45. package/dist/editor/AudioSourceDetails.d.ts.map +1 -0
  46. package/dist/editor/AudioTimeline.d.ts +22 -0
  47. package/dist/editor/AudioTimeline.d.ts.map +1 -0
  48. package/dist/editor/AudioTimelineContainer.d.ts +18 -0
  49. package/dist/editor/AudioTimelineContainer.d.ts.map +1 -0
  50. package/dist/editor/AudioTimelineNavContainer.d.ts +14 -0
  51. package/dist/editor/AudioTimelineNavContainer.d.ts.map +1 -0
  52. package/dist/editor/CCLane.d.ts +23 -0
  53. package/dist/editor/CCLane.d.ts.map +1 -0
  54. package/dist/editor/CCLaneSelector.d.ts +14 -0
  55. package/dist/editor/CCLaneSelector.d.ts.map +1 -0
  56. package/dist/editor/PianoRoll.d.ts +14 -0
  57. package/dist/editor/PianoRoll.d.ts.map +1 -0
  58. package/dist/editor/Waveform.d.ts +9 -0
  59. package/dist/editor/Waveform.d.ts.map +1 -0
  60. package/dist/editor/editorDisplayModes.d.ts +37 -0
  61. package/dist/editor/editorDisplayModes.d.ts.map +1 -0
  62. package/dist/editor/editorIO.d.ts +11 -0
  63. package/dist/editor/editorIO.d.ts.map +1 -0
  64. package/dist/editor/hooks/index.d.ts +7 -0
  65. package/dist/editor/hooks/index.d.ts.map +1 -0
  66. package/dist/editor/hooks/useAutoSave.d.ts +13 -0
  67. package/dist/editor/hooks/useAutoSave.d.ts.map +1 -0
  68. package/dist/editor/hooks/usePlaybackEngine.d.ts +35 -0
  69. package/dist/editor/hooks/usePlaybackEngine.d.ts.map +1 -0
  70. package/dist/editor/hooks/useProjectCRUD.d.ts +45 -0
  71. package/dist/editor/hooks/useProjectCRUD.d.ts.map +1 -0
  72. package/dist/editor/hooks/useRecording.d.ts +46 -0
  73. package/dist/editor/hooks/useRecording.d.ts.map +1 -0
  74. package/dist/editor/nav/AudioLayersNav.d.ts +9 -0
  75. package/dist/editor/nav/AudioLayersNav.d.ts.map +1 -0
  76. package/dist/editor/nav/AudioProjectSectionNav.d.ts +12 -0
  77. package/dist/editor/nav/AudioProjectSectionNav.d.ts.map +1 -0
  78. package/dist/editor/nav/AudioTimelineNav.d.ts +14 -0
  79. package/dist/editor/nav/AudioTimelineNav.d.ts.map +1 -0
  80. package/dist/editor/nav/SaveLoadControls.d.ts +9 -0
  81. package/dist/editor/nav/SaveLoadControls.d.ts.map +1 -0
  82. package/dist/editor/panels/AdvancedEditingPanel.d.ts +30 -0
  83. package/dist/editor/panels/AdvancedEditingPanel.d.ts.map +1 -0
  84. package/dist/editor/panels/ArpeggiatorPanel.d.ts +12 -0
  85. package/dist/editor/panels/ArpeggiatorPanel.d.ts.map +1 -0
  86. package/dist/editor/panels/CCAutomationLaneEditor.d.ts +19 -0
  87. package/dist/editor/panels/CCAutomationLaneEditor.d.ts.map +1 -0
  88. package/dist/editor/panels/DisplayModeSelector.d.ts +9 -0
  89. package/dist/editor/panels/DisplayModeSelector.d.ts.map +1 -0
  90. package/dist/editor/panels/EditorPanels.d.ts +66 -0
  91. package/dist/editor/panels/EditorPanels.d.ts.map +1 -0
  92. package/dist/editor/panels/LFOPanel.d.ts +12 -0
  93. package/dist/editor/panels/LFOPanel.d.ts.map +1 -0
  94. package/dist/editor/panels/LayerTrack.d.ts +17 -0
  95. package/dist/editor/panels/LayerTrack.d.ts.map +1 -0
  96. package/dist/editor/panels/ProjectPanel.d.ts +23 -0
  97. package/dist/editor/panels/ProjectPanel.d.ts.map +1 -0
  98. package/dist/editor/panels/SectionPanel.d.ts +11 -0
  99. package/dist/editor/panels/SectionPanel.d.ts.map +1 -0
  100. package/dist/editor/panels/StepSequencerPanel.d.ts +8 -0
  101. package/dist/editor/panels/StepSequencerPanel.d.ts.map +1 -0
  102. package/dist/editor/useEditorRecording.d.ts +45 -0
  103. package/dist/editor/useEditorRecording.d.ts.map +1 -0
  104. package/dist/editor/useEditorTrack.d.ts +71 -0
  105. package/dist/editor/useEditorTrack.d.ts.map +1 -0
  106. package/dist/effects/NoteParticles.d.ts +2 -0
  107. package/dist/effects/NoteParticles.d.ts.map +1 -0
  108. package/dist/effects/NoteRiver.d.ts +15 -0
  109. package/dist/effects/NoteRiver.d.ts.map +1 -0
  110. package/dist/effects/noteThemeColors.d.ts +14 -0
  111. package/dist/effects/noteThemeColors.d.ts.map +1 -0
  112. package/dist/engine/audioContext.d.ts +12 -0
  113. package/dist/engine/audioContext.d.ts.map +1 -0
  114. package/dist/engine/audioKeyboard.d.ts +28 -0
  115. package/dist/engine/audioKeyboard.d.ts.map +1 -0
  116. package/dist/engine/audioLayerDetails.d.ts +13 -0
  117. package/dist/engine/audioLayerDetails.d.ts.map +1 -0
  118. package/dist/engine/audioPlaybackEngine.d.ts +186 -0
  119. package/dist/engine/audioPlaybackEngine.d.ts.map +1 -0
  120. package/dist/engine/audioProject.d.ts +10 -0
  121. package/dist/engine/audioProject.d.ts.map +1 -0
  122. package/dist/engine/audioSource.d.ts +38 -0
  123. package/dist/engine/audioSource.d.ts.map +1 -0
  124. package/dist/engine/audioTimeline.d.ts +54 -0
  125. package/dist/engine/audioTimeline.d.ts.map +1 -0
  126. package/dist/engine/audioUtils.d.ts +3 -0
  127. package/dist/engine/audioUtils.d.ts.map +1 -0
  128. package/dist/engine/generate-pitch-points.d.ts +2 -0
  129. package/dist/engine/generate-pitch-points.d.ts.map +1 -0
  130. package/dist/engine/instrumentPresets.d.ts +13 -0
  131. package/dist/engine/instrumentPresets.d.ts.map +1 -0
  132. package/dist/engine/pitch-worklet-processor.d.ts +11 -0
  133. package/dist/engine/pitch-worklet-processor.d.ts.map +1 -0
  134. package/dist/engine/pitch_client.d.ts +16 -0
  135. package/dist/engine/pitch_client.d.ts.map +1 -0
  136. package/dist/engine/recording.d.ts +31 -0
  137. package/dist/engine/recording.d.ts.map +1 -0
  138. package/dist/engine/simpleSynth.d.ts +46 -0
  139. package/dist/engine/simpleSynth.d.ts.map +1 -0
  140. package/dist/hooks/useCCAutomation.d.ts +36 -0
  141. package/dist/hooks/useCCAutomation.d.ts.map +1 -0
  142. package/dist/hooks/useStepSequencer.d.ts +48 -0
  143. package/dist/hooks/useStepSequencer.d.ts.map +1 -0
  144. package/dist/index.cjs +73 -0
  145. package/dist/index.d.ts +101 -0
  146. package/dist/index.d.ts.map +1 -0
  147. package/dist/index.mjs +13179 -0
  148. package/dist/karaoke/AudioPitchAnalyzer.d.ts +25 -0
  149. package/dist/karaoke/AudioPitchAnalyzer.d.ts.map +1 -0
  150. package/dist/karaoke/BarFillEditor.d.ts +14 -0
  151. package/dist/karaoke/BarFillEditor.d.ts.map +1 -0
  152. package/dist/karaoke/KaraokeLyrics.d.ts +9 -0
  153. package/dist/karaoke/KaraokeLyrics.d.ts.map +1 -0
  154. package/dist/karaoke/KaraokeTimeline.d.ts +21 -0
  155. package/dist/karaoke/KaraokeTimeline.d.ts.map +1 -0
  156. package/dist/karaoke/karaokeTimelineTypes.d.ts +77 -0
  157. package/dist/karaoke/karaokeTimelineTypes.d.ts.map +1 -0
  158. package/dist/karaoke/rendering/fontCatalog.d.ts +30 -0
  159. package/dist/karaoke/rendering/fontCatalog.d.ts.map +1 -0
  160. package/dist/karaoke/rendering/glossyBarCaps.d.ts +57 -0
  161. package/dist/karaoke/rendering/glossyBarCaps.d.ts.map +1 -0
  162. package/dist/karaoke/rendering/glossyBarPatterns.d.ts +16 -0
  163. package/dist/karaoke/rendering/glossyBarPatterns.d.ts.map +1 -0
  164. package/dist/karaoke/rendering/glossyBarRenderer.d.ts +65 -0
  165. package/dist/karaoke/rendering/glossyBarRenderer.d.ts.map +1 -0
  166. package/dist/karaoke/rendering/karaokeAnimations.d.ts +25 -0
  167. package/dist/karaoke/rendering/karaokeAnimations.d.ts.map +1 -0
  168. package/dist/karaoke/rendering/karaokeDisplaySettings.d.ts +65 -0
  169. package/dist/karaoke/rendering/karaokeDisplaySettings.d.ts.map +1 -0
  170. package/dist/karaoke/rendering/karaokeLyrics.d.ts +54 -0
  171. package/dist/karaoke/rendering/karaokeLyrics.d.ts.map +1 -0
  172. package/dist/karaoke/rendering/karaokeNoteParsing.d.ts +20 -0
  173. package/dist/karaoke/rendering/karaokeNoteParsing.d.ts.map +1 -0
  174. package/dist/karaoke/rendering/karaokeSettings.d.ts +143 -0
  175. package/dist/karaoke/rendering/karaokeSettings.d.ts.map +1 -0
  176. package/dist/karaoke/rendering/karaokeTimeline.d.ts +8 -0
  177. package/dist/karaoke/rendering/karaokeTimeline.d.ts.map +1 -0
  178. package/dist/karaoke/rendering/karaokeTimelineRenderer.d.ts +45 -0
  179. package/dist/karaoke/rendering/karaokeTimelineRenderer.d.ts.map +1 -0
  180. package/dist/karaoke/rendering/karaokeTimelineTypes.d.ts +32 -0
  181. package/dist/karaoke/rendering/karaokeTimelineTypes.d.ts.map +1 -0
  182. package/dist/karaoke/rendering/padNotePlayer.d.ts +73 -0
  183. package/dist/karaoke/rendering/padNotePlayer.d.ts.map +1 -0
  184. package/dist/karaoke/rendering/textureCache.d.ts +32 -0
  185. package/dist/karaoke/rendering/textureCache.d.ts.map +1 -0
  186. package/dist/karaoke/rendering/textureCatalog.d.ts +27 -0
  187. package/dist/karaoke/rendering/textureCatalog.d.ts.map +1 -0
  188. package/dist/karaokeEditor/KaraokeEditorManager.d.ts +21 -0
  189. package/dist/karaokeEditor/KaraokeEditorManager.d.ts.map +1 -0
  190. package/dist/karaokeEditor/KaraokePhaserRenderer.d.ts +11 -0
  191. package/dist/karaokeEditor/KaraokePhaserRenderer.d.ts.map +1 -0
  192. package/dist/midi/midiSeedGenerator.d.ts +45 -0
  193. package/dist/midi/midiSeedGenerator.d.ts.map +1 -0
  194. package/dist/midi/oxygen25Profile.d.ts +42 -0
  195. package/dist/midi/oxygen25Profile.d.ts.map +1 -0
  196. package/dist/midi/useMidiLearn.d.ts +94 -0
  197. package/dist/midi/useMidiLearn.d.ts.map +1 -0
  198. package/dist/midi/useOxygen25.d.ts +90 -0
  199. package/dist/midi/useOxygen25.d.ts.map +1 -0
  200. package/dist/midi/useWebMidi.d.ts +60 -0
  201. package/dist/midi/useWebMidi.d.ts.map +1 -0
  202. package/dist/models/editor/audioTypes.d.ts +35 -0
  203. package/dist/models/editor/audioTypes.d.ts.map +1 -0
  204. package/dist/models/editor/fxTypes.d.ts +9 -0
  205. package/dist/models/editor/fxTypes.d.ts.map +1 -0
  206. package/dist/models/editor/midiTypes.d.ts +15 -0
  207. package/dist/models/editor/midiTypes.d.ts.map +1 -0
  208. package/dist/models/editor/timelineTypes.d.ts +11 -0
  209. package/dist/models/editor/timelineTypes.d.ts.map +1 -0
  210. package/dist/models/game/modelsGame.d.ts +12 -0
  211. package/dist/models/game/modelsGame.d.ts.map +1 -0
  212. package/dist/models/modelsAiAudio.d.ts +121 -0
  213. package/dist/models/modelsAiAudio.d.ts.map +1 -0
  214. package/dist/models/modelsAiVideo.d.ts +75 -0
  215. package/dist/models/modelsAiVideo.d.ts.map +1 -0
  216. package/dist/models/modelsAudio.d.ts +160 -0
  217. package/dist/models/modelsAudio.d.ts.map +1 -0
  218. package/dist/models/modelsDmx.d.ts +75 -0
  219. package/dist/models/modelsDmx.d.ts.map +1 -0
  220. package/dist/models/modelsEditor.d.ts +112 -0
  221. package/dist/models/modelsEditor.d.ts.map +1 -0
  222. package/dist/models/modelsKaraoke.d.ts +75 -0
  223. package/dist/models/modelsKaraoke.d.ts.map +1 -0
  224. package/dist/models/modelsMusicPlatform.d.ts +8 -0
  225. package/dist/models/modelsMusicPlatform.d.ts.map +1 -0
  226. package/dist/models/modelsPlatforms.d.ts +52 -0
  227. package/dist/models/modelsPlatforms.d.ts.map +1 -0
  228. package/dist/models/modelsPlaylistManager.d.ts +197 -0
  229. package/dist/models/modelsPlaylistManager.d.ts.map +1 -0
  230. package/dist/models/modelsPlaylists.d.ts +97 -0
  231. package/dist/models/modelsPlaylists.d.ts.map +1 -0
  232. package/dist/player/GenericPlayer.d.ts +56 -0
  233. package/dist/player/GenericPlayer.d.ts.map +1 -0
  234. package/dist/player/GenericPlayerControls.d.ts +17 -0
  235. package/dist/player/GenericPlayerControls.d.ts.map +1 -0
  236. package/dist/player/GenericPlayerStage.d.ts +20 -0
  237. package/dist/player/GenericPlayerStage.d.ts.map +1 -0
  238. package/dist/player/GenericPlayerStageVisualizer.d.ts +32 -0
  239. package/dist/player/GenericPlayerStageVisualizer.d.ts.map +1 -0
  240. package/dist/player/GenericPlayerTrackList.d.ts +10 -0
  241. package/dist/player/GenericPlayerTrackList.d.ts.map +1 -0
  242. package/dist/player/YouTubePlayer.d.ts +13 -0
  243. package/dist/player/YouTubePlayer.d.ts.map +1 -0
  244. package/dist/player/nowPlayingAdapter.d.ts +19 -0
  245. package/dist/player/nowPlayingAdapter.d.ts.map +1 -0
  246. package/dist/player/visualizer/ModeSwitcher.d.ts +12 -0
  247. package/dist/player/visualizer/ModeSwitcher.d.ts.map +1 -0
  248. package/dist/player/visualizer/StageVisualizer.d.ts +23 -0
  249. package/dist/player/visualizer/StageVisualizer.d.ts.map +1 -0
  250. package/dist/player/visualizer/VuOverlay.d.ts +6 -0
  251. package/dist/player/visualizer/VuOverlay.d.ts.map +1 -0
  252. package/dist/player/visualizer/modes/BarsMode.d.ts +2 -0
  253. package/dist/player/visualizer/modes/BarsMode.d.ts.map +1 -0
  254. package/dist/player/visualizer/modes/BlobFlowMode.d.ts +11 -0
  255. package/dist/player/visualizer/modes/BlobFlowMode.d.ts.map +1 -0
  256. package/dist/player/visualizer/modes/ColorRipplesMode.d.ts +12 -0
  257. package/dist/player/visualizer/modes/ColorRipplesMode.d.ts.map +1 -0
  258. package/dist/player/visualizer/modes/CoverMode.d.ts +9 -0
  259. package/dist/player/visualizer/modes/CoverMode.d.ts.map +1 -0
  260. package/dist/player/visualizer/modes/CozyFireplaceMode.d.ts +14 -0
  261. package/dist/player/visualizer/modes/CozyFireplaceMode.d.ts.map +1 -0
  262. package/dist/player/visualizer/modes/EqualizerCircleMode.d.ts +2 -0
  263. package/dist/player/visualizer/modes/EqualizerCircleMode.d.ts.map +1 -0
  264. package/dist/player/visualizer/modes/GridMode.d.ts +2 -0
  265. package/dist/player/visualizer/modes/GridMode.d.ts.map +1 -0
  266. package/dist/player/visualizer/modes/ImageTornadoMode.d.ts +18 -0
  267. package/dist/player/visualizer/modes/ImageTornadoMode.d.ts.map +1 -0
  268. package/dist/player/visualizer/modes/LavaLampMode.d.ts +13 -0
  269. package/dist/player/visualizer/modes/LavaLampMode.d.ts.map +1 -0
  270. package/dist/player/visualizer/modes/NeonTrianglesMode.d.ts +11 -0
  271. package/dist/player/visualizer/modes/NeonTrianglesMode.d.ts.map +1 -0
  272. package/dist/player/visualizer/modes/OrbitalsMode.d.ts +2 -0
  273. package/dist/player/visualizer/modes/OrbitalsMode.d.ts.map +1 -0
  274. package/dist/player/visualizer/modes/PaletteMode.d.ts +2 -0
  275. package/dist/player/visualizer/modes/PaletteMode.d.ts.map +1 -0
  276. package/dist/player/visualizer/modes/ParticlesMode.d.ts +13 -0
  277. package/dist/player/visualizer/modes/ParticlesMode.d.ts.map +1 -0
  278. package/dist/player/visualizer/modes/PlasmaBallMode.d.ts +3 -0
  279. package/dist/player/visualizer/modes/PlasmaBallMode.d.ts.map +1 -0
  280. package/dist/player/visualizer/modes/RadialMode.d.ts +2 -0
  281. package/dist/player/visualizer/modes/RadialMode.d.ts.map +1 -0
  282. package/dist/player/visualizer/modes/RaysMode.d.ts +4 -0
  283. package/dist/player/visualizer/modes/RaysMode.d.ts.map +1 -0
  284. package/dist/player/visualizer/modes/RiftMode.d.ts +3 -0
  285. package/dist/player/visualizer/modes/RiftMode.d.ts.map +1 -0
  286. package/dist/player/visualizer/modes/RingsMode.d.ts +2 -0
  287. package/dist/player/visualizer/modes/RingsMode.d.ts.map +1 -0
  288. package/dist/player/visualizer/modes/SpectrumMode.d.ts +2 -0
  289. package/dist/player/visualizer/modes/SpectrumMode.d.ts.map +1 -0
  290. package/dist/player/visualizer/modes/StarfieldMode.d.ts +13 -0
  291. package/dist/player/visualizer/modes/StarfieldMode.d.ts.map +1 -0
  292. package/dist/player/visualizer/modes/WaveformMode.d.ts +2 -0
  293. package/dist/player/visualizer/modes/WaveformMode.d.ts.map +1 -0
  294. package/dist/player/visualizer/types.d.ts +3 -0
  295. package/dist/player/visualizer/types.d.ts.map +1 -0
  296. package/dist/player/visualizer/useLocalStorageState.d.ts +2 -0
  297. package/dist/player/visualizer/useLocalStorageState.d.ts.map +1 -0
  298. package/dist/playlist/DynamicRuleEditor.d.ts +11 -0
  299. package/dist/playlist/DynamicRuleEditor.d.ts.map +1 -0
  300. package/dist/playlist/GenericPlaylist.d.ts +22 -0
  301. package/dist/playlist/GenericPlaylist.d.ts.map +1 -0
  302. package/dist/playlist/GenericPlaylistItem.d.ts +41 -0
  303. package/dist/playlist/GenericPlaylistItem.d.ts.map +1 -0
  304. package/dist/playlist/PlaylistBrowser.d.ts +24 -0
  305. package/dist/playlist/PlaylistBrowser.d.ts.map +1 -0
  306. package/dist/playlist/PlaylistDualPane.d.ts +17 -0
  307. package/dist/playlist/PlaylistDualPane.d.ts.map +1 -0
  308. package/dist/playlist/PlaylistGridView.d.ts +12 -0
  309. package/dist/playlist/PlaylistGridView.d.ts.map +1 -0
  310. package/dist/playlist/PlaylistList.d.ts +23 -0
  311. package/dist/playlist/PlaylistList.d.ts.map +1 -0
  312. package/dist/playlist/PlaylistOverview.d.ts +14 -0
  313. package/dist/playlist/PlaylistOverview.d.ts.map +1 -0
  314. package/dist/playlist/PlaylistSearchBar.d.ts +22 -0
  315. package/dist/playlist/PlaylistSearchBar.d.ts.map +1 -0
  316. package/dist/playlist/PlaylistSidebar.d.ts +25 -0
  317. package/dist/playlist/PlaylistSidebar.d.ts.map +1 -0
  318. package/dist/playlist/PlaylistTagEditor.d.ts +15 -0
  319. package/dist/playlist/PlaylistTagEditor.d.ts.map +1 -0
  320. package/dist/playlist/PlaylistTrackList.d.ts +26 -0
  321. package/dist/playlist/PlaylistTrackList.d.ts.map +1 -0
  322. package/dist/playlist/useLocalPlaylists.d.ts +17 -0
  323. package/dist/playlist/useLocalPlaylists.d.ts.map +1 -0
  324. package/dist/ui-audio.css +1 -0
  325. package/dist/utils/BaseStreamClient.d.ts +64 -0
  326. package/dist/utils/BaseStreamClient.d.ts.map +1 -0
  327. package/dist/utils/arpeggiator.d.ts +49 -0
  328. package/dist/utils/arpeggiator.d.ts.map +1 -0
  329. package/dist/utils/articulationEngine.d.ts +69 -0
  330. package/dist/utils/articulationEngine.d.ts.map +1 -0
  331. package/dist/utils/audioEditorUtils.d.ts +2 -0
  332. package/dist/utils/audioEditorUtils.d.ts.map +1 -0
  333. package/dist/utils/audioFxUtils.d.ts +6 -0
  334. package/dist/utils/audioFxUtils.d.ts.map +1 -0
  335. package/dist/utils/audioMidiUtils.d.ts +18 -0
  336. package/dist/utils/audioMidiUtils.d.ts.map +1 -0
  337. package/dist/utils/audioPitchAlgorithms.d.ts +3 -0
  338. package/dist/utils/audioPitchAlgorithms.d.ts.map +1 -0
  339. package/dist/utils/audioPitchAnalyzeFile.d.ts +26 -0
  340. package/dist/utils/audioPitchAnalyzeFile.d.ts.map +1 -0
  341. package/dist/utils/audioTimelineUtils.d.ts +5 -0
  342. package/dist/utils/audioTimelineUtils.d.ts.map +1 -0
  343. package/dist/utils/ccAutomation.d.ts +51 -0
  344. package/dist/utils/ccAutomation.d.ts.map +1 -0
  345. package/dist/utils/chordScale.d.ts +47 -0
  346. package/dist/utils/chordScale.d.ts.map +1 -0
  347. package/dist/utils/clipLauncher.d.ts +97 -0
  348. package/dist/utils/clipLauncher.d.ts.map +1 -0
  349. package/dist/utils/colorResolver.d.ts +12 -0
  350. package/dist/utils/colorResolver.d.ts.map +1 -0
  351. package/dist/utils/crepeStreaming.d.ts +21 -0
  352. package/dist/utils/crepeStreaming.d.ts.map +1 -0
  353. package/dist/utils/drawTool.d.ts +31 -0
  354. package/dist/utils/drawTool.d.ts.map +1 -0
  355. package/dist/utils/envelopeFollower.d.ts +46 -0
  356. package/dist/utils/envelopeFollower.d.ts.map +1 -0
  357. package/dist/utils/gameAudio.d.ts +237 -0
  358. package/dist/utils/gameAudio.d.ts.map +1 -0
  359. package/dist/utils/grooveTemplates.d.ts +69 -0
  360. package/dist/utils/grooveTemplates.d.ts.map +1 -0
  361. package/dist/utils/karaokeHelpers.d.ts +61 -0
  362. package/dist/utils/karaokeHelpers.d.ts.map +1 -0
  363. package/dist/utils/karaokeMetadata.d.ts +27 -0
  364. package/dist/utils/karaokeMetadata.d.ts.map +1 -0
  365. package/dist/utils/karaokeScoring.d.ts +111 -0
  366. package/dist/utils/karaokeScoring.d.ts.map +1 -0
  367. package/dist/utils/latencyEstimate.d.ts +8 -0
  368. package/dist/utils/latencyEstimate.d.ts.map +1 -0
  369. package/dist/utils/lfoEngine.d.ts +55 -0
  370. package/dist/utils/lfoEngine.d.ts.map +1 -0
  371. package/dist/utils/librosaStreaming.d.ts +19 -0
  372. package/dist/utils/librosaStreaming.d.ts.map +1 -0
  373. package/dist/utils/logger.d.ts +31 -0
  374. package/dist/utils/logger.d.ts.map +1 -0
  375. package/dist/utils/macroSystem.d.ts +97 -0
  376. package/dist/utils/macroSystem.d.ts.map +1 -0
  377. package/dist/utils/musicPlayerUtils.d.ts +7 -0
  378. package/dist/utils/musicPlayerUtils.d.ts.map +1 -0
  379. package/dist/utils/padKaraokeSession.d.ts +50 -0
  380. package/dist/utils/padKaraokeSession.d.ts.map +1 -0
  381. package/dist/utils/songDataHelpers.d.ts +59 -0
  382. package/dist/utils/songDataHelpers.d.ts.map +1 -0
  383. package/dist/utils/stepSequencer.d.ts +62 -0
  384. package/dist/utils/stepSequencer.d.ts.map +1 -0
  385. package/dist/utils/undoRedoUtils.d.ts +5 -0
  386. package/dist/utils/undoRedoUtils.d.ts.map +1 -0
  387. package/dist/utils/vocalEffectsEngine.d.ts +64 -0
  388. package/dist/utils/vocalEffectsEngine.d.ts.map +1 -0
  389. package/dist/utils/vocalPerformanceMetrics.d.ts +117 -0
  390. package/dist/utils/vocalPerformanceMetrics.d.ts.map +1 -0
  391. package/dist/workers/pitchWorker.d.ts +11 -0
  392. package/dist/workers/pitchWorker.d.ts.map +1 -0
  393. package/dist/workers/scoringWorker.d.ts +71 -0
  394. package/dist/workers/scoringWorker.d.ts.map +1 -0
  395. package/dist/workers/usePitchWorker.d.ts +7 -0
  396. package/dist/workers/usePitchWorker.d.ts.map +1 -0
  397. package/dist/workers/useScoringWorker.d.ts +7 -0
  398. package/dist/workers/useScoringWorker.d.ts.map +1 -0
  399. package/dist/workers/useWorker.d.ts +12 -0
  400. package/dist/workers/useWorker.d.ts.map +1 -0
  401. package/package.json +84 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";var Zo=Object.create;var Jr=Object.defineProperty;var Xo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Qo=Object.getPrototypeOf,ei=Object.prototype.hasOwnProperty;var ti=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Jo(t))!ei.call(e,a)&&a!==n&&Jr(e,a,{get:()=>t[a],enumerable:!(r=Xo(t,a))||r.enumerable});return e};var Qn=(e,t,n)=>(n=e!=null?Zo(Qo(e)):{},ti(t||!e||!e.__esModule?Jr(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),h=require("react"),Ge=require("react-bootstrap"),ur=require("pitchy"),ni=require("react-window"),$r=require("react-youtube"),ri=require("@fortawesome/react-fontawesome"),Qr=require("@fortawesome/free-brands-svg-icons"),er=require("@fortawesome/free-solid-svg-icons");var lt=typeof document<"u"?document.currentScript:null;const ai=(e,t)=>t??e,za=h.createContext(ai),si=({t:e,children:t})=>o.jsx(za.Provider,{value:e,children:t});function Ce(){return{t:h.useContext(za)}}const oi="Waveform",ii=({audioBlob:e,currentTime:t,duration:n})=>{const r=h.useRef(null);return h.useEffect(()=>{if(!e||!r.current||!n||n===1/0){console.warn(oi,"Cannot draw waveform � invalid duration:",n);return}(async()=>{const s=await e.arrayBuffer(),c=(await new AudioContext().decodeAudioData(s)).getChannelData(0),d=r.current;if(!d)return;const u=d.getContext("2d");if(!u)return;u.clearRect(0,0,d.width,d.height);const p=Math.floor(c.length/d.width),m=new Float32Array(d.width);for(let f=0;f<d.width;f++){const y=f*p,g=c.slice(y,y+p);m[f]=g.reduce((v,S)=>Math.abs(v)+Math.abs(S),0)/g.length}u.beginPath(),u.strokeStyle="#007bff",u.lineWidth=2;for(let f=0;f<d.width;f++){const y=f,g=(1-m[f])*d.height;f===0?u.moveTo(y,g):u.lineTo(y,g)}if(u.stroke(),n>0){const f=Math.max(0,Math.min(t/n*d.width,d.width));u.beginPath(),u.strokeStyle="red",u.lineWidth=2,u.moveTo(f,0),u.lineTo(f,d.height),u.stroke()}})()},[e,t,n]),o.jsx("canvas",{ref:r,width:600,height:200,style:{border:"1px solid black"},role:"img","aria-label":"Waveform canvas"})},ea=88,$t=16,mn=16,li=320;function ci(e){return e-21}function di(e){return e+21}const ui=({notes:e,onAddNote:t,onRemoveNote:n,selectedNoteId:r,setSelectedNoteId:a,duration:s=4,zoom:i=1})=>{const l=h.useRef(null),c=li*i,d=ea*$t,u=h.useRef(null);h.useEffect(()=>{},[e,i,s]);const p=f=>{const y=f.target.getBoundingClientRect(),g=f.clientX-y.left,v=f.clientY-y.top,S=Math.floor(v/$t),b=di(S),x=g/c*s;u.current={drawing:!0,startX:g,key:S},t(b,x,s/mn)},m=(f,y)=>{y.stopPropagation(),a==null||a(f)};return o.jsxs("svg",{ref:l,width:c,height:d,style:{background:"var(--surface-muted, #fafafa)",border:"1px solid var(--border, #bbb)",userSelect:"none",display:"block"},onMouseDown:p,children:[[...Array(ea)].map((f,y)=>o.jsx("rect",{x:0,y:y*$t,width:c,height:$t,fill:y%2===0?"var(--key-even, #f5f5f5)":"var(--key-odd, #e0e0e0)"},y)),[...Array(mn+1)].map((f,y)=>o.jsx("line",{x1:y*c/mn,y1:0,x2:y*c/mn,y2:d,stroke:"var(--border-muted, #ccc)",strokeWidth:y%4===0?2:1},y)),e.map(f=>{const y=ci(f.pitch),g=f.start/s*c,v=f.duration/s*c;return o.jsx("rect",{x:g,y:y*$t,width:Math.max(6,v),height:$t-2,fill:f.id===r?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:f.id===r?2:1,rx:3,onClick:S=>m(f.id,S),onDoubleClick:()=>n(f.id),style:{cursor:"pointer"}},f.id)})]})},hi=({ccEvents:e,onAddEvent:t,onUpdateEvent:n,onRemoveEvent:r,ccType:a,duration:s,width:i,height:l=60,curveType:c})=>{const d=h.useRef(null),{t:u}=Ce(),[p,m]=h.useState(null),[f,y]=h.useState(null),[g,v]=h.useState(null),S=[...e].sort((A,V)=>A.time-V.time),b=A=>[A.time/s*i,(127-A.value)/127*l],x=(A,V,te)=>Math.max(V,Math.min(te,A)),w=A=>{var E;if(A.target instanceof SVGCircleElement)return;const V=(E=d.current)==null?void 0:E.getBoundingClientRect();if(!V)return;const te=A.clientX-V.left,ee=A.clientY-V.top,W=x(te/i*s,0,s),Q=x(127-Math.round(ee/l*127),0,127);t(a,Q,W)},k=(A,V)=>{var Q;V.stopPropagation(),m(A.id),v(A.id);const[te,ee]=b(A),W=(Q=d.current)==null?void 0:Q.getBoundingClientRect();W&&y({dx:V.clientX-W.left-te,dy:V.clientY-W.top-ee})},j=A=>{var E;if(p==null||!f)return;const V=(E=d.current)==null?void 0:E.getBoundingClientRect();if(!V)return;const te=x(A.clientX-V.left-f.dx,0,i),ee=x(A.clientY-V.top-f.dy,0,l),W=x(te/i*s,0,s),Q=x(127-Math.round(ee/l*127),0,127);n(p,Q,W)},T=()=>{m(null),y(null)};h.useEffect(()=>{const A=V=>{(V.key==="Delete"||V.key==="Backspace")&&g!=null&&(r(g),v(null))};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[g,r]),h.useEffect(()=>{if(p!=null)return window.addEventListener("mousemove",j),window.addEventListener("mouseup",T),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",T)}});const[D,C]=h.useState(null),L=(A,V)=>{const[te,ee]=b(A);C({x:te+10,y:ee-10,text:`Val: ${A.value}, Time: ${A.time.toFixed(2)}s`})},G=()=>C(null),q=A=>{var E;const V=(E=d.current)==null?void 0:E.getBoundingClientRect();if(!V)return;const te=A.clientX-V.left,ee=A.clientY-V.top,W=x(te/i*s,0,s),Q=x(127-Math.round(ee/l*127),0,127);t(a,Q,W)};return o.jsxs("svg",{ref:d,width:i,height:l,style:{background:"var(--surface-muted, #f3f3f3)",border:"1px solid var(--border, #bbb)",cursor:p?"grabbing":"crosshair",display:"block"},onClick:w,onDoubleClick:q,tabIndex:0,children:[[...Array(9)].map((A,V)=>o.jsx("line",{x1:0,y1:V*l/8,x2:i,y2:V*l/8,stroke:"var(--border-muted, #ddd)",strokeWidth:V===0||V===8?2:1},V)),S.length>1&&o.jsx("polyline",{fill:"none",stroke:"var(--accent, #1976d2)",strokeWidth:2,points:S.map(A=>b(A).join(",")).join(" ")}),S.map(A=>{const[V,te]=b(A);return o.jsxs("g",{children:[o.jsx("circle",{cx:V,cy:te,r:g===A.id?8:6,fill:g===A.id?"var(--accent, #1976d2)":"var(--accent-light, #90caf9)",stroke:"var(--accent, #1976d2)",strokeWidth:g===A.id?3:2,style:{cursor:"pointer"},onMouseDown:ee=>k(A,ee),onContextMenu:ee=>{ee.preventDefault(),r(A.id)},onClick:ee=>{ee.stopPropagation(),v(A.id)},onMouseOver:ee=>L(A),onMouseOut:G}),g===A.id&&o.jsx("foreignObject",{x:V+10,y:te-18,width:90,height:30,style:{pointerEvents:"auto"},children:o.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:[o.jsxs("label",{style:{marginRight:4},children:[u("ccLane.curve","Curve"),":"]}),o.jsxs("select",{value:A.handleType||c||"linear",onChange:ee=>{n(A.id,A.value,A.time,ee.target.value)},children:[o.jsx("option",{value:"linear",children:u("ccLane.linear","Linear")}),o.jsx("option",{value:"step",children:u("ccLane.step","Step")}),o.jsx("option",{value:"exp",children:u("ccLane.exponential","Exponential")})]})]})})]},A.id)}),D&&o.jsxs("g",{pointerEvents:"none",children:[o.jsx("rect",{x:D.x,y:D.y-18,width:90,height:20,fill:"var(--surface-bg, #fff)",stroke:"var(--accent, #1976d2)",rx:4}),o.jsx("text",{x:D.x+6,y:D.y-4,fontSize:13,fill:"var(--accent, #1976d2)",children:D.text})]}),o.jsxs("text",{x:6,y:16,fontSize:14,fill:"var(--accent, #1976d2)",children:["CC",a]})]})},fi="audioContext";let hn=null;function qt(){if(!hn)try{hn=new(window.AudioContext||window.webkitAudioContext)}catch(e){console.error(fi,"Error initializing AudioContext:",e)}return hn}async function Vt(){const e=qt();e&&e.state==="suspended"&&await e.resume()}function Wa(){return!!hn&&hn.state==="running"}function Ua(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 pi(e,t){if(!t.snapEnabled)return e;const n=Ua(t);return Math.round(e/n)*n}function mi(e,t=!1){const n=Math.floor(e/60),r=Math.floor(e%60),a=Math.floor(e%1*1e3);return t?`${n}:${r.toString().padStart(2,"0")}.${a.toString().padStart(3,"0")}`:`${n}:${r.toString().padStart(2,"0")}`}function gi(e,t){const n=t/60,r=e*n,a=Math.floor(r/4),s=Math.floor(r%4);return`${a+1}:${s+1}`}function qa(e,t,n=!0){const r=e.getContext("2d");if(!r)return;const a=30*t.zoom*t.duration,s=Math.max(80,30*t.zoom);e.width=a,e.height=s,r.clearRect(0,0,a,s),r.fillStyle="var(--surface-bg, #f5f5f5)",r.fillRect(0,0,a,s);const i=a/t.duration;let l=1;i<30?l=5:i<60?l=2:i>150&&(l=.5),r.strokeStyle="var(--border-secondary, #ddd)",r.lineWidth=1;for(let c=0;c<=t.duration;c+=l){const d=c/t.duration*a,u=c%1===0;if(r.strokeStyle=u?"var(--border-secondary, #ccc)":"var(--border-muted, #eee)",r.lineWidth=u?1.5:.5,r.beginPath(),r.moveTo(d,0),r.lineTo(d,s),r.stroke(),u&&i>40){r.fillStyle="var(--muted, #666)",r.font="10px monospace",r.textAlign="center";const p=n?gi(c,t.bpm):mi(c);r.fillText(p,d,12)}}if(t.snapEnabled){const c=Ua(t);r.strokeStyle="var(--accent-primary, #ffeb3b)",r.lineWidth=.5;for(let d=0;d<=t.duration;d+=c){const u=d/t.duration*a;r.beginPath(),r.moveTo(u,s-5),r.lineTo(u,s),r.stroke()}}}function yi(e,t,n,r){const a=e.getContext("2d");if(!a)return;const s=30*t.zoom*t.duration,i=Math.max(80,30*t.zoom),l=n/t.duration*s;qa(e,t),a.strokeStyle=r?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",a.lineWidth=2,a.beginPath(),a.moveTo(l,0),a.lineTo(l,i),a.stroke(),a.fillStyle=r?"var(--danger, #f44336)":"var(--accent-primary, #2196f3)",a.beginPath(),a.moveTo(l,0),a.lineTo(l-5,-8),a.lineTo(l+5,-8),a.closePath(),a.fill()}function bi(e,t,n,r="var(--success, #4caf50)"){const a=e.getContext("2d");if(!a||!(n!=null&&n.length))return;const s=30*t.zoom*t.duration,l=e.height/2,c=Math.max(10,l-6);a.save(),a.strokeStyle=r,a.lineWidth=1,a.beginPath(),n.forEach((d,u)=>{const p=u/(n.length-1)*s,m=l-d*c;u===0?a.moveTo(p,m):a.lineTo(p,m)}),a.stroke(),a.restore()}const vi=({zoom:e=1,duration:t=4,isPlaying:n,isRecording:r,currentTime:a,bpm:s=120,snapEnabled:i=!1,snapMode:l="beat",waveform:c,waveformColor:d,onCurrentTimeChange:u,onZoomChange:p})=>{const m=h.useRef(null),f=h.useRef(null),y=h.useRef(null),[g,v]=h.useState(!1),S={zoom:e,duration:t,bpm:s,snapEnabled:i,snapMode:l};h.useEffect(()=>{Vt(),b()},[e,t,a,r,s,i,l,c]),h.useEffect(()=>{n?(y.current=performance.now(),x()):f.current&&cancelAnimationFrame(f.current)},[n]);const b=()=>{m.current&&(qa(m.current,S),c!=null&&c.length&&bi(m.current,S,c,d),yi(m.current,S,a,r))},x=()=>{if(!n)return;const C=L=>{if(y.current!==null){const G=(L-y.current)/1e3;y.current=L;const q=Math.min(a+G,t);u(q)}a<t&&(f.current=requestAnimationFrame(C))};f.current=requestAnimationFrame(C)},w=C=>{v(!0),T(C)},k=C=>{g&&T(C)},j=()=>{v(!1)},T=C=>{if(!m.current)return;const L=m.current.getBoundingClientRect();let q=(C.clientX-L.left)/L.width*t;q=pi(q,S),u(Math.min(Math.max(q,0),t))},D=C=>{if(!p)return;C.preventDefault();const L=C.deltaY>0?-.1:.1,G=Math.max(.5,Math.min(5,e+L));p(G)};return o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:o.jsx("canvas",{ref:m,style:{border:"1px solid black",backgroundColor:"white",width:`${30*e*t}px`,height:`${Math.max(80,30*e)}px`,cursor:g?"grabbing":"pointer"},onMouseDown:w,onMouseMove:k,onMouseUp:j,onMouseLeave:j,onWheel:D,role:"img","aria-label":"Audio timeline canvas"})})};let xi=Date.now();function Ut(){return xi++}function Si(e,t,n=.01){if(e.length===0)return[];const r=[];let a=-1/0;for(const s of e)s.time-a>=n&&(r.push({id:Ut(),cc:t,value:Kt(s.value),time:s.time}),a=s.time);return r}function ta(e,t,n,r=32){const a=[];for(let s=0;s<=r;s++){const i=s/r;a.push({id:Ut(),cc:n,value:Kt(Nn(e.value,t.value,i)),time:Nn(e.time,t.time,i)})}return a}function wi(e,t,n,r,a=48){const s=[];for(let i=0;i<=a;i++){const l=i/a,c=na(e.time,t.time,n.time,l),d=na(e.value,t.value,n.value,l);s.push({id:Ut(),cc:r,value:Kt(d),time:c})}return s}function Ci(e,t,n,r=8){const a=[],s=(t.time-e.time)/r,i=(t.value-e.value)/r;for(let l=0;l<r;l++){const c=e.time+l*s,d=Kt(e.value+l*i);a.push({id:Ut(),cc:n,value:d,time:c}),a.push({id:Ut(),cc:n,value:d,time:c+s-.001})}return a}function Mi(e,t,n,r=2,a=32){const s=[];for(let i=0;i<=a;i++){const l=i/a,c=Math.pow(l,r);s.push({id:Ut(),cc:n,value:Kt(Nn(e.value,t.value,c)),time:Nn(e.time,t.time,l)})}return s}function ki(e,t=3){if(e.length<t)return e;const n=[...e].sort((r,a)=>r.time-a.time);return n.map((r,a)=>{const s=Math.max(0,a-Math.floor(t/2)),i=Math.min(n.length,s+t),l=n.slice(s,i),c=l.reduce((d,u)=>d+u.value,0)/l.length;return{...r,value:Kt(Math.round(c))}})}function $i(e,t){let n;switch(e.mode){case"pencil":n=Si(t,e.cc,e.resolution);break;case"line":n=t.length>=2?ta(t[0],t[t.length-1],e.cc):[];break;case"curve":t.length>=3?n=wi(t[0],t[Math.floor(t.length/2)],t[t.length-1],e.cc):t.length>=2?n=ta(t[0],t[t.length-1],e.cc):n=[];break;case"step":n=t.length>=2?Ci(t[0],t[t.length-1],e.cc):[];break;case"ramp":n=t.length>=2?Mi(t[0],t[t.length-1],e.cc):[];break;default:n=[]}if(e.smoothing>0){const r=Math.max(2,Math.round(e.smoothing*8));n=ki(n,r)}return n}function Kt(e){return Math.max(0,Math.min(127,Math.round(e)))}function Nn(e,t,n){return e+(t-e)*n}function na(e,t,n,r){const a=1-r;return a*a*e+2*a*r*t+r*r*n}function Wn(){return{waveform:"sine",rate:1,depth:.5,phase:0,center:.5,syncToBpm:!1,syncDivision:"1/4",enabled:!0}}const Ri={"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 Va(e,t){return e/60*Ri[t]/4}function Ka(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 Rr(e,t,n){if(!e.enabled)return e.center;const r=e.syncToBpm&&n?Va(n,e.syncDivision):e.rate,a=t*r+e.phase/(2*Math.PI),s=Ka(e.waveform,a),i=e.center+s*e.depth*.5;return Math.max(0,Math.min(1,i))}function jr(e,t,n){return Math.round(Rr(e,t,n)*127)}function Ha(e,t,n,r,a=30,s){const i=n-t,l=Math.max(2,Math.ceil(i*a)),c=[];for(let d=0;d<=l;d++){const u=t+d/l*i,p=jr(e,u,s);c.push({time:u,value:p,cc:r})}return c}function Ya(e,t,n,r=2,a,s=200){const i=[];for(let l=0;l<=s;l++){const c=l/s*r,d=Rr(e,c,a);i.push({x:l/s*t,y:(1-d)*n})}return i}function ji(e){return JSON.stringify(e,null,2)}function Ti(e){try{const t=JSON.parse(e);return!t||typeof t.waveform!="string"?null:t}catch{return null}}const tr=140,Ht=24,Pi=[{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"}],Ei=({layerId:e,ccNumber:t,duration:n,zoom:r,automation:a,onChangeCCNumber:s})=>{const{t:i}=Ce(),l=h.useRef(null),[c,d]=h.useState("pencil"),[u,p]=h.useState(!1),m=h.useRef([]),[f,y]=h.useState(null),[g,v]=h.useState(!1),[S,b]=h.useState(Wn()),x=h.useRef(null),w=a.getEvents(e),k=w.filter(E=>E.cc===t),j=Math.max(400,n*30*r),T=h.useCallback(E=>E/j*n,[j,n]),D=h.useCallback(E=>Math.round(Math.max(0,Math.min(127,127-(E-Ht)/tr*127))),[]),C=h.useCallback(E=>E/n*j,[j,n]),L=h.useCallback(E=>Ht+(127-E)/127*tr,[]),G=h.useCallback(()=>{const E=l.current;if(!E)return;const F=E.getContext("2d");if(!F)return;const N=E.width,$=E.height;F.clearRect(0,0,N,$),F.fillStyle="#1a1a2e",F.fillRect(0,0,N,$),F.strokeStyle="rgba(255,255,255,0.06)",F.lineWidth=1;for(let R=0;R<=127;R+=16){const _=L(R);F.beginPath(),F.moveTo(0,_),F.lineTo(N,_),F.stroke()}F.fillStyle="rgba(255,255,255,0.3)",F.font="10px monospace",F.textBaseline="middle";for(const R of[0,32,64,96,127])F.fillText(String(R),2,L(R));F.strokeStyle="rgba(255,255,255,0.04)";for(let R=0;R<=n;R++){const _=C(R);F.beginPath(),F.moveTo(_,0),F.lineTo(_,$),F.stroke()}const M=[...k].sort((R,_)=>R.time-_.time);if(M.length>0){F.beginPath(),F.moveTo(C(M[0].time),$-Ht);for(const R of M)F.lineTo(C(R.time),L(R.value));F.lineTo(C(M[M.length-1].time),$-Ht),F.closePath(),F.fillStyle="rgba(59, 130, 246, 0.15)",F.fill(),F.beginPath(),F.strokeStyle="#3b82f6",F.lineWidth=2;for(let R=0;R<M.length;R++){const _=C(M[R].time),I=L(M[R].value);R===0?F.moveTo(_,I):((M[R].handleType??"linear")==="step"&&F.lineTo(_,L(M[R-1].value)),F.lineTo(_,I))}F.stroke();for(const R of M){const _=C(R.time),I=L(R.value),B=f===R.id;F.beginPath(),F.arc(_,I,B?6:4,0,Math.PI*2),F.fillStyle=B?"#60a5fa":"#3b82f6",F.fill(),F.strokeStyle="#fff",F.lineWidth=1.5,F.stroke()}}F.strokeStyle="rgba(255,255,255,0.15)",F.lineWidth=1,F.setLineDash([4,4]);const O=L(0);F.beginPath(),F.moveTo(0,O),F.lineTo(N,O),F.stroke(),F.setLineDash([])},[k,n,j,C,L,f]);h.useEffect(()=>{G()},[G]);const q=E=>{var M;const F=(M=l.current)==null?void 0:M.getBoundingClientRect();if(!F)return;const N=E.clientX-F.left,$=E.clientY-F.top;c==="pencil"?(p(!0),m.current=[{time:T(N),value:D($)}]):(p(!0),m.current=[{time:T(N),value:D($)}])},A=E=>{var R;const F=(R=l.current)==null?void 0:R.getBoundingClientRect();if(!F)return;const N=E.clientX-F.left,$=E.clientY-F.top;u&&m.current.push({time:T(N),value:D($)});const M=[...k].sort((_,I)=>_.time-I.time);let O=null;for(const _ of M){const I=C(_.time),B=L(_.value);if(Math.abs(N-I)<8&&Math.abs($-B)<8){O=_.id;break}}y(O)},V=()=>{if(!u)return;p(!1);const E=m.current;if(E.length===0)return;const F=$i({mode:c,cc:t,resolution:.02,smoothing:c==="pencil"?.3:0},E);F.length>0&&a.setEvents(e,[...w,...F]),m.current=[]},te=E=>{var M;const F=(M=l.current)==null?void 0:M.getBoundingClientRect();if(!F)return;const N=E.clientX-F.left,$=E.clientY-F.top;for(const O of k){const R=C(O.time),_=L(O.value);if(Math.abs(N-R)<8&&Math.abs($-_)<8){a.removeEvent(e,O.id);return}}a.addEvent(e,{id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:D($),time:T(N)})},ee=()=>{const F=Ha(S,0,n,t,Math.ceil(n*20),120).map((N,$)=>({...N,id:Date.now()+$}));a.setEvents(e,[...w,...F]),v(!1)},W=()=>{const E=a.exportLane(e),F=new Blob([E],{type:"application/json"}),N=URL.createObjectURL(F),$=document.createElement("a");$.href=N,$.download=`cc-lane-${t}-layer-${e}.json`,document.body.appendChild($),$.click(),$.remove(),URL.revokeObjectURL(N)},Q=E=>{var N;const F=(N=E.target.files)==null?void 0:N[0];F&&(F.text().then($=>{a.importLane(e,$)}),x.current&&(x.current.value=""))};return o.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#e6edf3",borderRadius:8},children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[o.jsx("h6",{className:"mb-0",style:{color:"#58a6ff"},children:i("ccLane.title","CC Automation Lane")}),o.jsx("select",{className:"form-select form-select-sm",style:{width:160,background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"},value:t,onChange:E=>s(Number(E.target.value)),children:Pi.map(E=>o.jsxs("option",{value:E.cc,children:[E.label," (CC",E.cc,")"]},E.cc))}),o.jsx("div",{className:"btn-group btn-group-sm",children:["pencil","line","curve","step","ramp"].map(E=>o.jsx("button",{className:`btn ${c===E?"btn-primary":"btn-outline-secondary"}`,onClick:()=>d(E),style:{fontSize:11,textTransform:"capitalize"},children:E},E))}),o.jsxs("div",{className:"btn-group btn-group-sm",children:[o.jsx("button",{className:"btn btn-outline-secondary",onClick:a.undo,disabled:!a.canUndo,title:"Undo",children:"↩"}),o.jsx("button",{className:"btn btn-outline-secondary",onClick:a.redo,disabled:!a.canRedo,title:"Redo",children:"↪"})]}),o.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>v(!g),title:"Apply LFO modulation",children:"LFO"}),o.jsx("button",{className:"btn btn-sm btn-outline-warning",onClick:W,title:"Export CC lane as JSON",children:"Export"}),o.jsx("button",{className:"btn btn-sm btn-outline-success",onClick:()=>{var E;return(E=x.current)==null?void 0:E.click()},title:"Import CC lane from JSON",children:"Import"}),o.jsx("input",{ref:x,type:"file",accept:".json",style:{display:"none"},onChange:Q}),o.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:()=>a.setEvents(e,w.filter(E=>E.cc!==t)),title:"Clear all CC events for this lane",children:"Clear"}),o.jsxs("span",{style:{fontSize:11,color:"#8b949e",marginLeft:"auto"},children:[k.length," ",i("ccLane.events","events")]})]}),g&&o.jsx("div",{className:"mb-2 p-2",style:{background:"#161b22",borderRadius:6,border:"1px solid #30363d"},children:o.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-center mb-2",children:[o.jsxs("label",{style:{fontSize:12},children:["Wave:",o.jsx("select",{className:"form-select form-select-sm ms-1",style:{width:110,display:"inline-block",background:"#0d1117",color:"#e6edf3",border:"1px solid #30363d"},value:S.waveform,onChange:E=>b(F=>({...F,waveform:E.target.value})),children:["sine","triangle","sawtooth","square","random","sample-hold"].map(E=>o.jsx("option",{value:E,children:E},E))})]}),o.jsxs("label",{style:{fontSize:12},children:["Rate:",o.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:70,display:"inline-block",background:"#0d1117",color:"#e6edf3",border:"1px solid #30363d"},min:.01,max:20,step:.1,value:S.rate,onChange:E=>b(F=>({...F,rate:Number(E.target.value)}))})]}),o.jsxs("label",{style:{fontSize:12},children:["Depth:",o.jsx("input",{type:"range",min:0,max:1,step:.01,value:S.depth,onChange:E=>b(F=>({...F,depth:Number(E.target.value)})),style:{width:80}}),o.jsx("span",{style:{fontSize:11,marginLeft:4},children:S.depth.toFixed(2)})]}),o.jsxs("label",{style:{fontSize:12},children:["Center:",o.jsx("input",{type:"range",min:0,max:1,step:.01,value:S.center,onChange:E=>b(F=>({...F,center:Number(E.target.value)})),style:{width:80}}),o.jsx("span",{style:{fontSize:11,marginLeft:4},children:S.center.toFixed(2)})]}),o.jsx("button",{className:"btn btn-sm btn-primary",onClick:ee,children:"Apply LFO"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>v(!1),children:"Cancel"})]})}),o.jsx("div",{style:{overflowX:"auto",borderRadius:6},children:o.jsx("canvas",{ref:l,width:j,height:tr+Ht*2,style:{cursor:u?"crosshair":f?"pointer":"crosshair",display:"block",borderRadius:6},onMouseDown:q,onMouseMove:A,onMouseUp:V,onMouseLeave:()=>{u&&V()},onDoubleClick:te,role:"img","aria-label":"CC automation lane editor canvas"})}),o.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:4},children:i("ccLane.hint","Click to draw. Double-click to add/remove points. Drag to draw curves.")})]})},Za={"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},Xa={mode:"up",octaves:1,rate:"1/8",gate:.8,swing:0,repeats:1,latch:!1};function Ai(e,t){const n=[];for(let r=0;r<t;r++)for(const a of e)n.push({...a,pitch:a.pitch+r*12});return n}function Ja(e,t){if(e.length===0)return[];const n=Ai(e,t.octaves),r=[...n].sort((i,l)=>i.pitch-l.pitch),a=[...n].sort((i,l)=>l.pitch-i.pitch);let s;switch(t.mode){case"up":s=r;break;case"down":s=a;break;case"updown":s=[...r,...a.slice(1,-1)];break;case"downup":s=[...a,...r.slice(1,-1)];break;case"random":s=[...n].sort(()=>Math.random()-.5);break;case"as-played":s=[...n].sort((i,l)=>i.originalOrder-l.originalOrder);break;case"chord":s=n;break;default:s=r}if(t.repeats>1){const i=[];for(const l of s)for(let c=0;c<t.repeats;c++)i.push(l);s=i}return s}function Li(e,t,n,r=0,a=1){const s=Ja(e,t);if(s.length===0)return[];const i=60/n,l=Za[t.rate]*i,c=l*t.gate,d=[],u=t.mode==="chord",p=u?a:s.length*a;for(let m=0;m<p;m++){const f=m%2===1?l*t.swing*.5:0,y=r+m*l+f;if(u)for(const g of s){const v=t.velocityPattern?t.velocityPattern[m%t.velocityPattern.length]:g.velocity;d.push({pitch:g.pitch,velocity:v,startTime:y,duration:c,step:m})}else{const g=m%s.length,v=s[g],S=t.velocityPattern?t.velocityPattern[m%t.velocityPattern.length]:v.velocity;d.push({pitch:v.pitch,velocity:S,startTime:y,duration:c,step:m})}}return d}function Qa(){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 es(){return Object.keys(Za)}const Ni=({config:e,onChange:t,active:n,onToggleActive:r})=>{const{t:a}=Ce(),s=Qa(),i=es(),l=c=>t({...e,...c});return o.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#e6edf3",borderRadius:8,opacity:n?1:.6},children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[o.jsx("h6",{className:"mb-0",style:{color:"#58a6ff"},children:a("arp.title","Arpeggiator")}),o.jsx("button",{className:`btn btn-sm ${n?"btn-success":"btn-outline-secondary"}`,onClick:r,children:n?"ON":"OFF"}),o.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"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Xa),title:"Reset to defaults",children:"Reset"})]}),o.jsxs("div",{className:"row g-2",children:[o.jsxs("div",{className:"col-12",children:[o.jsx("label",{style:{fontSize:12},className:"mb-1",children:a("arp.mode","Mode")}),o.jsx("div",{className:"btn-group btn-group-sm w-100",children:s.map(c=>o.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))})]}),o.jsxs("div",{className:"col-6",children:[o.jsx("label",{style:{fontSize:12},className:"mb-1",children:a("arp.rate","Rate")}),o.jsx("select",{className:"form-select form-select-sm",style:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"},value:e.rate,onChange:c=>l({rate:c.target.value}),children:i.map(c=>o.jsx("option",{value:c,children:c},c))})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.octaves","Octaves"),": ",e.octaves]}),o.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.octaves,onChange:c=>l({octaves:Number(c.target.value)})})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.gate","Gate"),": ",Math.round(e.gate*100),"%"]}),o.jsx("input",{type:"range",className:"form-range",min:.05,max:1,step:.05,value:e.gate,onChange:c=>l({gate:Number(c.target.value)})})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.swing","Swing"),": ",Math.round(e.swing*100),"%"]}),o.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.swing,onChange:c=>l({swing:Number(c.target.value)})})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:12},className:"mb-1",children:[a("arp.repeats","Repeats"),": ",e.repeats]}),o.jsx("input",{type:"range",className:"form-range",min:1,max:4,step:1,value:e.repeats,onChange:c=>l({repeats:Number(c.target.value)})})]})]})]})},Ii=["sine","triangle","sawtooth","square","random","sample-hold"],Fi=["1/1","1/2","1/4","1/8","1/16","1/32"],Yt=200,Rt=48,Oi=({config:e,onChange:t,index:n,onRemove:r})=>{const{t:a}=Ce(),s=h.useRef(null),i=c=>t({...e,...c}),l=h.useCallback(()=>{const c=s.current;if(!c)return;const d=c.getContext("2d");if(!d)return;d.clearRect(0,0,Yt,Rt),d.fillStyle="#161b22",d.fillRect(0,0,Yt,Rt),d.strokeStyle="rgba(255,255,255,0.1)",d.lineWidth=1,d.setLineDash([3,3]),d.beginPath(),d.moveTo(0,Rt/2),d.lineTo(Yt,Rt/2),d.stroke(),d.setLineDash([]);const u=Ya(e,Yt,Rt);if(u.length>0){d.beginPath(),d.strokeStyle=e.enabled?"#3b82f6":"#484f58",d.lineWidth=1.5;for(let p=0;p<u.length;p++){const m=u[p].x,f=u[p].y;p===0?d.moveTo(m,f):d.lineTo(m,f)}d.stroke()}},[e]);return h.useEffect(()=>{l()},[l]),o.jsxs("div",{className:"card p-2 mb-2",style:{background:"#0d1117",color:"#e6edf3",borderRadius:8,opacity:e.enabled?1:.5},children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[o.jsxs("h6",{className:"mb-0",style:{color:"#58a6ff",fontSize:13},children:[a("lfo.title","LFO")," ",n!==void 0?`#${n+1}`:""]}),o.jsx("button",{className:`btn btn-sm ${e.enabled?"btn-success":"btn-outline-secondary"}`,onClick:()=>i({enabled:!e.enabled}),style:{fontSize:11,padding:"1px 8px"},children:e.enabled?"ON":"OFF"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>t(Wn()),style:{fontSize:11,padding:"1px 8px"},title:"Reset to defaults",children:"Reset"}),r&&o.jsx("button",{className:"btn btn-sm btn-outline-danger ms-auto",onClick:r,style:{fontSize:11,padding:"1px 8px"},children:"✕"})]}),o.jsxs("div",{className:"d-flex gap-2 flex-wrap align-items-start",children:[o.jsx("canvas",{ref:s,width:Yt,height:Rt,style:{borderRadius:4,border:"1px solid #30363d",flexShrink:0},role:"img","aria-label":"LFO waveform preview canvas"}),o.jsxs("div",{className:"flex-grow-1",children:[o.jsx("div",{className:"mb-1",children:o.jsx("div",{className:"btn-group btn-group-sm w-100",children:Ii.map(c=>o.jsx("button",{className:`btn ${e.waveform===c?"btn-primary":"btn-outline-secondary"}`,onClick:()=>i({waveform:c}),style:{fontSize:10,textTransform:"capitalize",padding:"1px 4px"},children:c==="sample-hold"?"S&H":c.slice(0,3)},c))})}),o.jsxs("div",{className:"row g-1",children:[o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:10},children:["Rate: ",e.rate.toFixed(1)," Hz"]}),o.jsx("input",{type:"range",className:"form-range",min:.01,max:20,step:.1,value:e.rate,onChange:c=>i({rate:Number(c.target.value)}),style:{height:16}})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:10},children:["Depth: ",Math.round(e.depth*100),"%"]}),o.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.depth,onChange:c=>i({depth:Number(c.target.value)}),style:{height:16}})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:10},children:["Center: ",Math.round(e.center*100),"%"]}),o.jsx("input",{type:"range",className:"form-range",min:0,max:1,step:.01,value:e.center,onChange:c=>i({center:Number(c.target.value)}),style:{height:16}})]}),o.jsxs("div",{className:"col-6",children:[o.jsxs("label",{style:{fontSize:10},children:["Phase: ",Math.round(e.phase),"°"]}),o.jsx("input",{type:"range",className:"form-range",min:0,max:360,step:1,value:e.phase,onChange:c=>i({phase:Number(c.target.value)}),style:{height:16}})]})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2 mt-1",children:[o.jsxs("label",{style:{fontSize:10},children:[o.jsx("input",{type:"checkbox",checked:e.syncToBpm,onChange:c=>i({syncToBpm:c.target.checked}),className:"form-check-input me-1",style:{marginTop:0,width:12,height:12}}),"BPM Sync"]}),e.syncToBpm&&o.jsx("select",{className:"form-select form-select-sm",style:{width:80,background:"#161b22",color:"#e6edf3",border:"1px solid #30363d",fontSize:11},value:e.syncDivision??"1/4",onChange:c=>i({syncDivision:c.target.value}),children:Fi.map(c=>o.jsx("option",{value:c,children:c},c))}),o.jsxs("label",{style:{fontSize:10},children:["CC:",o.jsx("input",{type:"number",className:"form-control form-control-sm ms-1",style:{width:55,display:"inline-block",background:"#161b22",color:"#e6edf3",border:"1px solid #30363d",fontSize:11},min:0,max:127,value:e.targetCC??1,onChange:c=>i({targetCC:Number(c.target.value)})})]})]})]})]})]})},Di=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Gi(e){const t=Math.floor(e/12)-1;return`${Di[e%12]}${t}`}const _i=({seq:e})=>{const{t}=Ce(),{pattern:n,currentStep:r,playing:a}=e,s=h.useMemo(()=>n.steps.slice(0,n.length),[n]);return o.jsxs("div",{className:"card p-3 mb-3",style:{background:"#0d1117",color:"#e6edf3",borderRadius:8},children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2 flex-wrap",children:[o.jsx("h6",{className:"mb-0",style:{color:"#58a6ff"},children:t("stepSeq.title","Step Sequencer")}),o.jsx("button",{className:`btn btn-sm ${a?"btn-danger":"btn-success"}`,onClick:e.togglePlayback,style:{minWidth:60},children:a?"■ Stop":"▶ Play"}),o.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["BPM:",o.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:70,background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"},min:20,max:300,value:n.bpm,onChange:i=>e.setBpm(Number(i.target.value))})]}),o.jsxs("label",{style:{fontSize:12,display:"flex",alignItems:"center",gap:4},children:["Swing:",o.jsx("input",{type:"range",min:0,max:1,step:.01,value:n.swing,onChange:i=>e.setSwing(Number(i.target.value)),style:{width:60}}),o.jsxs("span",{style:{fontSize:11,minWidth:28},children:[Math.round(n.swing*100),"%"]})]}),o.jsx("div",{className:"btn-group btn-group-sm",children:[16,32,64].map(i=>o.jsx("button",{className:`btn ${n.length===i?"btn-primary":"btn-outline-secondary"}`,onClick:()=>e.setLength(i),style:{fontSize:11},children:i},i))})]}),o.jsxs("div",{className:"d-flex gap-1 mb-2 flex-wrap",children:[o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(1),"aria-label":"Transpose up one semitone",children:"+1"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-1),"aria-label":"Transpose down one semitone",children:"-1"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(12),children:"+Oct"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.transpose(-12),children:"-Oct"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:e.reverse,children:"Reverse"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(1),children:"Shift →"}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>e.shift(-1),children:"← Shift"}),o.jsx("button",{className:"btn btn-sm btn-outline-info",onClick:()=>e.randomizeVel(),children:"Rnd Vel"}),o.jsx("button",{className:"btn btn-sm btn-outline-danger",onClick:e.clear,children:"Clear"})]}),o.jsx("div",{style:{overflowX:"auto"},children:o.jsx("div",{style:{display:"flex",gap:2,minWidth:n.length*36},children:s.map((i,l)=>{const c=i.active,d=r===l,u=l%4===0;return o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,minWidth:34},children:[o.jsx("span",{style:{fontSize:9,color:u?"#8b949e":"#30363d"},children:l+1}),o.jsx("button",{onClick:()=>e.toggle(l),style:{width:32,height:32,borderRadius:4,border:d?"2px solid #f0c040":"1px solid #30363d",background:c?`hsl(${210+i.velocity/127*40}, 80%, ${35+i.velocity/127*20}%)`:u?"#21262d":"#161b22",cursor:"pointer",padding:0,color:c?"#fff":"#484f58",fontSize:8,fontWeight:600,transition:"background 0.1s"},children:c?Gi(i.note):""}),o.jsx("div",{style:{width:32,height:20,background:"#161b22",borderRadius:2,position:"relative",overflow:"hidden"},children:o.jsx("div",{style:{position:"absolute",bottom:0,left:0,width:"100%",height:`${i.velocity/127*100}%`,background:c?"rgba(59, 130, 246, 0.6)":"rgba(59, 130, 246, 0.15)",borderRadius:2,cursor:"ns-resize"},title:`Vel: ${i.velocity}`,onMouseDown:p=>{p.preventDefault();const m=p.target.parentElement.getBoundingClientRect(),f=g=>{const v=g.clientY-m.top,S=Math.round(Math.max(1,Math.min(127,(1-v/m.height)*127)));e.setVelocity(l,S)},y=()=>{document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",y)};document.addEventListener("mousemove",f),document.addEventListener("mouseup",y)}})}),c&&i.probability<1&&o.jsxs("span",{style:{fontSize:8,color:"#f0c040"},children:[Math.round(i.probability*100),"%"]})]},l)})})}),o.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:6},children:t("stepSeq.hint","Click steps to toggle. Drag velocity bars vertically.")})]})},Bi="_panelNarrow_se2i3_3",zi="_panelWide_se2i3_9",Wi="_smallLabel_se2i3_19",Ui="_noteText_se2i3_29",qi="_buttonRow_se2i3_41",Vi="_noteTextMargin_se2i3_49",Ki="_rangeW100_se2i3_63",Hi="_zoomValue_se2i3_69",Yi="_selectW100_se2i3_77",Zi="_inputW70_se2i3_83",Xi="_masterVolGroup_se2i3_93",Ji="_rangeW140_se2i3_99",Qi="_volumeValue_se2i3_105",el="_selectW140_se2i3_115",tl="_freqGroup_se2i3_121",nl="_freqValue_se2i3_127",rl="_narrowGroup_se2i3_137",al="_rangeW120_se2i3_143",sl="_smallValue_se2i3_149",ol="_presetDivider_se2i3_159",il="_presetLabel_se2i3_165",ll="_presetBtn_se2i3_175",cl="_deletePresetSelect_se2i3_183",dl="_presetNameInput_se2i3_191",ul="_savePresetBtn_se2i3_199",hl="_countInAlert_se2i3_211",fl="_inputW80_se2i3_219",pl="_levelLabel_se2i3_225",ml="_levelMeter_se2i3_233",gl="_levelBar_se2i3_249",de={panelNarrow:Bi,panelWide:zi,smallLabel:Wi,noteText:Ui,buttonRow:qi,noteTextMargin:Vi,rangeW100:Ki,zoomValue:Hi,selectW100:Yi,inputW70:Zi,masterVolGroup:Xi,rangeW140:Ji,volumeValue:Qi,selectW140:el,freqGroup:tl,freqValue:nl,narrowGroup:rl,rangeW120:al,smallValue:sl,presetDivider:ol,presetLabel:il,presetBtn:ll,deletePresetSelect:cl,presetNameInput:dl,savePresetBtn:ul,countInAlert:hl,inputW80:fl,levelLabel:pl,levelMeter:ml,levelBar:gl},yl=({autoSaveMode:e,setAutoSaveMode:t,autoSaveInterval:n,setAutoSaveInterval:r})=>{const{t:a}=Ce();return o.jsxs("div",{className:`card p-3 mb-3 ${de.panelNarrow}`,children:[o.jsx("h6",{className:"mb-2",children:a("editorPanels.autoSaveTitle","Project auto-save")}),o.jsxs("div",{className:"mb-2",children:[o.jsxs("label",{className:"form-label",children:[a("editorPanels.autoSaveMode","Auto-save mode"),":"]}),o.jsxs("select",{className:"form-select",value:e,onChange:s=>t(s.target.value),children:[o.jsx("option",{value:"off",children:a("editorPanels.off","Off")}),o.jsx("option",{value:"onChange",children:a("editorPanels.onChange","On every change")}),o.jsx("option",{value:"interval",children:a("editorPanels.interval","At set interval")}),o.jsx("option",{value:"both",children:a("editorPanels.both","Both")})]})]}),(e==="interval"||e==="both")&&o.jsxs("div",{className:"mb-2",children:[o.jsxs("label",{className:"form-label",children:[a("editorPanels.autoSaveFrequency","Auto-save frequency (seconds)"),":"]}),o.jsx("input",{type:"number",className:"form-control",min:5,max:600,value:n,onChange:s=>r(Math.max(5,Math.min(600,Number(s.target.value))))})]}),o.jsxs("div",{className:de.noteText,children:[o.jsxs("b",{children:[a("editorPanels.noteLabel","Note"),":"]})," ",a("editorPanels.autoSaveNote","Auto-save works locally (localStorage/browser). Manual save (PUT) always overwrites the project on the server.")]})]})},bl=({undoCount:e,redoCount:t,onUndo:n,onRedo:r})=>{const{t:a}=Ce();return o.jsxs("div",{className:`card p-3 mb-3 ${de.panelNarrow}`,children:[o.jsx("h6",{className:"mb-2",children:a("editorPanels.changeHistory","Project change history")}),o.jsxs("div",{className:de.buttonRow,children:[o.jsxs("button",{className:"btn btn-secondary",onClick:n,disabled:e===0,title:a("editorPanels.undoTitle","Undo last change (Ctrl+Z)"),children:["↩️ ",a("editorPanels.undo","Undo")]}),o.jsxs("button",{className:"btn btn-secondary",onClick:r,disabled:t===0,title:a("editorPanels.redoTitle","Redo change (Ctrl+Y or Ctrl+Shift+Z)"),children:["↪️ ",a("editorPanels.redo","Redo")]})]}),o.jsx("div",{className:de.noteTextMargin,children:a("editorPanels.undoRedoNote","Undo/Redo works on the entire project (all editor changes). After each change Redo is cleared.")})]})},vl=({zoom:e,setZoom:t,uiZoom:n,setUiZoom:r,snapEnabled:a,onToggleSnap:s,snapMode:i,onSnapModeChange:l,bpm:c,setBpm:d})=>{const{t:u}=Ce();return o.jsx("div",{className:`card p-2 mb-3 ${de.panelNarrow}`,children:o.jsxs("div",{className:"d-flex align-items-center gap-3",children:[o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("label",{className:`form-label mb-0 ${de.smallLabel}`,children:"Zoom:"}),o.jsx("input",{type:"range",min:"0.5",max:"5",step:"0.1",value:e,onChange:p=>t(Number(p.target.value)),className:de.rangeW100}),o.jsxs("span",{className:de.zoomValue,children:[e.toFixed(1),"x"]})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("label",{className:`form-label mb-0 ${de.smallLabel}`,children:"Zoom UI:"}),o.jsx("input",{type:"range",min:"1",max:"4",step:"0.1",value:n,onChange:p=>r(Number(p.target.value)),className:de.rangeW100}),o.jsxs("span",{className:de.zoomValue,children:[n.toFixed(1),"x"]})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("input",{id:"snap-toggle",type:"checkbox",className:"form-check-input",checked:a,onChange:s}),o.jsx("label",{htmlFor:"snap-toggle",className:`form-check-label mb-0 ${de.smallLabel}`,children:"Snap"})]}),a&&o.jsxs("select",{className:`form-select form-select-sm ${de.selectW100}`,value:i,onChange:p=>l(p.target.value),children:[o.jsx("option",{value:"bar",children:u("editorPanels.snapBar","Bar")}),o.jsx("option",{value:"beat",children:u("editorPanels.snapBeat","Beat")}),o.jsx("option",{value:"sub-beat",children:u("editorPanels.snap16","1/16")}),o.jsx("option",{value:"second",children:u("editorPanels.snapSecond","Second")})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("label",{className:`form-label mb-0 ${de.smallLabel}`,children:"BPM:"}),o.jsx("input",{type:"number",className:`form-control form-control-sm ${de.inputW70}`,value:c,onChange:p=>d(Number(p.target.value)),min:"20",max:"300"})]})]})})},xl=({masterVolume:e,onMasterVolumeChange:t,filterType:n,filterFreq:r,filterQ:a,filterGain:s,onFilterChange:i,masterEQPresets:l,customPresets:c,onLoadPreset:d,onSavePreset:u,onDeletePreset:p})=>{const{t:m}=Ce();return o.jsxs("div",{className:`card p-2 mb-3 ${de.panelWide}`,children:[o.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[o.jsxs("div",{className:`d-flex align-items-center gap-2 ${de.masterVolGroup}`,children:[o.jsx("label",{className:`form-label mb-0 ${de.smallLabel}`,children:"Master Vol"}),o.jsx("input",{type:"range",min:"0",max:"1",step:"0.01",value:e,onChange:f=>t(Number(f.target.value)),className:de.rangeW140}),o.jsxs("span",{className:de.volumeValue,children:[Math.round(e*100),"%"]})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("label",{className:`form-label mb-0 ${de.smallLabel}`,children:"Filter"}),o.jsx("select",{className:`form-select form-select-sm ${de.selectW140}`,value:n,onChange:f=>i({type:f.target.value}),children:["peaking","lowpass","highpass","lowshelf","highshelf","notch","bandpass"].map(f=>o.jsx("option",{value:f,children:f},f))})]}),o.jsxs("div",{className:`d-flex align-items-center gap-2 ${de.freqGroup}`,children:[o.jsx("span",{className:de.smallLabel,children:"Freq"}),o.jsx("input",{type:"range",min:"40",max:"12000",step:"10",value:r,onChange:f=>i({frequency:Number(f.target.value)}),className:de.rangeW140}),o.jsxs("span",{className:de.freqValue,children:[Math.round(r)," Hz"]})]}),o.jsxs("div",{className:`d-flex align-items-center gap-2 ${de.narrowGroup}`,children:[o.jsx("span",{className:de.smallLabel,children:"Q"}),o.jsx("input",{type:"range",min:"0.1",max:"12",step:"0.1",value:a,onChange:f=>i({q:Number(f.target.value)}),className:de.rangeW120}),o.jsx("span",{className:de.smallValue,children:a.toFixed(1)})]}),(n==="peaking"||n==="lowshelf"||n==="highshelf")&&o.jsxs("div",{className:`d-flex align-items-center gap-2 ${de.narrowGroup}`,children:[o.jsx("span",{className:de.smallLabel,children:"Gain"}),o.jsx("input",{type:"range",min:"-18",max:"18",step:"0.5",value:s,onChange:f=>i({gain:Number(f.target.value)}),className:de.rangeW120}),o.jsxs("span",{className:de.smallValue,children:[s.toFixed(1)," dB"]})]})]}),o.jsxs("div",{className:`mt-2 pt-2 ${de.presetDivider}`,children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[o.jsxs("span",{className:de.presetLabel,children:[m("editorPanels.eqPresets","EQ Presets"),":"]}),[...l,...c].map(f=>o.jsx("button",{className:`btn btn-sm btn-outline-secondary ${de.presetBtn}`,onClick:()=>d(f),children:f.name},f.name)),c.length>0&&o.jsxs("select",{className:`form-select form-select-sm ${de.deletePresetSelect}`,onChange:f=>{f.target.value&&(p(f.target.value),f.target.value="")},defaultValue:"",children:[o.jsx("option",{value:"",children:m("editorPanels.deletePreset","Delete preset...")}),c.map(f=>o.jsx("option",{value:f.name,children:f.name},f.name))]})]}),o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsx("input",{type:"text",className:`form-control form-control-sm ${de.presetNameInput}`,placeholder:m("editorPanels.presetName","Preset name..."),id:"presetNameInput"}),o.jsx("button",{className:`btn btn-sm btn-success ${de.savePresetBtn}`,onClick:()=>{const f=document.getElementById("presetNameInput");f!=null&&f.value.trim()&&(u(f.value.trim()),f.value="")},children:m("editorPanels.saveCurrent","Save Current")})]})]})]})},Sl=({countInBars:e,setCountInBars:t,isCountIn:n,countInRemaining:r,overdubEnabled:a,setOverdubEnabled:s,punchIn:i,setPunchIn:l,punchOut:c,setPunchOut:d,monitorLevel:u})=>{const{t:p}=Ce();return o.jsx("div",{className:`card p-2 mb-3 ${de.panelWide}`,children:o.jsxs("div",{className:"d-flex align-items-center flex-wrap gap-3",children:[o.jsxs("div",{className:"d-flex align-items-center gap-2",children:[o.jsxs("label",{className:`form-label mb-0 ${de.smallLabel}`,children:[p("editorPanels.countIn","Count-in (bars)"),":"]}),o.jsx("input",{type:"number",min:"0",max:"8",step:"1",className:`form-control form-control-sm ${de.inputW70}`,value:e,onChange:m=>t(Number(m.target.value))}),n&&o.jsxs("span",{className:de.countInAlert,children:["Count-in: ",r.toFixed(1),"s"]})]}),o.jsxs("div",{className:"form-check d-flex align-items-center gap-2",children:[o.jsx("input",{id:"overdub-toggle",className:"form-check-input",type:"checkbox",checked:a,onChange:m=>s(m.target.checked)}),o.jsx("label",{htmlFor:"overdub-toggle",className:`form-check-label ${de.smallLabel}`,children:p("editorPanels.overdub","Overdub (play background)")})]}),o.jsxs("div",{className:"d-flex align-items-center gap-1",children:[o.jsx("span",{className:de.smallLabel,children:"Punch In"}),o.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${de.inputW80}`,value:i??"",onChange:m=>l(m.target.value===""?null:Number(m.target.value))}),o.jsx("span",{className:de.smallLabel,children:"s"})]}),o.jsxs("div",{className:"d-flex align-items-center gap-1",children:[o.jsx("span",{className:de.smallLabel,children:"Punch Out"}),o.jsx("input",{type:"number",min:"0",step:"0.1",className:`form-control form-control-sm ${de.inputW80}`,value:c??"",onChange:m=>d(m.target.value===""?null:Number(m.target.value))}),o.jsx("span",{className:de.smallLabel,children:"s"})]}),o.jsx("button",{className:"btn btn-sm btn-outline-secondary",onClick:()=>{l(null),d(null)},children:p("editorPanels.clearPunch","Clear punch")}),o.jsx("div",{className:de.levelLabel,children:"Level"}),o.jsx("div",{className:de.levelMeter,children:o.jsx("div",{className:de.levelBar,style:{width:`${Math.min(1,u*2)*100}%`,background:u>.7?"#f44336":"#4caf50"}})})]})})};function wl(e,t,n){const[r,a]=h.useState("interval"),[s,i]=h.useState(30),l=h.useRef(null),c=h.useCallback(()=>{if(e)try{localStorage.setItem("audioEditor.autoSave",JSON.stringify(e)),t("Project auto-saved locally"),n("success"),setTimeout(()=>t(""),2e3)}catch(d){t("Auto-save error: "+d.message),n("error")}},[e,t,n]);return h.useEffect(()=>{(r==="onChange"||r==="both")&&c()},[e,r,c]),h.useEffect(()=>(l.current&&(clearInterval(l.current),l.current=null),(r==="interval"||r==="both")&&s>0&&(l.current=window.setInterval(c,s*1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[r,s,c]),{autoSaveMode:r,setAutoSaveMode:a,autoSaveInterval:s,setAutoSaveInterval:i}}function Cl(e,t,n){const r=h.useRef(null),[a,s]=h.useState(!1),[i,l]=h.useState(0),[c,d]=h.useState(10),[u,p]=h.useState(!1),[m,f]=h.useState(120),y=h.useCallback((T,D)=>`L${T}-C${D}`,[]),g=h.useCallback((T,D)=>{if(!r.current||!D.audioBuffer)return;const C=y(T,D.id),L=e[T];r.current.addClip({id:C,buffer:D.audioBuffer,startTime:D.start,offset:0,duration:D.duration,layerId:T,volume:(L==null?void 0:L.volume)??1,pan:(L==null?void 0:L.pan)??0,stretchFactor:D.stretchFactor||1,effectChain:(L==null?void 0:L.effectChain)||[]})},[e,y]),v=h.useCallback((T,D)=>{var C;(C=r.current)==null||C.removeClip(y(T,D))},[y]);h.useEffect(()=>{Object.entries(t).forEach(([T,D])=>{const C=Number(T);D==null||D.forEach(L=>g(C,L))})},[t,e,g]),h.useEffect(()=>{r.current&&Object.entries(n).forEach(([T,D])=>{const C=Number(T);r.current.setMidiCCEvents(C,D)})},[n]);const S=h.useCallback(()=>{r.current&&(a?r.current.pause():r.current.play())},[a]),b=h.useCallback(()=>{var T;(T=r.current)==null||T.stop()},[]),x=h.useCallback(T=>{var D;(D=r.current)==null||D.seek(T)},[]),w=h.useCallback(()=>{if(!r.current)return;const T=!u;p(T),r.current.setLoopRegion(0,c,T)},[u,c]),k=h.useCallback(T=>{var C;const D=Math.max(1,c+T);d(D),(C=r.current)==null||C.setLoopRegion(0,D,u)},[c,u]),j=h.useCallback(async(T,D=1024)=>{const C=await T.arrayBuffer(),L=new(window.AudioContext||window.webkitAudioContext),G=await L.decodeAudioData(C.slice(0)),q=G.getChannelData(0),A=q.length,V=Math.max(1,Math.floor(A/D)),te=[];for(let ee=0;ee<D;ee++){const W=ee*V;if(W>=A)break;te.push(q[W])}return L.close(),{waveform:te.map(ee=>Math.max(-1,Math.min(1,ee))),duration:G.duration,buffer:G}},[]);return{engineRef:r,isPlaying:a,setIsPlaying:s,currentTime:i,setCurrentTime:l,duration:c,setDuration:d,isLooping:u,setIsLooping:p,bpm:m,setBpm:f,handlePlayPause:S,handleStop:b,handleSeek:x,handleToggleLoop:w,handleAdjustDuration:k,upsertEngineClip:g,removeEngineClip:v,makeEngineClipId:y,blobToWaveform:j}}class ts{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 a=this.audioContext.createMediaStreamSource(this.stream);t.gain!==void 0&&t.gain>0&&(this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t.gain,a.connect(this.gainNode),a=this.gainNode),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,a.connect(this.analyser),t.monitorEnabled&&(this.monitorGain=this.audioContext.createGain(),this.monitorGain.gain.value=(t.monitorVolume??100)/100,a.connect(this.monitorGain),this.monitorGain.connect(this.audioContext.destination));const s=()=>{if(!this.analyser)return;const i=new Uint8Array(this.analyser.fftSize);this.analyser.getByteTimeDomainData(i);let l=0;for(let d=0;d<i.length;d++){const u=(i[d]-128)/128;l+=u*u}const c=Math.sqrt(l/i.length);this.levelCallback&&this.levelCallback(c),this.isRecording&&(this.levelRaf=requestAnimationFrame(s))};this.mediaRecorder.ondataavailable=i=>{i.data&&i.data.size>0&&this.audioChunks.push(i.data)},this.mediaRecorder.start(),this.isRecording=!0,this.levelRaf=requestAnimationFrame(s)}getStream(){return this.stream}async stopRecording(){return!this.isRecording||!this.mediaRecorder?null:new Promise(t=>{const n=this.mediaRecorder;n.onstop=()=>{const r=new Blob(this.audioChunks,{type:n.mimeType});this.cleanup(),t(r)},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 Ml(e){const[t,n]=h.useState(!1),[r,a]=h.useState(!1),[s,i]=h.useState(0),[l,c]=h.useState(0),[d,u]=h.useState(null),p=h.useRef(null),m=h.useRef(null),f=h.useRef(0),y=h.useRef(null),g=h.useRef(null),v=h.useCallback(()=>{y.current&&(clearInterval(y.current),y.current=null),g.current&&(clearTimeout(g.current),g.current=null)},[]),S=h.useCallback(async()=>{if(!e.activeLayer){e.showToast("Select a layer to record.","error");return}t||(p.current||(p.current=new ts),f.current=m.current??e.currentTime,n(!0),i(0),await p.current.startRecording({onLevel:i}))},[e,t]),b=h.useCallback(async()=>{var q;if(v(),a(!1),c(0),m.current=null,!p.current){n(!1),i(0);return}const k=await p.current.stopRecording();if(n(!1),i(0),!k||!e.activeLayer)return;const{waveform:j,duration:T,buffer:D}=await e.blobToWaveform(k),C=e.activeLayer.id;e.setWaveforms(A=>({...A,[C]:j}));const L=Math.max(0,f.current||0),G={id:Date.now(),label:"Recording",start:L,duration:T,fadeIn:0,fadeOut:0,reverse:!1,stretchFactor:1,color:(q=e.layerSettings[C])==null?void 0:q.color,blob:k,blobUrl:URL.createObjectURL(k),audioBuffer:D};e.setLayerClips(A=>({...A,[C]:[...A[C]||[],G]})),e.upsertEngineClip(C,G),e.setSelectedClip({layerId:C,clipId:G.id})},[e,v]),x=h.useCallback(k=>{if(k<=0){S();return}a(!0),c(k);const j=performance.now();y.current=window.setInterval(()=>{const T=(performance.now()-j)/1e3;c(Math.max(0,k-T))},100),g.current=window.setTimeout(()=>{v(),a(!1),c(0),m.current||S()},k*1e3)},[S,v]),w=h.useCallback(async()=>{if(t||r){await b();return}if(!e.activeLayer){e.showToast("Select a layer before recording","error");return}const k=Math.max(0,e.countInBars)*4*(60/e.bpm),j=e.punchIn!=null&&e.punchIn>e.currentTime?e.punchIn:null;j&&(m.current=j),e.overdubEnabled&&!e.isPlaying&&e.playEngine(),j?k>0&&x(k):x(k)},[t,r,e,b,x]);return{isRecording:t,isCountIn:r,monitorLevel:s,countInRemaining:l,punchOut:d,setPunchOut:u,armedPunchInRef:m,recorderRef:p,clearCountInTimers:v,startRecordingNow:S,stopRecordingFlow:b,handleRecord:w}}var ns=(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))(ns||{});const kl={};class gn{constructor(t,n,r,a={}){this.type=t,this.name=n,this.component=kl[t]??(()=>null),this.audioType=r,this.parameters=a}}new gn("Recorder","Recorder","vocal",{deviceId:"",gain:1,sensitivity:"high"}),new gn("Audio Clip","Audio Clip","instrumental",{clipId:null,octave:"4"}),new gn("Speech Synth","Speech Synth","vocal",{text:"",voice:"default"}),new gn("Keyboard/Pads","Keyboard","instrumental",{instrument:"piano",preset:"default",velocity:100});function rs(e,t,n,r,a){n(s=>t?[...s,t]:s),r([]),a(e)}function $l(e,t,n,r){t(a=>{if(a.length===0)return a;const s=a[a.length-1];return n(i=>e?[e,...i]:i),r(s),a.slice(0,-1)})}function Rl(e,t,n,r){n(a=>{if(a.length===0)return a;const s=a[0];return t(i=>e?[...i,e]:i),r(s),a.slice(1)})}const jl="[useProjectCRUD]";function Tl(e){const{project:t,activeSection:n,setProject:r,setActiveSection:a,setLayers:s,setActiveLayer:i,setUndoStack:l,setRedoStack:c}=e,d=h.useCallback(v=>rs(v,t,l,c,r),[t,l,c,r]),u=h.useCallback(async()=>{var x;if(!t)return;const v=(((x=t.sections)==null?void 0:x.length)??0)+1,b={id:await e.addSection(t.id,"Section",v),projectId:t.id,name:"Section",orderNumber:v,layers:[]};d({...t,sections:[...t.sections||[],b]}),a(b)},[t,d,a]),p=h.useCallback(async v=>{var x,w,k;if(!t||!await e.confirm("Delete this section?"))return;await e.deleteSection(v);const b=(t.sections??[]).filter(j=>j.id!==v);d({...t,sections:b}),a(b[0]??null),s(((x=b[0])==null?void 0:x.layers)??[]),i(((k=(w=b[0])==null?void 0:w.layers)==null?void 0:k[0])??null)},[t,d,a,s,i,e]),m=h.useCallback(async()=>{var S;if(!n)return;const v={id:-Date.now(),name:"New Layer",sectionId:n.id,audioSource:ns.AudioClip,audioSourceParameters:JSON.stringify({clipId:null}),items:[]};s(b=>[...b,v]),i(v);try{const b=await e.addLayer(n.id,v.name,v.audioSource,v.audioSourceParameters);s(x=>x.map(w=>w.id===v.id?{...v,id:b}:w)),t&&d({...t,sections:((S=t.sections)==null?void 0:S.map(x=>x.id===n.id?{...x,layers:[...(x.layers??[]).filter(w=>w.id!==b),{...v,id:b}]}:x))??[]})}catch(b){s(x=>x.filter(w=>w.id!==v.id)),console.error(jl,"Failed to add layer:",b)}},[n,t,d,s,i]),f=h.useCallback(async v=>{var b,x;if((b=e.layerSettings[v])!=null&&b.locked){e.showToast("Layer is locked. Unlock to delete.","error");return}await e.confirm("Delete this layer?")&&((e.layerClips[v]||[]).forEach(w=>e.removeEngineClip(v,w.id)),e.setLayerMidiNotes(w=>{const k={...w};return delete k[v],k}),await e.deleteLayer(v),s(w=>w.filter(k=>k.id!==v)),i(w=>(w==null?void 0:w.id)===v?null:w),t&&d({...t,sections:((x=t.sections)==null?void 0:x.map(w=>w.id===(n==null?void 0:n.id)?{...w,layers:(w.layers??[]).filter(k=>k.id!==v)}:w))??[]}))},[t,n,d,s,i,e]),y=h.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]),g=h.useCallback(async()=>{var b;if(!n)return;const v=e.sectionName||n.name,S=e.sectionOrder===""?n.orderNumber:Number(e.sectionOrder);if(!v.trim()){e.setStatusType("error"),e.setStatusMessage("Section name cannot be empty");return}if(Number.isNaN(S)){e.setStatusType("error"),e.setStatusMessage("Order musi byc liczba");return}await e.updateSection(n.id,{name:v,orderNumber:S}),a({...n,name:v,orderNumber:S}),t&&d({...t,sections:((b=t.sections)==null?void 0:b.map(x=>x.id===n.id?{...x,name:v,orderNumber:S}:x))??[]}),e.setStatusType("success"),e.setStatusMessage("Section saved")},[n,t,e,d,a]);return{handleAddSection:u,handleDeleteSection:p,handleAddLayer:m,handleDeleteLayer:f,handleSaveProject:y,handleSaveSection:g}}const as=h.createContext(null);function Pl(){const e=h.useContext(as);if(!e)throw new Error("useEditorTrack must be used within <EditorTrackProvider>");return e}const ss=({value:e,children:t})=>o.jsx(as.Provider,{value:e,children:t});ss.displayName="EditorTrackProvider";const Ft=(e,t)=>t&&t>0?e*15/t:e/10,Tr=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const r=parseFloat(n.substring(5).replace(",","."));if(isFinite(r)&&r>0)return r}}return null},El=(e,t)=>{const n=t??Tr(e),r=[];let a="",s=0,i="",l=!0;function c(){i.trim()!==""&&(a.length>0&&(a+=" "),a+=i.trim()),i=""}return e.forEach(d=>{if(!(d.startsWith("#")||d.startsWith("E"))){if(d.startsWith("-"))c(),a.trim().length>0&&(r.push({text:a.trim(),timestamp:s}),a=""),l=!0;else if(d.startsWith(":")||d.startsWith("*")){const u=d.indexOf(" "),p=d.indexOf(" ",u+1),m=d.indexOf(" ",p+1),f=d.indexOf(" ",m+1);if(f===-1)return;const y=Ft(parseFloat(d.substring(u+1,p)),n);a===""&&(s=y);const g=d.substring(f+1);if(g.trim()==="~")return;let v=g;v.startsWith("~")&&(v=v.substring(1)),l?(c(),i=v.trimEnd()):i+=v.trimEnd(),l=g.endsWith(" ")}}}),c(),a.trim().length>0&&r.push({text:a.trim(),timestamp:s}),r},Al=(e,t)=>{const n=t??Tr(e),r=[];let a=[],s="",i=0,l=!0,c=null,d="";function u(){c&&d.trim()!==""&&(c.text=d.trim(),a.push({...c}),s.length>0&&(s+=" "),s+=c.text),c=null,d=""}return e.forEach(p=>{if(!(p.startsWith("#")||p.startsWith("E"))){if(p.startsWith("-"))u(),s.trim().length>0&&(r.push({text:s.trim(),timestamp:i,words:a}),s="",a=[]),l=!0;else if(p.startsWith(":")||p.startsWith("*")){const m=p.startsWith("*"),f=p.indexOf(" "),y=p.indexOf(" ",f+1),g=p.indexOf(" ",y+1),v=p.indexOf(" ",g+1);if(v===-1)return;const S=Ft(parseFloat(p.substring(f+1,y)),n),b=Ft(parseFloat(p.substring(y+1,g)),n),x=S+b;s===""&&(i=S);const w=p.substring(v+1);if(w.trim()==="~"){c&&(c.endTime=x);return}let k=w;k.startsWith("~")&&(k=k.substring(1)),l?(u(),d=k.trimEnd(),c={text:"",startTime:S,endTime:x,isGolden:m}):c?(d+=k.trimEnd(),c.endTime=x,m&&(c.isGolden=!0)):(d=k.trimEnd(),c={text:"",startTime:S,endTime:x,isGolden:m}),l=w.endsWith(" ")}}}),u(),s.trim().length>0&&r.push({text:s.trim(),timestamp:i,words:a}),r},os=(e,t)=>{const n=t??Tr(e),r=[];let a=[],s=0;function i(){a.length>0&&(r.push({timestamp:s,syllables:[...a]}),a=[])}return e.forEach(l=>{if(!(l.startsWith("#")||l.startsWith("E"))){if(l.startsWith("-")){i();const c=l.trim().split(/\s+/);if(c.length>=2){const d=parseFloat(c[1]);isFinite(d)&&(s=Ft(d,n))}}else if(l.startsWith(":")||l.startsWith("*")){const c=l.startsWith("*"),d=l.indexOf(" "),u=l.indexOf(" ",d+1),p=l.indexOf(" ",u+1),m=l.indexOf(" ",p+1);if(m===-1)return;const f=parseFloat(l.substring(d+1,u)),y=parseFloat(l.substring(u+1,p)),g=Ft(f,n),v=g+Ft(y,n);a.length===0&&(s=g);const S=l.substring(m+1);if(S.trim()==="~"){a.length>0&&(a[a.length-1].endTime=v);return}let b=S;b.startsWith("~")&&(b=b.substring(1));const x=S.endsWith(" "),w=x?b.slice(0,-1):b;a.push({text:w,startTime:g,endTime:v,isGolden:c,hasTrailingSpace:x})}}}),i(),r},Ll=(e,t,n=3)=>{const r=[];let a=-1;for(let s=0;s<e.length;s++){const i=e[s].timestamp,l=e[s+1]?e[s+1].timestamp:i+5;if(t>=i&&t<l){a=s;break}}if(a>=0){const s=Math.max(0,a-(n-1));for(let i=s;i<=a;i++)r.push(e[i].text)}return r},Nl=(e,t)=>{const n=[];for(const r of e)for(const a of r.words)t>=a.startTime&&t<=a.endTime&&n.push(a);return n},ra="var(--karaoke-sung-gradient, linear-gradient(90deg, #00e5ff 0%, #ffe600 60%, #ffab00 100%))",aa="var(--karaoke-gold-glow-first, 0 0 12px #FFD700)",Il="var(--karaoke-active-glow, 0 0 10px rgba(0,229,255,0.6), 0 0 4px rgba(255,230,0,0.4))",Fl="var(--karaoke-active-drop-first, 0 0 6px rgba(0,229,255,0.5))",Ol=({song:e,currentTime:t})=>{const n=h.useMemo(()=>!e||!e.notes.length?[]:os(e.notes.map(l=>l.noteLine),e.bpm??void 0),[e]),r=t-(e.gap??0)/1e3;let a=-1;for(let l=0;l<n.length;l++){const c=n[l].timestamp,d=l+1<n.length?n[l+1].timestamp:c+30;if(r>=c&&r<d){a=l;break}}const s=a>=0?n[a]:null,i=a>=0&&a+1<n.length?n[a+1]:null;return o.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:s?o.jsxs(o.Fragment,{children:[o.jsx("p",{style:{color:"var(--karaoke-primary-text, #fff)",margin:"5px 0",lineHeight:1.4,textShadow:Il,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:s.syllables.map((l,c)=>{let d=0;r>=l.endTime?d=1:r>l.startTime&&(d=(r-l.startTime)/(l.endTime-l.startTime));const u=Math.round(d*100),p=l.text+(l.hasTrailingSpace?" ":""),m=d>0&&d<1,f=l.isGolden;return d<=0?o.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",transition:"color 0.15s ease"},children:p},c):d>=1?o.jsx("span",{style:{background:f?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":ra,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",filter:f?`drop-shadow(${aa})`:"none",transition:"filter 0.2s ease"},children:p},c):o.jsxs("span",{style:{position:"relative",display:"inline",filter:m?f?`drop-shadow(${aa})`:`drop-shadow(${Fl})`:"none",transition:"filter 0.15s ease"},children:[o.jsx("span",{style:{color:"var(--karaoke-syllable-dim, rgba(255,255,255,0.85))",visibility:"visible"},children:p}),o.jsx("span",{style:{position:"absolute",left:0,top:0,background:f?"var(--karaoke-gold-gradient, linear-gradient(90deg, #FFD700, #FFA000, #FFD700))":ra,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",clipPath:`inset(0 ${100-u}% 0 0)`,pointerEvents:"none"},children:p})]},c)})}),i&&o.jsx("p",{style:{color:"var(--karaoke-next-text, #666)",margin:"5px 0",lineHeight:1.4,fontSize:"22px",transition:"opacity 0.3s ease"},children:i.syllables.map((l,c)=>o.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?o.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:"🎵"}):o.jsx("p",{style:{color:"var(--karaoke-waiting-text, #999)"},children:"🎤 Waiting for lyrics..."})})},Dl=h.memo(Ol),is=e=>{for(const t of e){const n=t.trim();if(n.toUpperCase().startsWith("#BPM:")){const r=parseFloat(n.substring(5).replace(",","."));if(isFinite(r)&&r>0)return r}}return null},sa=(e,t)=>t&&t>0?e*15/t:e/10,Pr=(e,t)=>{const n=t??is(e),r=[];let a=[];return e.forEach(s=>{const i=s.split(" ");if(!(i.length<4))if(s.startsWith("-"))a.length>0&&(r.push(a),a=[]);else{const l=(i[0]||"").charAt(0),c=l==="*"||l==="G";a.push({startTime:sa(parseFloat(i[1]),n),duration:sa(parseFloat(i[2]),n),pitch:parseInt(i[3],10),isGold:c})}}),a.length>0&&r.push(a),r},ls=(e,t)=>{let r=(Math.round(12*Math.log2(e/440)+69)%12+12)%12;if(t!==null){for(;r-t>6;)r-=12;for(;r-t<-6;)r+=12}return r};function hr(e){if(typeof document>"u")return e;const t=/var\(\s*([^,\s)]+)\s*(?:,\s*([^)]+))?\)/,n=e.match(t);if(n){const r=n[1],a=n[2]?n[2].trim():"",s=getComputedStyle(document.documentElement).getPropertyValue(r).trim();return s||a||e}return e}function Gl(e){if(!e)return[128,128,128];const t=e.match(/^#([0-9a-f]{3,8})$/i);if(t){let r=t[1];if(r.length===3&&(r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]),r.length>=6)return[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.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 _l=1e3,Bl=20,zl=70,Wl=5,oa=26,ia="rgba(255,215,70,0.98)",la=new Map,Ul=(e,t,n,r,a)=>{const s=`g${a}`,i=`<?xml version="1.0" encoding="UTF-8"?>
2
+ <svg xmlns='http://www.w3.org/2000/svg' width='${r}' height='${r}' viewBox='0 0 ${r} ${r}'>
3
+ <defs>
4
+ <radialGradient id='g${s}' cx='50%' cy='40%' r='60%'>
5
+ <stop offset='0%' stop-color='hsl(${e} ${t}% ${n}%)' stop-opacity='1'/>
6
+ <stop offset='60%' stop-color='hsl(${e} ${Math.max(10,t-30)}% ${Math.min(90,n+10)}%)' stop-opacity='0.9'/>
7
+ <stop offset='100%' stop-color='rgba(0,0,0,0)' stop-opacity='0'/>
8
+ </radialGradient>
9
+ </defs>
10
+ <g transform='translate(${r/2}, ${r/2})'>
11
+ <circle cx='0' cy='0' r='${r*.45}' fill='url(#g${s})' />
12
+ </g>
13
+ </svg>`;return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`},ql=(e,t,n,r,a)=>{const s=`${e}-${t}-${n}-${Math.round(r)}-${a}`;let i=la.get(s);return i||(i=new Image,i.src=Ul(e,t,n,r,a),la.set(s,i),i)},Vl=e=>{const t=e.replace("#",""),n=parseInt(t.length===3?t[0]+t[0]:t.substring(0,2),16)/255,r=parseInt(t.length===3?t[1]+t[1]:t.substring(2,4),16)/255,a=parseInt(t.length===3?t[2]+t[2]:t.substring(4,6),16)/255,s=Math.max(n,r,a),i=Math.min(n,r,a);let l=0,c=0;const d=(s+i)/2;if(s!==i){const u=s-i;switch(c=d>.5?u/(2-s-i):u/(s+i),s){case n:l=(r-a)/u+(r<a?6:0);break;case r:l=(a-n)/u+2;break;case a:l=(n-r)/u+4;break}l/=6}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(d*100)}},Kl=(e,t,n,r=1)=>`hsla(${Math.round(e)}, ${Math.round(t)}%, ${Math.round(n)}%, ${r})`;function yn(e){try{const t=hr(e),[n,r,a]=Gl(t),s=i=>i.toString(16).padStart(2,"0");return`#${s(n)}${s(r)}${s(a)}`.toLowerCase()}catch{return"#ffcc00"}}function Hl(e,t,n,r,a,s){const i=Math.min(s,r/2,a/2);e.beginPath(),e.moveTo(t+i,n),e.lineTo(t+r-i,n),e.quadraticCurveTo(t+r,n,t+r,n+i),e.lineTo(t+r,n+a-i),e.quadraticCurveTo(t+r,n+a,t+r-i,n+a),e.lineTo(t+i,n+a),e.quadraticCurveTo(t,n+a,t,n+a-i),e.lineTo(t,n+i),e.quadraticCurveTo(t,n,t+i,n),e.closePath()}function Yl(e){const{ctx:t,ballX:n,height:r,playerColor:a,currentTime:s}=e;t.save(),t.globalCompositeOperation="source-over";const i=t.createLinearGradient(Math.max(0,n-60),0,n,0);i.addColorStop(0,"rgba(0,0,0,0)"),i.addColorStop(1,a),t.globalAlpha=.18,t.fillStyle=i,t.fillRect(Math.max(0,n-60),0,60,r),t.globalAlpha=.9,t.strokeStyle=a,t.lineWidth=3,t.shadowColor=a,t.shadowBlur=12,t.beginPath(),t.moveTo(n,0),t.lineTo(n,r),t.stroke();const l=6+Math.sin(s*6)*2;t.fillStyle=e.ballIsGold?"#FFD700":a,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?"#FFD700":a,t.fillRect(c.x,c.y,c.w,c.h));t.restore()}function Zl(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:s,ballIsGold:i,currentTime:l}=e,c=3,d=a*1.5,u=l*4;t.save();for(let m=0;m<c;m++){const f=(u+m*2.1)%(Math.PI*2),y=Math.sin(f)*.5+.5,g=d+y*a*3,v=(1-y)*.5;t.globalAlpha=v,t.strokeStyle=i?"#FFD700":s,t.lineWidth=2-y,t.beginPath(),t.arc(n,r,g,0,Math.PI*2),t.stroke()}t.globalAlpha=.8,t.shadowColor=i?"#FFD700":s,t.shadowBlur=16+Math.sin(l*8)*4,t.fillStyle=i?"#FFF0A8":s;const p=a*(.8+Math.sin(l*10)*.2);t.beginPath(),t.arc(n,r,p,0,Math.PI*2),t.fill();for(const m of e.visibleNotes){if(!m.isSung)continue;const f=(l*6+m.x*.01)%(Math.PI*2),y=.15+Math.sin(f)*.1;t.globalAlpha=y,t.fillStyle=m.isGold?"#FFD700":s,t.fillRect(m.x,m.y,m.w,m.h)}t.restore()}function Xl(e){const{ctx:t,ballX:n,ballY:r,ballRadius:a,playerColor:s,ballIsGold:i,currentTime:l}=e,c=20+Math.abs(Math.sin(l*3))*15,d=l*5%(Math.PI*2),u=-Math.abs(Math.sin(d))*c,p=r+u;t.save(),t.globalAlpha=.3,t.fillStyle="rgba(0,0,0,0.5)";const m=1-Math.abs(u)/(c+20);t.beginPath(),t.ellipse(n,r+a*.5,a*m*1.5,a*.3*m,0,0,Math.PI*2),t.fill(),t.restore(),t.save();const f=5;for(let v=0;v<f;v++){const S=(v+1)*.04,b=(l-S)*5%(Math.PI*2),x=r+-Math.abs(Math.sin(b))*c,w=.15*(1-v/f),k=a*(.6-v*.08);t.globalAlpha=w,t.fillStyle=s,t.beginPath(),t.arc(n-v*3,x,Math.max(2,k),0,Math.PI*2),t.fill()}t.restore(),t.save();const y=1+Math.abs(Math.sin(d))*.15,g=1/y;if(t.translate(n,p),t.scale(g,y),t.shadowColor=i?"#FFD700":s,t.shadowBlur=12,t.fillStyle=i?"#FFF0A8":s,t.beginPath(),t.arc(0,0,a,0,Math.PI*2),t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0,0,0,0.35)",t.stroke(),t.restore(),Math.abs(Math.sin(d))<.1){t.save(),t.globalAlpha=.6,t.fillStyle=i?"#FFD700":s;for(let v=0;v<4;v++){const S=v/4*Math.PI*2+l,b=n+Math.cos(S)*(a+4),x=r+Math.sin(S)*2;t.beginPath(),t.arc(b,x,2,0,Math.PI*2),t.fill()}t.restore()}}function Jl(e,t){switch(e){case"wipe":return Yl(t),!0;case"pulse":return Zl(t),!0;case"bounce":return Xl(t),!0;case"ball":default:return!1}}const Ql=3,P=Ql;function yt(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} ${P}V${e-P}A${t-P} ${t-P} 0 0 1 ${P} ${t}A${t-P} ${t-P} 0 0 1 ${t} ${P}Z`}}function Ot(e){return{w:P+1,out:`M0 0H${P+1}V${e}H0Z`,inn:`M${P} ${P}H${P+1}V${e-P}H${P}Z`}}function Er(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-P,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${P+r} ${P}H${n}V${e-P}H${P+r}Q${P} ${e-P} ${P} ${e-P-r}V${P+r}Q${P} ${P} ${P+r} ${P}Z`}}function In(e){const t=e*.3|0,n=t+2,r=Math.max(t-P,1);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e-t}V${t}Z`,inn:`M${P+r} ${P}H${n}V${e-P}H${P+r}L${P} ${e-P-r}V${P+r}Z`}}function ft(e){const t=e*.42|0,n=t+2,r=Math.max(t-(P*1.4|0),2);return{w:n,out:`M${t} 0H${n}V${e}H${t}L0 ${e/2}Z`,inn:`M${P+r} ${P}H${n}V${e-P}H${P+r}L${P} ${e/2}Z`}}function Fn(e){const t=e*.3|0,n=t+4,r=Math.max(t-P,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${P+r} ${P}H${n}V${e-P}H${P+(r*.6|0)}L${P} ${e-P-r}V${P+r}Q${P} ${P} ${P+r} ${P}Z`}}function Ar(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${P+(t*1.2|0)} ${P}H${n}V${e-P}H${P+(t*1.2|0)}C${P+(t*2.2|0)} ${e*.37|0} ${P+(t*2.2|0)} ${e*.63|0} ${P+(t*1.2|0)} ${e-P}Z`}}function Lr(e){const t=e*.32|0,n=t+3,r=Math.max(t-P,1);return{w:n,out:`M0 0H${n}V${e}H${t}Q0 ${e} 0 ${e-t}Z`,inn:`M${P} ${P}H${n}V${e-P}H${P+r}Q${P} ${e-P} ${P} ${e-P-r}Z`}}function On(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${P+(t*1.8|0)} ${P}H${n}V${e-P}H${P+(t*1.8|0)}C${P+(t*.4|0)} ${e*.78|0} ${P+(t*2.8|0)} ${e*.55|0} ${P+(t*.4|0)} ${e*.37|0}S${P+(t*.9|0)} ${P} ${P+(t*1.8|0)} ${P}Z`}}function Nr(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${P+(t*2.5|0)} ${P}H${n}V${e-P}H${P+(t*2.5|0)}L${P+(t*.7|0)} ${e-P-(t*1.6|0)}L${P+(t*1.7|0)} ${e*.64|0}L${P} ${e/2|0}L${P+(t*1.7|0)} ${e*.36|0}L${P+(t*.7|0)} ${P+(t*1.6|0)}Z`}}function Rn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M${t} 0H${n}V${e}H0Z`,inn:`M${P+t-(P*1.3|0)} ${P}H${n}V${e-P}H${P+1}Z`}}function fr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}V${e}H${t}Z`,inn:`M${P} ${P}H${n}V${e-P}H${P+t-(P*1.3|0)+1}Z`}}function ut(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 ${P}A${t-P} ${t-P} 0 0 1 ${t-P} ${t}A${t-P} ${t-P} 0 0 1 0 ${e-P}Z`}}function Dt(e){return{w:P+1,out:`M0 0H${P+1}V${e}H0Z`,inn:`M0 ${P}H1V${e-P}H0Z`}}function cs(e){const t=Math.min(14,e*.22)|0,n=t+2,r=Math.max(t-P,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 ${P}H${n-P-r}Q${n-P} ${P} ${n-P} ${P+r}V${e-P-r}Q${n-P} ${e-P} ${n-P-r} ${e-P}H0Z`}}function Gt(e){const t=e*.3|0,n=t+2,r=Math.max(t-P,1);return{w:n,out:`M0 0H${n-t}L${n} ${t}V${e-t}L${n-t} ${e}H0Z`,inn:`M0 ${P}H${n-P-r}L${n-P} ${P+r}V${e-P-r}L${n-P-r} ${e-P}H0Z`}}function at(e){const t=e*.42|0,n=t+2,r=Math.max(t-(P*1.4|0),2);return{w:n,out:`M0 0H${n-t}L${n} ${e/2}L${n-t} ${e}H0Z`,inn:`M0 ${P}H${n-P-r}L${n-P} ${e/2}L${n-P-r} ${e-P}H0Z`}}function ds(e){const t=e*.3|0,n=t+4,r=Math.max(t-P,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 ${P}H${n-P-r}Q${n-P} ${P} ${n-P} ${P+r}V${e-P-r}L${n-P-(r*.6|0)} ${e-P}H0Z`}}function us(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 ${P}H${n-P-(t*1.2|0)}C${n-P-(t*2.2|0)} ${e*.37|0} ${n-P-(t*2.2|0)} ${e*.63|0} ${n-P-(t*1.2|0)} ${e-P}H0Z`}}function hs(e){const t=e*.32|0,n=t+3,r=Math.max(t-P,1);return{w:n,out:`M0 0H${n}V${e-t}Q${n} ${e} ${n-t} ${e}H0Z`,inn:`M0 ${P}H${n-P}V${e-P-r}Q${n-P} ${e-P} ${n-P-r} ${e-P}H0Z`}}function Ir(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 ${P}H${n-P-(t*1.8|0)}C${n-P-(t*.9|0)} ${P} ${n-P+(t*.1|0)} ${e*.22|0} ${n-P-(t*.4|0)} ${e*.37|0}S${n-P-(t*.4|0)} ${e*.78|0} ${n-P-(t*1.8|0)} ${e-P}H0Z`}}function Dn(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 ${P}H${n-P-(t*2.5|0)}L${n-P-(t*.7|0)} ${P+(t*1.6|0)}L${n-P-(t*1.7|0)} ${e*.36|0}L${n-P} ${e/2|0}L${n-P-(t*1.7|0)} ${e*.64|0}L${n-P-(t*.7|0)} ${e-P-(t*1.6|0)}L${n-P-(t*2.5|0)} ${e-P}H0Z`}}function pr(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n}L${n-t} ${e}H0Z`,inn:`M0 ${P}H${n-P}L${n-P-t+(P*1.3|0)} ${e-P}H0Z`}}function jn(e){const t=e*.42|0,n=t+2;return{w:n,out:`M0 0H${n-t}L${n} ${e}H0Z`,inn:`M0 ${P}H${n-P-t+(P*1.3|0)}L${n-P} ${e-P}H0Z`}}const Fr=[{name:"Pill",L:yt,R:ut},{name:"Sharp",L:Ot,R:Dt},{name:"Soft",L:Er,R:cs},{name:"Chamfer",L:In,R:Gt},{name:"Arrow",L:ft,R:at},{name:"Shield",L:Fn,R:ds},{name:"Bracket",L:Ar,R:us},{name:"Tab",L:Lr,R:hs},{name:"Wave",L:On,R:Ir},{name:"Ornate",L:Nr,R:Dn}],fs=[{name:"Pill→Arrow",L:yt,R:at},{name:"Arrow→Pill",L:ft,R:ut},{name:"Pill→Sharp",L:yt,R:Dt},{name:"Sharp→Pill",L:Ot,R:ut},{name:"Pill→Chamfer",L:yt,R:Gt},{name:"Chamfer→Pill",L:In,R:ut},{name:"Arrow→Sharp",L:ft,R:Dt},{name:"Sharp→Arrow",L:Ot,R:at},{name:"Arrow→Chamfer",L:ft,R:Gt},{name:"Chamfer→Arrow",L:In,R:at},{name:"Soft→Arrow",L:Er,R:at},{name:"Shield→Chamfer",L:Fn,R:Gt},{name:"Pill→Wave",L:yt,R:Ir},{name:"Wave→Arrow",L:On,R:at},{name:"Tab→Pill",L:Lr,R:ut},{name:"Ornate→Sharp",L:Nr,R:Dt},{name:"Sharp→Ornate",L:Ot,R:Dn},{name:"Bracket→Arrow",L:Ar,R:at},{name:"Shield→Pill",L:Fn,R:ut},{name:"Wave→Ornate",L:On,R:Dn}],ps=[{name:"Skew ╲",L:Rn,R:pr},{name:"Skew ╱",L:fr,R:jn},{name:"◇ Romb",L:ft,R:at},{name:"╲→Pill",L:Rn,R:ut},{name:"Pill→╲",L:yt,R:pr},{name:"╱→Sharp",L:fr,R:Dt},{name:"Sharp→╱",L:Ot,R:jn},{name:"╲→Arrow",L:Rn,R:at},{name:"Arrow→╱",L:ft,R:jn},{name:"◇→Chamfer",L:ft,R:Gt}],fn=[...Fr,...fs,...ps],ms=Fr[0];function en(e){return fn.find(t=>t.name===e)||ms}const Gn=[{name:"Flames",mk:(e,t,n)=>{const r=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="${r}" opacity=".3"/><path d="M9 6C10 8 11 10 9 14C7 10 8 8 9 6Z" fill="${r}" 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 r=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="${r}" stroke-width=".8" opacity=".3"/><ellipse cx="12" cy="4" rx="6" ry="4.5" fill="none" stroke="${r}" 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 r=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="${r}" opacity=".3"/><circle cx="8" cy="8" r="1" fill="${r}" 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 r=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="${r}" stroke-width=".6" opacity=".3"/><path d="M5 5L7 6M5 8L7 7.5" stroke="${r}" 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 r=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="${r}" stroke-width=".8" opacity=".35"/><circle cx="11" cy="3" r="1.8" fill="${r}" 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 tn(e){return Gn.find(t=>t.name===e)||null}const xt={color:null,capStyleName:"Pill",patternName:null,patternColor:null,patternOnly:!1,highlight:70,glow:55,glass:0,textureUrl:null,textureScale:1},Un={...xt,glass:85},qn={...xt,patternName:"Stars"},Vn={...xt,patternName:"Stars"},Kn={fontFamily:null,fontSize:18,fontColor:null,outlineColor:null,outlineWidth:0,shadow:null},gs={filledBar:{...xt},emptyBar:{...Un},goldFilledBar:{...Vn},goldEmptyBar:{...qn},font:{...Kn},disableGoldNotes:!1},_t={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},ca="nice2dev-player-bar-style",da="nice2dev-player-karaoke-settings";function Bt(e){return e!=null?`${da}-${e}`:da}function pn(e){return e!=null?`${ca}-${e}`:ca}function ua(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 ha(e){const t=gs,n=(a,s)=>!s||typeof s!="object"?{...a}:{...a,...s},r=(a,s)=>!s||typeof s!="object"?{...a}:{...a,...s};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:r(t.font,e.font),disableGoldNotes:typeof e.disableGoldNotes=="boolean"?e.disableGoldNotes:t.disableGoldNotes}}function ys(e){try{const t=localStorage.getItem(Bt(e));if(t){const r=JSON.parse(t);return ha(r)}const n=localStorage.getItem(pn(e));if(n){const r=JSON.parse(n),a=ua({..._t,...r});return localStorage.setItem(Bt(e),JSON.stringify(a)),a}if(e!=null){const r=localStorage.getItem(Bt());if(r)return ha(JSON.parse(r));const a=localStorage.getItem(pn());if(a)return ua({..._t,...JSON.parse(a)})}}catch{}return{filledBar:{...xt},emptyBar:{...Un},goldFilledBar:{...Vn},goldEmptyBar:{...qn},font:{...Kn}}}function ec(e,t){const n=JSON.stringify(e);localStorage.setItem(Bt(t),n)}let fa=!1;async function tc(e){if(fa||(fa=!0,!e))return;const t=await e();if(t)try{localStorage.getItem(Bt())||localStorage.setItem(Bt(),t)}catch{}}function nc(e){const t=new Map;for(const n of e)t.set(n,ys(n));return t}function bs(e){try{const t=localStorage.getItem(pn(e));if(t)return{..._t,...JSON.parse(t)};if(e!=null){const n=localStorage.getItem(pn());if(n)return{..._t,...JSON.parse(n)}}}catch{}return{..._t}}function rc(e,t){localStorage.setItem(pn(t),JSON.stringify(e))}function ac(e){const t=new Map;for(const n of e)t.set(n,bs(n));return t}const sc=3,Ne=sc;function _n(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,r=parseInt(e.slice(5,7),16)/255,a=Math.max(t,n,r),s=Math.min(t,n,r);let i=0,l=0;const c=(a+s)/2;if(a!==s){const d=a-s;switch(l=c>.5?d/(2-a-s):d/(a+s),a){case t:i=((n-r)/d+(n<r?6:0))/6;break;case n:i=((r-t)/d+2)/6;break;case r:i=((t-n)/d+4)/6;break}}return[Math.round(i*360),Math.round(l*100),Math.round(c*100)]}function Bn(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 Ke(e,t){return e.replace(/([MLHVCSQTAZ])/gi,`
14
+ $1`).split(`
15
+ `).filter(Boolean).map(n=>{const r=n[0],a=n.slice(1).trim().split(/[\s,]+/).map(Number);if(r==="H")return`H${a[0]+t}`;if(r==="V"||r==="Z")return n;if("MLCSQT".includes(r.toUpperCase())){for(let s=0;s<a.length;s+=2)a[s]+=t;return r+a.join(" ")}return r==="A"&&a.length>=7?(a[5]+=t,r+a.join(" ")):n}).join("")}function vs(e){const{width:t,height:n,capStyle:r,color:a,highlight:s=70,glow:i=55,glass:l=0,pattern:c=null,patternColor:d=null,patternOnly:u=!1,textureUrl:p=null,textureScale:m=1}=e,[f,y,g]=_n(Bn(a)),v="c"+Math.random().toString(36).slice(2,7),S=r.L(n),b=r.R(n),x=t-S.w-b.w;if(x<4)return"";if(u&&c){const H=`hsl(${f},${y}%,${g}%)`,ae=`hsl(${f},${Math.max(y-20,0)}%,${Math.min(g+30,95)}%)`,le=d||ae,ne=S.w,X=S.w+x,K=S.inn,J=`M${ne} ${Ne}H${X}V${n-Ne}H${ne}Z`,oe=Ke(b.inn,X),ie=S.out,ue=`M${ne} 0H${X}V${n}H${ne}Z`,U=Ke(b.out,X),fe=c.mk(v+"pat",le,d||void 0),me=Math.round(256*m),xe=Math.round(256*m),De=p?`<pattern id="${v}tex" patternUnits="userSpaceOnUse" width="${me}" height="${xe}"><image href="${p}" width="${me}" height="${xe}" preserveAspectRatio="none"/></pattern>`:"",Te=p?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}tex)" opacity=".85" clip-path="url(#${v}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
16
+ ${fe}
17
+ ${De}
18
+ <clipPath id="${v}c"><path d="${K}"/><path d="${J}"/><path d="${oe}"/></clipPath>
19
+ </defs>
20
+ <path d="${ie}" fill="rgba(255,255,255,.18)"/><path d="${ue}" fill="rgba(255,255,255,.18)"/><path d="${U}" fill="rgba(255,255,255,.18)"/>
21
+ <path d="${K}" fill="${H}" opacity=".22"/><path d="${J}" fill="${H}" opacity=".22"/><path d="${oe}" fill="${H}" opacity=".22"/>
22
+ ${Te}
23
+ <rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}pat)" clip-path="url(#${v}c)"/>
24
+ </svg>`}const w=`hsl(${f},${Math.min(y+10,100)}%,${Math.max(g-22,4)}%)`,k=`hsl(${f},${y}%,${g}%)`,j=`hsl(${f},${Math.max(y-12,0)}%,${Math.min(g+18,88)}%)`,T=`hsl(${f},${Math.min(y+20,100)}%,${Math.min(g+30,93)}%)`,D=`hsl(${f},${Math.max(y-20,0)}%,${Math.min(g+30,95)}%)`,C=d||D,L=s/100*.78,G=i/100*.65,q=1-l/100*.87,A=Ne,V=n-Ne,te=A+(V-A)*.44,ee=A+(V-A)*.58,W=S.w,Q=S.w+x,E=S.out,F=`M${W} 0H${Q}V${n}H${W}Z`,N=Ke(b.out,Q),$=S.inn,M=`M${W} ${Ne}H${Q}V${n-Ne}H${W}Z`,O=Ke(b.inn,Q),R=c?c.mk(v+"pat",C,d||void 0):"",_=c?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}pat)" clip-path="url(#${v}c)"/>`:"",I=Math.round(256*m),B=Math.round(256*m),Z=p?`<pattern id="${v}tex" patternUnits="userSpaceOnUse" width="${I}" height="${B}"><image href="${p}" width="${I}" height="${B}" preserveAspectRatio="none"/></pattern>`:"",z=p?`<rect x="0" y="0" width="${t}" height="${n}" fill="url(#${v}tex)" opacity="${q*.9}" clip-path="url(#${v}c)"/>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}"><defs>
25
+ ${R}
26
+ ${Z}
27
+ <linearGradient id="${v}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>
28
+ <linearGradient id="${v}f" x1="0" y1="${A}" x2="0" y2="${V}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${j}"/><stop offset=".5" stop-color="${k}"/><stop offset="1" stop-color="${w}"/></linearGradient>
29
+ <linearGradient id="${v}h" x1="0" y1="${A}" x2="0" y2="${te}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity="${L}"/><stop offset=".5" stop-color="#fff" stop-opacity="${L*.25}"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>
30
+ <linearGradient id="${v}g" x1="0" y1="${ee}" x2="0" y2="${V}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="${T}" stop-opacity="0"/><stop offset=".6" stop-color="${T}" stop-opacity="${G*.6}"/><stop offset="1" stop-color="${T}" stop-opacity="${G}"/></linearGradient>
31
+ <clipPath id="${v}c"><path d="${$}"/><path d="${M}"/><path d="${O}"/></clipPath>
32
+ </defs>
33
+ <path d="${E}" fill="url(#${v}b)"/><path d="${F}" fill="url(#${v}b)"/><path d="${N}" fill="url(#${v}b)"/>
34
+ <path d="${$}" fill="url(#${v}f)" opacity="${q}"/><path d="${M}" fill="url(#${v}f)" opacity="${q}"/><path d="${O}" fill="url(#${v}f)" opacity="${q}"/>
35
+ ${z}
36
+ ${_}
37
+ <rect x="0" y="${ee}" width="${t}" height="${V-ee}" fill="url(#${v}g)" clip-path="url(#${v}c)"/>
38
+ <rect x="0" y="${A}" width="${t}" height="${te-A}" fill="url(#${v}h)" clip-path="url(#${v}c)"/>
39
+ </svg>`}function Oe(e,t){const n=t.match(/[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*/g);if(!n)return;let r=0,a=0;for(const s of n){const i=s[0],l=s.slice(1).trim().split(/[\s,]+/).filter(Boolean).map(Number);switch(i){case"M":r=l[0],a=l[1],e.moveTo(r,a);break;case"L":r=l[0],a=l[1],e.lineTo(r,a);break;case"H":r=l[0],e.lineTo(r,a);break;case"V":a=l[0],e.lineTo(r,a);break;case"C":e.bezierCurveTo(l[0],l[1],l[2],l[3],l[4],l[5]),r=l[4],a=l[5];break;case"Q":e.quadraticCurveTo(l[0],l[1],l[2],l[3]),r=l[2],a=l[3];break;case"S":{e.bezierCurveTo(r,a,l[0],l[1],l[2],l[3]),r=l[2],a=l[3];break}case"A":{const c=Math.abs(l[0]),d=Math.abs(l[1]),u=l[3]!==0,p=l[4]!==0,m=l[5],f=l[6],y=r,g=a;if(Math.abs(y-m)<.001&&Math.abs(g-f)<.001||c<.001||d<.001){e.lineTo(m,f),r=m,a=f;break}const v=(c+d)/2,S=(y-m)/2,b=(g-f)/2,x=S*S+b*b,w=x>v*v?Math.sqrt(x):v,k=w*w,j=Math.sqrt(Math.max(0,(k-x)/x)),T=u!==p?1:-1,D=(y+m)/2+T*j*b,C=(g+f)/2-T*j*S,L=Math.atan2(g-C,y-D),G=Math.atan2(f-C,m-D);e.arc(D,C,w,L,G,!p),r=m,a=f;break}case"Z":e.closePath();break}}}function nn(e,t,n,r,a,s,i,l=70,c=55,d=0,u,p,m=!1,f,y){const[g,v,S]=_n(Bn(i)),b=s.L(a),x=s.R(a),w=r-b.w-x.w;if(w<0){const[M,,O]=_n(Bn(i));e.save(),e.translate(t,n),e.globalAlpha=1-d/100*.87,e.fillStyle=`hsl(${M},50%,${Math.min(O+10,80)}%)`;const R=Math.min(r/2,a/2);e.beginPath(),e.moveTo(R,0),e.lineTo(r-R,0),e.quadraticCurveTo(r,0,r,R),e.lineTo(r,a-R),e.quadraticCurveTo(r,a,r-R,a),e.lineTo(R,a),e.quadraticCurveTo(0,a,0,a-R),e.lineTo(0,R),e.quadraticCurveTo(0,0,R,0),e.closePath(),e.fill(),e.restore();return}const k=b.w,j=b.w+w;if(m){const M=`hsla(${g},${v}%,${S}%,0.22)`;e.save(),e.translate(t,n),e.fillStyle="rgba(255,255,255,0.18)",e.beginPath(),Oe(e,b.out),e.fill(),e.fillRect(k,0,w,a),e.beginPath(),Oe(e,Ke(x.out,j)),e.fill(),e.fillStyle=M,e.beginPath(),Oe(e,b.inn),e.fill(),e.fillRect(k,Ne,w,a-2*Ne),e.beginPath(),Oe(e,Ke(x.inn,j)),e.fill(),f&&(e.save(),e.beginPath(),Oe(e,b.inn),e.rect(k,Ne,w,a-2*Ne),Oe(e,Ke(x.inn,j)),e.clip(),e.globalAlpha=.85,e.fillStyle=f,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),y&&(e.save(),e.beginPath(),Oe(e,b.inn),e.rect(k,Ne,w,a-2*Ne),Oe(e,Ke(x.inn,j)),e.clip(),e.globalAlpha=.85,e.fillStyle=y,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.restore();return}const T=`hsl(${g},${Math.min(v+10,100)}%,${Math.max(S-22,4)}%)`,D=`hsl(${g},${v}%,${S}%)`,C=`hsl(${g},${Math.max(v-12,0)}%,${Math.min(S+18,88)}%)`,L=`hsl(${g},${Math.min(v+20,100)}%,${Math.min(S+30,93)}%)`,G=l/100*.78,q=c/100*.65,A=1-d/100*.87,V=Ne,te=a-Ne,ee=te-V,W=V+ee*.44,Q=V+ee*.58;e.save(),e.translate(t,n);const E=e.createLinearGradient(0,0,0,a);E.addColorStop(0,"rgba(255,255,255,0.55)"),E.addColorStop(.3,"rgba(255,255,255,0.35)"),E.addColorStop(1,"rgba(255,255,255,0.08)"),e.fillStyle=E,e.beginPath(),Oe(e,b.out),e.fill(),e.fillRect(k,0,w,a),e.beginPath(),Oe(e,Ke(x.out,j)),e.fill();const F=e.createLinearGradient(0,V,0,te);F.addColorStop(0,C),F.addColorStop(.5,D),F.addColorStop(1,T),e.globalAlpha=A,e.fillStyle=F,e.beginPath(),Oe(e,b.inn),e.fill(),e.fillRect(k,Ne,w,a-2*Ne),e.beginPath(),Oe(e,Ke(x.inn,j)),e.fill(),e.globalAlpha=1,f&&(e.save(),e.beginPath(),Oe(e,b.inn),e.rect(k,Ne,w,a-2*Ne),Oe(e,Ke(x.inn,j)),e.clip(),e.globalAlpha=A*.9,e.fillStyle=f,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),y&&(e.save(),e.beginPath(),Oe(e,b.inn),e.rect(k,Ne,w,a-2*Ne),Oe(e,Ke(x.inn,j)),e.clip(),e.globalAlpha=A*.85,e.fillStyle=y,e.fillRect(0,0,r,a),e.globalAlpha=1,e.restore()),e.save(),e.beginPath(),Oe(e,b.inn),e.rect(k,Ne,w,a-2*Ne),Oe(e,Ke(x.inn,j)),e.clip();const N=e.createLinearGradient(0,Q,0,te);N.addColorStop(0,"transparent"),N.addColorStop(.6,L.replace(")",`, ${q*.6})`).replace("hsl","hsla")),N.addColorStop(1,L.replace(")",`, ${q})`).replace("hsl","hsla")),e.fillStyle=N,e.fillRect(0,Q,r,te-Q);const $=e.createLinearGradient(0,V,0,W);$.addColorStop(0,`rgba(255,255,255,${G})`),$.addColorStop(.5,`rgba(255,255,255,${G*.25})`),$.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=$,e.fillRect(0,V,r,W-V),e.restore(),e.restore()}const Nt=new Map,rn=new Set,Tn=new Set;function Or(e){const t=Nt.get(e);return t?Promise.resolve(t):Tn.has(e)?Promise.reject(new Error(`Texture failed: ${e}`)):rn.has(e)?new Promise((n,r)=>{const a=()=>{Nt.has(e)?n(Nt.get(e)):Tn.has(e)?r(new Error(`Texture failed: ${e}`)):requestAnimationFrame(a)};a()}):(rn.add(e),new Promise((n,r)=>{const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{Nt.set(e,a),rn.delete(e),n(a)},a.onerror=()=>{rn.delete(e),Tn.add(e),r(new Error(`Failed to load texture: ${e}`))},a.src=e}))}function oc(e){return Nt.get(e)??null}function an(e,t,n=1){const r=Nt.get(t);if(!r)return!rn.has(t)&&!Tn.has(t)&&Or(t).catch(()=>{}),null;const a=e.createPattern(r,"repeat");if(!a)return null;if(n!==1){const s=new DOMMatrix;s.scaleSelf(n,n),a.setTransform(s)}return a}function ic(e){for(const t of e)t&&Or(t).catch(()=>{})}const sn=new Map,Et=new Set;function xs(e,t,n){return`${e}|${t}|${n??""}`}function lc(e,t,n){const r=xs(e.name,t,n),a=sn.get(r);if(a)return Promise.resolve(a);if(Et.has(r))return new Promise((y,g)=>{const v=()=>{sn.has(r)?y(sn.get(r)):Et.has(r)?requestAnimationFrame(v):g(new Error(`Pattern render failed: ${r}`))};v()});Et.add(r);const s="p",i=e.mk(s,t,n??void 0),l=i.match(/width="(\d+)"/),c=i.match(/height="(\d+)"/),d=l?parseInt(l[1],10):16,u=c?parseInt(c[1],10):16,p=`<svg xmlns="http://www.w3.org/2000/svg" width="${d}" height="${u}"><defs>${i}</defs><rect width="${d}" height="${u}" fill="url(#${s})"/></svg>`,m=new Blob([p],{type:"image/svg+xml;charset=utf-8"}),f=URL.createObjectURL(m);return new Promise((y,g)=>{const v=new Image;v.onload=()=>{sn.set(r,v),Et.delete(r),URL.revokeObjectURL(f),y(v)},v.onerror=()=>{Et.delete(r),URL.revokeObjectURL(f),g(new Error(`Failed to render pattern tile: ${e.name}`))},v.src=f})}function on(e,t,n,r){const a=xs(t.name,n,r),s=sn.get(a);return s?e.createPattern(s,"repeat"):(Et.has(a)||lc(t,n,r).catch(()=>{}),null)}const cc="karaokeScoringConfig",Dr={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}},dc="karaoke.scoringPresets";function uc(){try{const e=localStorage.getItem(dc);return e?JSON.parse(e):null}catch(e){return console.warn(cc,"Failed to parse scoring presets overrides",e),null}}function Ss(e){const t={...Dr},n=uc();return n&&Object.keys(n).forEach(r=>{const a=n[r];a&&(t[r]={...t[r],...a})}),e&&Object.keys(e).forEach(r=>{const a=e[r];a&&(t[r]={...t[r],...a})}),t}exports.ScoringPresets=Ss();const hc=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=Ss(t.presets),exports.ScoringPresets}catch{}return exports.ScoringPresets},ws=(e="normal")=>exports.ScoringPresets[e]||Dr.normal,nr={},fc=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:lt&&lt.tagName.toUpperCase()==="SCRIPT"&&lt.src||new URL("index.cjs",document.baseURI).href}<"u"&&(nr==null?void 0:nr.VITE_DEBUG_KARAOKE)==="true";function mr(e,t,...n){(fc||typeof window<"u"&&window.DEBUG_KARAOKE)&&console.log(`%c[KARAOKE-DEBUG]%c [${e}] ${t}`,"background:#6c3483;color:#fff;padding:1px 4px;border-radius:3px;font-weight:bold","color:#6c3483;font-weight:bold",...n)}let tt=null,_e=null,Ye=null,ct=null,Je=null,$e=null,pa="",ma=0,ga="";const gr=(e,t,n,r,a,s,i,l,c,d,u,p,m,f,y,g,v,S,b,x,w,k,j,T)=>{e.clearRect(0,0,t,n);const D=T??null,C=(D==null?void 0:D.filledBar)??xt,L=(D==null?void 0:D.emptyBar)??Un,G=(D==null?void 0:D.goldFilledBar)??Vn,q=(D==null?void 0:D.goldEmptyBar)??qn,A=(D==null?void 0:D.font)??Kn,V=en(C.capStyleName),te=en(L.capStyleName),ee=en(G.capStyleName),W=en(q.capStyleName),Q=C.patternName?tn(C.patternName):null,E=L.patternName?tn(L.patternName):null,F=G.patternName?tn(G.patternName):null,N=q.patternName?tn(q.patternName):null,$=Q?on(e,Q,C.patternColor??C.color??"#ffffff",C.patternColor):null,M=E?on(e,E,L.patternColor??L.color??"#d1d5db",L.patternColor):null,O=F?on(e,F,G.patternColor??"#FFD700",G.patternColor):null,R=N?on(e,N,q.patternColor??"#FFD700",q.patternColor):null;ga!==s&&(ga=s,mr("RENDER",`?? Renderer using settings for "${s}" � filled: cap=${C.capStyleName}, glass=${C.glass} | empty: cap=${L.capStyleName}, glass=${L.glass} | goldFilled: cap=${G.capStyleName}, pattern=${G.patternName??"none"} | goldEmpty: cap=${q.capStyleName}, pattern=${q.patternName??"none"} | hasSettings=${!!D}`,{filledBar:C,emptyBar:L,goldFilledBar:G,goldEmptyBar:q,filledOverlay:!!$,emptyOverlay:!!M,goldFilledOverlay:!!O,goldEmptyOverlay:!!R}));const _=C.textureUrl?an(e,C.textureUrl,C.textureScale):null,I=L.textureUrl?an(e,L.textureUrl,L.textureScale):null,B=G.textureUrl?an(e,G.textureUrl,G.textureScale):null,Z=q.textureUrl?an(e,q.textureUrl,q.textureScale):null,z=typeof document<"u"?hr(l||"var(--accent-primary, #ffcc00)"):l||"var(--accent-primary, #ffcc00)",H=yn(z||"#ffcc00"),ae=se=>hr(se),le=A.fontFamily||"Arial",ne=A.fontSize||18,X=ae(A.fontColor||"var(--btn-text, #fff)"),K=A.outlineColor?ae(A.outlineColor):null,J=typeof A.outlineWidth=="number"?A.outlineWidth:0,oe=A.shadow||null;typeof document<"u"&&((!tt||tt.width!==t||tt.height!==n)&&(tt=document.createElement("canvas"),tt.width=t,tt.height=n,_e=tt.getContext("2d")),_e&&_e.clearRect(0,0,t,n),(!Ye||Ye.width!==t||Ye.height!==n)&&(Ye=document.createElement("canvas"),Ye.width=t,Ye.height=n,ct=Ye.getContext("2d")),ct&&ct.clearRect(0,0,t,n),(!Je||Je.width!==t||Je.height!==n)&&(Je=document.createElement("canvas"),Je.width=t,Je.height=n,$e=Je.getContext("2d")),$e&&$e.clearRect(0,0,t,n));const ie=b?-b:0,ue=x||t;e.fillStyle=z,e.font=`bold ${ne}px ${le}`;const fe=e.measureText(s).width+20;if(e.fillRect(ie+10,5,fe,25),e.save(),e.fillStyle=X,oe){const se=oe.match(/(-?\d+)px\s+(-?\d+)px\s+(\d+)px\s+(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|[a-zA-Z]+)/);se&&(e.shadowOffsetX=parseInt(se[1],10),e.shadowOffsetY=parseInt(se[2],10),e.shadowBlur=parseInt(se[3],10),e.shadowColor=se[4])}if(e.fillText(s,ie+20,22),K&&J>0&&(e.lineWidth=J,e.strokeStyle=K,e.strokeText(s,ie+20,22)),e.restore(),v){const se=ae(S||"var(--text-secondary, #6b7280)");e.font=`bold 12px ${le}`;const ce=e.measureText(v).width,Ee=8,ye=ie+10+fe+6,pe=20,he=7,be=ce+Ee*2,Se=4;e.beginPath(),e.moveTo(ye+Se,he),e.lineTo(ye+be-Se,he),e.quadraticCurveTo(ye+be,he,ye+be,he+Se),e.lineTo(ye+be,he+pe-Se),e.quadraticCurveTo(ye+be,he+pe,ye+be-Se,he+pe),e.lineTo(ye+Se,he+pe),e.quadraticCurveTo(ye,he+pe,ye,he+pe-Se),e.lineTo(ye,he+Se),e.quadraticCurveTo(ye,he,ye+Se,he),e.closePath(),e.fillStyle=se,e.fill(),e.fillStyle=X,e.fillText(v,ye+Ee,he+14),e.font=`bold ${ne}px ${le}`}const me=120;if(e.fillStyle=z,e.fillRect(ie+ue-me-10,5,me,25),e.fillStyle=X,e.fillText(`${i} pts`,ie+ue-me+15,22),w&&w.currentCombo>=5){const se=w.currentCombo>=50?"3x":w.currentCombo>=30?"2.5x":w.currentCombo>=20?"2x":w.currentCombo>=10?"1.5x":"",ce=`${w.currentCombo} combo${se?" "+se:""}`;e.font=`bold 12px ${le}`;const ye=e.measureText(ce).width+16,pe=ie+ue-me-10-ye-6;e.fillStyle=ae(w.currentCombo>=20?"var(--success, #FFD700)":"var(--warning, #ff9800)"),e.globalAlpha=.9,Hl(e,pe,7,ye,21,4),e.fill(),e.globalAlpha=1,e.fillStyle=ae(w.currentCombo>=20?"var(--text-primary, #000)":"var(--btn-text, #fff)"),e.fillText(ce,pe+8,22),e.font=`bold 14px ${le}`}if(k&&k.length>0){const se=k[k.length-1];if(se.label){const ce=`${k.length}-${se.label}`;ce!==pa&&(pa=ce,ma=Date.now());const Ee=Date.now()-ma;if(Ee<2500){const ye=Ee<2e3?1:1-(Ee-2e3)/500,pe={Perfect:ae("var(--success, #00e676)"),Great:ae("var(--success, #66bb6a)"),Good:ae("var(--accent-primary, #ffeb3b)"),OK:ae("var(--warning, #ff9800)"),Bad:ae("var(--error, #ef5350)"),Awful:ae("var(--error, #b71c1c)")};e.save(),e.globalAlpha=ye,e.font=`bold ${Math.round(ne*1.2)}px ${le}`;const he=se.label,be=e.measureText(he).width,Se=ie+ue/2-be/2;e.fillStyle=pe[he]||X,e.shadowColor="rgba(0,0,0,0.5)",e.shadowBlur=6,e.fillText(he,Se,58),K&&J>0&&(e.lineWidth=J,e.strokeStyle=K,e.strokeText(he,Se,58)),e.restore()}}}const xe=a-2,De=a+5,Te=40;let Me=1/0,Y=-1/0;if(r.forEach(se=>{se.forEach(ce=>{ce.pitch<Me&&(Me=ce.pitch),ce.pitch>Y&&(Y=ce.pitch)})}),c&&Array.isArray(c)&&c.length>0){let se=null;isFinite(Me)&&isFinite(Y)&&(se=Math.round((Me+Y)/2));let ce=1/0,Ee=-1/0;c.forEach(({t:ye,hz:pe})=>{if(!pe||pe<=0)return;let he=se;for(const Se of r)for(const Fe of Se)ye>=Fe.startTime&&ye<=Fe.startTime+Fe.duration&&(he=Fe.pitch);const be=ls(pe,he);be<ce&&(ce=be),be>Ee&&(Ee=be)}),ce!==1/0&&Ee!==-1/0&&(ce<Me&&(Me=Math.floor(ce-2)),Ee>Y&&(Y=Math.ceil(Ee+2)))}(!isFinite(Me)||!isFinite(Y))&&(Me=40,Y=80),Me===Y&&(Me=Math.max(0,Me-6),Y=Y+6);const re=se=>{const ce=n-Te-10;return Te+ce-(se-Me)/(Y-Me)*ce},Ie=ws(m||"normal"),pt=(n-Te-10)/Math.max(1,Y-Me),Pe=Math.max(10,Math.round(pt*(1+2*Ie.semitoneTolerance)*.3)),wt=Math.max(5,Math.round(Pe*.45));((se,ce,Ee,ye,pe,he)=>{se.lineWidth=1;for(let be=Math.ceil(pe);be<=Math.floor(he);be++){const Se=re(be);se.strokeStyle=ae(be%2===0?"var(--guide-line-strong, rgba(255, 255, 255, 0.12))":"var(--guide-line-weak, rgba(255, 255, 255, 0.06))"),se.beginPath(),se.moveTo(0,Math.round(Se)+.5),se.lineTo(ce,Math.round(Se)+.5),se.stroke()}})(e,t,n-Te,Te,Me,Y),ct&&ct.clearRect(0,0,t,n);const st=(a-xe)/(De-xe)*t;let Ve=n*.5,Hr=!1,Ct=!1;const Ko=(se,ce,Ee,ye,pe,he,be=0)=>{const Se=(ge,ve,we,je,Le,We)=>{const Re=Math.min(We,je/2,Le/2);ge.beginPath(),ge.moveTo(ve+Re,we),ge.lineTo(ve+je-Re,we),ge.quadraticCurveTo(ve+je,we,ve+je,we+Re),ge.lineTo(ve+je,we+Le-Re),ge.quadraticCurveTo(ve+je,we+Le,ve+je-Re,we+Le),ge.lineTo(ve+Re,we+Le),ge.quadraticCurveTo(ve,we+Le,ve,we+Le-Re),ge.lineTo(ve,we+Re),ge.quadraticCurveTo(ve,we,ve+Re,we),ge.closePath()},Fe=Math.max(2,Pe/2);ye.forEach(ge=>{if(ge.startTime+ge.duration<pe||ge.startTime>he)return;const ve=(ge.startTime-pe)/(he-pe)*ce,we=ge.duration/(he-pe)*ce,je=re(ge.pitch)-Pe/2,Le=[];if(Array.isArray(p)){const We=ge.startTime+ge.duration;p.forEach(Re=>{if(Re.pitch!==ge.pitch||Re.noteStart!=null&&Re.noteEnd!=null&&(Math.abs(Re.noteStart-ge.startTime)>.01||Math.abs(Re.noteEnd-We)>.01))return;const Xe=Math.max(Re.start,ge.startTime),ot=Math.min(Re.end,We);if(Xe>=ot)return;const gt=(Xe-pe)/(he-pe)*ce,kt=(ot-pe)/(he-pe)*ce;Le.push({x1:gt,x2:kt,frac:Re.frac})})}if(ge.isGold){se.save();const We=y&&y.shadowColor?y.shadowColor:ia,Re=y&&typeof y.glowBlur=="number"?y.glowBlur:oa;se.shadowColor=We,se.shadowBlur=Math.max(4,Re-12),se.fillStyle=ae("var(--gold-overlay, rgba(255, 215, 0, 0.15))"),Se(se,ve-1,je-1,we+2,Pe+2,Fe),se.fill(),se.restore();const Xe=yn("var(--gold-base, #b4af9f)");nn(se,ve,je,we,Pe,W,q.color??Xe,q.highlight,q.glow,q.glass,N,q.patternColor,q.patternOnly,Z,R),se.save(),Se(se,ve,je,we,Pe,Fe),se.clip(),se.globalAlpha=.18,se.fillStyle=ae("var(--success, #FFD700)"),se.fillRect(ve,je,we,Math.max(1,Pe*.25)),se.globalAlpha=1,se.restore(),Le.length>0&&(se.save(),Se(se,ve,je,we,Pe,Fe),se.clip(),Le.forEach(ot=>{const gt=Math.max(1,ot.x2-ot.x1);nn(se,ot.x1,je,gt,Pe,ee,G.color??"#FFD700",G.highlight,G.glow,G.glass,F,G.patternColor,G.patternOnly,B,O)}),se.restore()),Le.length===0&&(se.lineWidth=1,se.strokeStyle=ae("var(--gold-outline, rgba(255, 215, 0, 0.35))"),Se(se,ve+.5,je+.5,we-1,Math.max(1,Pe-1),Fe),se.stroke())}else{const We=yn("var(--note-base, #d1d5db)");nn(se,ve,je,we,Pe,te,L.color??We,L.highlight,L.glow,L.glass,E,L.patternColor,L.patternOnly,I,M),Le.length>0&&(se.save(),Se(se,ve,je,we,Pe,Fe),se.clip(),Le.forEach(Re=>{const Xe=Math.max(1,Re.x2-Re.x1);nn(se,Re.x1,je,Xe,Pe,V,C.color??H,C.highlight,C.glow,C.glass,Q,C.patternColor,C.patternOnly,_,$)}),se.restore())}ct&&(ct.fillStyle="#ffffff",ct.fillRect(ve,je,we,Pe))})};if(r.forEach(se=>{Ko(e,t,n-Te,se,xe,De,Te);for(const ce of se)if(a>=ce.startTime&&a<=ce.startTime+ce.duration){Ve=re(ce.pitch),Hr=!0,Ct=!!ce.isGold;break}}),!Hr){let se=null,ce=null;for(const Ee of r)for(const ye of Ee)ye.startTime>a&&(!se||ye.startTime<se.startTime)&&(se=ye),ye.startTime<=a&&(!ce||ye.startTime>ce.startTime)&&(ce=ye);se?(Ve=re(se.pitch),Ct=!!se.isGold):ce?(Ve=re(ce.pitch),Ct=!!ce.isGold):Ve=n*.5}const mt=z||ae("var(--accent-primary, #ffcc00)"),Ho=1+Math.sin((a||0)*8)*.06,Mt=wt*Ho,Yr=[];for(const se of r)for(const ce of se){if(ce.startTime+ce.duration<xe||ce.startTime>De)continue;const Ee=(ce.startTime-xe)/(De-xe)*t,ye=ce.duration/(De-xe)*t,pe=re(ce.pitch)-Pe/2,he=ce.startTime+ce.duration<=a;Yr.push({x:Ee,y:pe,w:ye,h:Pe,isGold:ce.isGold,isSung:he})}if(!Jl(j||"ball",{ctx:e,ballX:st,ballY:Ve,ballRadius:Mt,playerColor:mt,ballIsGold:Ct,currentTime:a,height:n,visibleNotes:Yr})){tt&&e.drawImage(tt,0,0),Je&&e.drawImage(Je,0,0),e.save(),e.globalCompositeOperation="source-over",e.globalAlpha=.28;const se=Math.max(18,Mt*5),ce=e.createRadialGradient(st,Ve,0,st,Ve,se);if(ce.addColorStop(0,mt),ce.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=ce,e.beginPath(),e.arc(st,Ve,se,0,Math.PI*2),e.fill(),e.restore(),f&&_e&&Ye&&(_e.save(),_e.globalCompositeOperation="source-over",_e.globalAlpha=.95,_e.fillStyle=mt,_e.beginPath(),_e.arc(st,Ve,Mt+4,0,Math.PI*2),_e.fill(),_e.restore(),_e.save(),_e.globalCompositeOperation="destination-in",_e.drawImage(Ye,0,0),_e.restore(),e.drawImage(tt,0,0)),f&&$e&&Ye)try{const pe=yn(mt),{h:he,s:be,l:Se}=Vl(pe),ge=Kl(he,Math.max(10,Math.round(be*(typeof u=="number"?u:.25))),Se,.85);$e.save(),$e.globalCompositeOperation="multiply",$e.globalAlpha=.65,$e.fillStyle=ge,$e.beginPath(),$e.arc(st,Ve,Math.max(8,Mt+6),0,Math.PI*2),$e.fill(),$e.restore(),$e.save(),$e.globalCompositeOperation="destination-out",$e.drawImage(Ye,0,0),$e.restore(),e.drawImage(Je,0,0)}catch{$e.save(),$e.globalCompositeOperation="source-over",$e.globalAlpha=.6,$e.fillStyle=mt,$e.beginPath(),$e.arc(st,Ve,Math.max(8,Mt+6),0,Math.PI*2),$e.fill(),$e.restore(),$e.save(),$e.globalCompositeOperation="destination-out",$e.drawImage(Ye,0,0),$e.restore(),e.drawImage(Je,0,0)}const Ee=y&&y.shadowColor?y.shadowColor:ia,ye=y&&typeof y.glowBlur=="number"?y.glowBlur:oa;e.save(),Ct?(e.shadowColor=Ee,e.shadowBlur=ye,e.fillStyle=ae("var(--gold-light, #FFF0A8)")):(e.shadowColor=mt,e.shadowBlur=10,e.fillStyle=mt),e.globalCompositeOperation="source-over",e.globalAlpha=1,e.beginPath(),e.arc(st,Ve,Mt,0,Math.PI*2),e.fill(),e.lineWidth=1.5,e.strokeStyle=ae("var(--shadow, rgba(0,0,0,0.35))"),e.stroke(),e.restore()}try{if(Array.isArray(g)&&g.length>0){const se=Date.now(),ce=y&&typeof y.lifeMs=="number"?y.lifeMs:_l,Ee=(pe,he,be,Se=5)=>{const Fe=be,ge=be*.45;e.beginPath();let ve=Math.PI/2*3,we=pe,je=he;const Le=Math.PI/Se;e.moveTo(pe,he-Fe);for(let We=0;We<Se;We++)we=pe+Math.cos(ve)*Fe,je=he+Math.sin(ve)*Fe,e.lineTo(we,je),ve+=Le,we=pe+Math.cos(ve)*ge,je=he+Math.sin(ve)*ge,e.lineTo(we,je),ve+=Le;e.lineTo(pe,he-Fe),e.closePath()},ye=pe=>{let he=pe>>>0;return()=>(he=he*1664525+1013904223>>>0,(he&2147483647)/2147483647)};g.forEach(pe=>{const he=se-pe.createdAt;if(he<0||he>ce)return;const be=he/ce,Se=(pe.noteStart-(a-2))/7*t,Fe=re(pe.notePitch),ge=ye(pe.seed||Math.floor(pe.createdAt%1e5)),ve=y&&typeof y.count=="number"?y.count:Bl,we=y&&typeof y.baseSpeed=="number"?y.baseSpeed:zl,je=y&&typeof y.baseSize=="number"?y.baseSize:Wl;for(let Le=0;Le<ve;Le++){const We=ge(),Re=ge(),Xe=Le/ve*Math.PI*2+We*Math.PI*.6+be*1.5,ot=6+we*(1-be)*(.5+Re*.8),gt=Se+Math.cos(Xe)*ot,kt=Fe+Math.sin(Xe)*ot*(.8+We*.6),et=Math.max(1,je*(1-be)*(.5+Re)),Zr=40+Math.round(20*ge()),Xr=70+Math.round(20*ge()),Xn=Math.max(0,1-be)*(.9-ge()*.3),Yo=Math.max(6,et*2.6),Jn=ql(Zr,Xr,60,Math.round(Yo),(pe.seed||0)+Le);Jn&&Jn.complete?(e.save(),e.translate(gt,kt+4),e.rotate(Xe+be*4+(ge()-.5)*1.2),e.globalAlpha=Xn,e.drawImage(Jn,-et/2,-et/2,et,et),e.restore()):(e.save(),e.translate(gt,kt+4),e.rotate(Xe+be*4),e.fillStyle=`hsla(${Zr}, ${Xr}%, 60%, ${Xn})`,e.fillRect(-et/2,-et/2,et,et),e.restore()),ge()>.85&&(e.save(),e.globalAlpha=Math.max(.35,1-be),e.fillStyle=`hsla(${30+Math.round(10*ge())}, ${60+Math.round(30*ge())}%, ${70+Math.round(10*ge())}%, ${Xn})`,e.strokeStyle=`rgba(0,0,0,${.12*(1-be)})`,e.lineWidth=.8,Ee(gt,kt+4,et*(1.4+ge())),e.fill(),e.stroke(),e.restore())}})}}catch{}return{ballX:st,ballY:Ve,ballIsGold:Ct}},pc=({song:e,currentTime:t,playerRef:n,config:r={},userPitch:a,segmentScores:s,goldBursts:i,combo:l,verseRatings:c})=>{const{isPlaying:d=!1,playerName:u="Ziom",score:p=1e4,playerBgColor:m="var(--karaoke-player-bg, #2196f3)",playerCount:f=2,gapDesaturation:y,goldSettings:g,difficultyLevel:v,algorithmLabel:S,algorithmColor:b,latencyMs:x=null,top:w,animationMode:k,karaokeSettings:j=null}=r,T=h.useRef(null),D=h.useRef(null),[C,L]=h.useState({width:600,height:150,top:250,visibleWidth:600}),[G,q]=h.useState(0),A=h.useRef(0),V=h.useRef(null),te=h.useRef(null),ee=h.useRef(null),W=h.useRef(t),Q=h.useRef(performance.now()),E=h.useRef(e),F=h.useRef(C),N=h.useRef(a),$=h.useRef(d),M=h.useRef(0),O=h.useRef(!1),R=h.useRef(null),_=h.useRef(null),I=()=>{const B=(e==null?void 0:e.id)??null;if(B!==_.current||!R.current){_.current=B;const Z=e.notes.map(X=>X.noteLine);R.current=Pr(Z,e.bpm??void 0);const z=R.current.reduce((X,K)=>X+K.length,0),H=R.current.reduce((X,K)=>X+K.filter(J=>J.isGold).length,0),ae=R.current.flat().map(X=>X.pitch),le=ae.length?Math.min(...ae):0,ne=ae.length?Math.max(...ae):0;mr("BARS",`?? Parsed notes for "${e.title}" — ${R.current.length} verses, ${z} notes (including ${H} golden), pitch range: ${le}–${ne}, BPM: ${e.bpm??"?"}, GAP: ${e.gap??0}ms`,{rawLinesCount:Z.length,verseCount:R.current.length,totalNotes:z,goldCount:H,minPitch:le,maxPitch:ne})}return R.current};return h.useEffect(()=>{const B=(z,H,ae)=>z+(H-z)*ae,Z=z=>{te.current===null&&(te.current=z);const H=Math.min(.1,(z-(te.current||z))/1e3);te.current=z;const ae=M.current,le=A.current,ne=1-Math.exp(-12*H),X=Math.abs(le-ae)<.25?le:B(ae,le,ne);Math.abs(X-ae)>1e-4&&(q(X),M.current=X,T.current&&(T.current.style.transform=`translateX(${X}px)`)),V.current=requestAnimationFrame(Z)};return V.current=requestAnimationFrame(Z),()=>{V.current&&cancelAnimationFrame(V.current),V.current=null,te.current=null}},[]),h.useEffect(()=>{const B=()=>{if(!n.current)return;const Z=n.current.getBoundingClientRect(),z=2/Math.max(1,f),H=Math.round(Z.width*z),ae=Math.round(Z.width),le=H*(150/600);L({width:H,height:le,top:30,visibleWidth:ae})};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[n,f]),h.useEffect(()=>{var ae;if(d||!T.current)return;const B=T.current.getContext("2d");if(!B)return;const Z=I(),z=t-(e.gap??0)/1e3,H=gr(B,C.width,C.height,Z,z,u,p,m,a,e.id,y??void 0,s,v??void 0,d,g??void 0,i,S,b,M.current,C.visibleWidth,l,c,k,j);if(H&&T.current){const le=C.visibleWidth||(((ae=D.current)==null?void 0:ae.getBoundingClientRect().width)??C.width),ne=C.width;let X=Math.round(le/2-H.ballX);const K=le-ne;X=Math.max(K,Math.min(0,X)),A.current=X}},[t,e,C,a,d,s,i,k,j]),h.useEffect(()=>{W.current=t,Q.current=performance.now()},[t]),h.useEffect(()=>{E.current=e},[e]),h.useEffect(()=>{F.current=C},[C]),h.useEffect(()=>{N.current=a},[a]),h.useEffect(()=>{$.current=d},[d]),h.useEffect(()=>{const B=()=>{var oe;const Z=T.current,z=E.current,H=F.current;if(!Z||!z||!H)return;const ae=Z.getContext("2d");if(!ae)return;const le=I(),ne=Math.min(.5,(performance.now()-Q.current)/1e3),K=($.current?W.current+ne:W.current)-(z.gap??0)/1e3,J=gr(ae,H.width,H.height,le,K,u,p,m,N.current,z.id,y??void 0,s,v??void 0,$.current,g??void 0,i,S,b,M.current,H.visibleWidth,l,c,k,j);if(J){const ie=H.visibleWidth||(((oe=D.current)==null?void 0:oe.getBoundingClientRect().width)??H.width),ue=H.width;let U=Math.round(ie/2-J.ballX);const fe=ie-ue;U=Math.max(fe,Math.min(0,U)),A.current=U}};if(d){O.current||(O.current=!0,mr("BARS",`? Drawing bars in RAF loop � canvas: ${F.current.width}�${F.current.height}px, player: ${u}`,{canvasSize:F.current}));const Z=()=>{B(),ee.current=requestAnimationFrame(Z)};return ee.current=requestAnimationFrame(Z),()=>{ee.current&&cancelAnimationFrame(ee.current),ee.current=null}}O.current=!1},[d,u,p,m,y,s,v,g,i,k,j]),o.jsxs("div",{ref:D,style:{position:"absolute",left:"50%",top:`${w??C.top}px`,transform:"translateX(-50%)",zIndex:10,pointerEvents:"none",background:"transparent",width:C.visibleWidth,height:C.height,overflow:"hidden"},children:[o.jsx("style",{children:"@keyframes av-latency-pulse {0% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2);} 50% { transform: scale(1.08); box-shadow: 0 8px 18px rgba(0,0,0,0.32);} 100% { transform: scale(1); box-shadow: 0 4px 10px rgba(0,0,0,0.2);} } .av-latency-pulse { animation: av-latency-pulse 1s ease-in-out infinite; }"}),o.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 x<"u"&&x!==null?(()=>{const B=x,Z=B<=120?"var(--latency-good, #10b981)":B<=250?"var(--latency-warn, #f59e0b)":"var(--latency-bad, #ef4444)",z=`${B}ms`;return o.jsxs("div",{className:B>250?"av-latency-pulse":"",style:{background:Z,padding:"6px 10px",borderRadius:12,boxShadow:"0 4px 10px rgba(0,0,0,0.35)",fontWeight:700,minWidth:56,textAlign:"center",display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:{display:"inline-block",transform:"translateY(-1px)"},children:"??"}),o.jsx("span",{children:z})]})})():o.jsx("div",{style:{background:"var(--latency-none-bg, rgba(75,85,99,0.9))",padding:"6px 8px",borderRadius:12,boxShadow:"0 4px 10px rgba(0,0,0,0.35)",minWidth:44,textAlign:"center"},children:"�"})}),o.jsx("canvas",{ref:T,width:C.width,height:C.height,role:"img","aria-label":`Pitch timeline for ${u??"player"}. Score: ${p??0}`,style:{position:"absolute",left:0,top:0,transform:`translateX(${G}px)`,willChange:"transform"}})]})},Cs="/textures/seamless/256x256";function it(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(r,a)=>{const s=String(a+1).padStart(2,"0");return{label:`${e} ${s}`,url:`${Cs}/${e}/Photoreal_${e}_${s}-512x512.png`}})}}function dt(e,t,n){return{name:e,icon:n,entries:Array.from({length:t},(r,a)=>{const s=String(a+1).padStart(2,"0");return{label:`${e} ${s}`,url:`${Cs}/${e}/${e}_${s}-256x256.png`}})}}const Gr=[it("Fire",8,"🔥"),it("Metal",8,"⚙️"),it("Ice",8,"❄️"),it("Stone",8,"🪨"),it("Wood",8,"🪵"),it("Tile",8,"🧱"),it("Concrete",8,"🏗️"),it("Trees",8,"🌲"),it("Grass",8,"🌿"),dt("Wall",24,"🏠"),dt("Rust",24,"🟤"),dt("Woven",24,"🧵"),dt("Ground",24,"🟫"),dt("Pebbles",24,"🫧"),dt("Plant",24,"🌱"),dt("Roof",24,"🏛️"),dt("Misc",24,"🎨")],Ms=Gr.flatMap(e=>e.entries);function mc(e){return Ms.find(t=>t.url===e)}const gc=({fill:e,onChange:t,previewColor:n,accentColor:r="#0d6efd"})=>{const{t:a}=Ce(),[s,i]=h.useState(null),l=(g,v)=>{t({...e,[g]:v})},c=h.useMemo(()=>{const g=e.color||n||"#2196f3";return(v,S,b)=>{const x=fn.find(k=>k.name===v)||fn[0],w=S?Gn.find(k=>k.name===S)??null:null;return vs({width:80,height:22,capStyle:x,color:g,highlight:e.highlight,glow:e.glow,glass:e.glass,pattern:w,patternColor:e.patternColor,patternOnly:e.patternOnly,textureUrl:b??null,textureScale:e.textureScale})}},[e,n]),d=`2px solid ${r}`,u=r==="#d4a017"?"#fff8e1":"#e7f1ff",p=h.useRef(null),m=h.useRef(null),f=h.useCallback((g,v)=>{g.current&&g.current.scrollBy({left:v*180,behavior:"smooth"})},[]),y={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:"#ccc",background:"linear-gradient(90deg, rgba(30,30,30,0.9) 60%, transparent)"};return o.jsxs("div",{style:{padding:"4px 0"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[o.jsx(Ge.Form.Label,{className:"mb-0",style:{fontSize:13,color:"#ccc"},children:a("playerForm.barColor","Color")}),o.jsx(Ge.Form.Check,{type:"checkbox",id:`bar-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.color,onChange:g=>l("color",g.target.checked?null:n||"#2196f3"),className:"mb-0"}),e.color&&o.jsx("input",{type:"color",value:e.color,onChange:g=>l("color",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),o.jsx(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.capShape","Cap shape")}),o.jsxs("div",{style:{position:"relative",marginBottom:10},children:[o.jsx("button",{type:"button",style:{...y,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>f(p,-1),children:"‹"}),o.jsx("button",{type:"button",style:{...y,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>f(p,1),children:"›"}),o.jsx("div",{ref:p,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:fn.map(g=>{const v=e.capStyleName===g.name;return o.jsx("div",{title:g.name,onClick:()=>l("capStyleName",g.name),style:{cursor:"pointer",flexShrink:0,border:v?d:"1px solid #555",borderRadius:6,padding:3,background:v?u:"#222"},dangerouslySetInnerHTML:{__html:c(g.name,null)}},g.name)})})]}),o.jsx(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:a("playerForm.pattern","Pattern")}),o.jsxs("div",{style:{position:"relative",marginBottom:10},children:[o.jsx("button",{type:"button",style:{...y,left:0,borderRadius:"6px 0 0 6px"},onClick:()=>f(m,-1),children:"‹"}),o.jsx("button",{type:"button",style:{...y,left:"auto",right:0,borderRadius:"0 6px 6px 0",background:"linear-gradient(270deg, rgba(30,30,30,0.9) 60%, transparent)"},onClick:()=>f(m,1),children:"›"}),o.jsxs("div",{ref:m,style:{display:"flex",gap:6,overflowX:"auto",scrollBehavior:"smooth",padding:"4px 32px",scrollbarWidth:"none"},children:[o.jsx("div",{title:"None",onClick:()=>l("patternName",null),style:{cursor:"pointer",flexShrink:0,border:e.patternName?"1px solid #555":d,borderRadius:6,padding:"3px 8px",background:e.patternName?"#222":u,fontSize:12,lineHeight:"22px",color:"#ccc"},children:"—"}),Gn.map(g=>{const v=e.patternName===g.name;return o.jsx("div",{title:g.name,onClick:()=>l("patternName",g.name),style:{cursor:"pointer",flexShrink:0,border:v?d:"1px solid #555",borderRadius:6,padding:3,background:v?u:"#222"},dangerouslySetInnerHTML:{__html:c(e.capStyleName,g.name)}},g.name)})]})]}),o.jsx(Ge.Form.Check,{type:"switch",id:`bar-pattern-only-${r}`,label:a("playerForm.patternOnly","Pattern only (flat, no 3D)"),checked:e.patternOnly,onChange:g=>l("patternOnly",g.target.checked),className:"mb-2"}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[o.jsx(Ge.Form.Label,{className:"mb-0",style:{fontSize:13,color:"#ccc"},children:a("playerForm.patternColor","Pattern color")}),o.jsx(Ge.Form.Check,{type:"checkbox",id:`bar-pattern-color-auto-${r}`,label:a("playerForm.auto","Auto"),checked:!e.patternColor,onChange:g=>l("patternColor",g.target.checked?null:n||"#ffffff"),className:"mb-0"}),e.patternColor&&o.jsx("input",{type:"color",value:e.patternColor,onChange:g=>l("patternColor",g.target.value),style:{width:32,height:28,border:"none",padding:0,cursor:"pointer"}})]}),!e.patternOnly&&o.jsxs(o.Fragment,{children:[o.jsxs(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.highlight","Highlight"),": ",e.highlight,"%"]}),o.jsx(Ge.Form.Range,{min:0,max:100,value:e.highlight,onChange:g=>l("highlight",parseInt(g.target.value)),className:"mb-2"}),o.jsxs(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glow","Glow"),": ",e.glow,"%"]}),o.jsx(Ge.Form.Range,{min:0,max:100,value:e.glow,onChange:g=>l("glow",parseInt(g.target.value)),className:"mb-2"})]}),o.jsxs(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.glass","Transparency (glass)"),": ",e.glass,"%"]}),o.jsx(Ge.Form.Range,{min:0,max:100,value:e.glass,onChange:g=>l("glass",parseInt(g.target.value)),className:"mb-2"}),o.jsx(Ge.Form.Label,{style:{fontSize:13,fontWeight:600,marginTop:4,color:"#ccc"},children:a("playerForm.texture","Texture")}),o.jsxs("div",{style:{marginBottom:6},children:[o.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:6},children:[o.jsx("button",{type:"button",className:`btn btn-sm ${e.textureUrl?"btn-outline-secondary":"btn-primary"}`,onClick:()=>{l("textureUrl",null),i(null)},children:a("playerForm.texNone","None")}),Gr.map(g=>o.jsx("button",{type:"button",className:`btn btn-sm ${(s==null?void 0:s.name)===g.name?"btn-primary":"btn-outline-secondary"}`,onClick:()=>i(v=>(v==null?void 0:v.name)===g.name?null:g),title:g.name,children:g.icon},g.name))]}),s&&o.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",maxHeight:130,overflowY:"auto",padding:4,border:"1px solid #dee2e6",borderRadius:6,background:"#f8f9fa"},children:s.entries.map(g=>{const v=e.textureUrl===g.url;return o.jsx("div",{title:g.label,onClick:()=>l("textureUrl",v?null:g.url),style:{width:48,height:48,borderRadius:6,cursor:"pointer",border:v?`3px solid ${r}`:"1px solid #bbb",backgroundImage:`url(${g.url})`,backgroundSize:"cover",boxShadow:v?`0 0 6px ${r}`:void 0}},g.url)})}),e.textureUrl&&o.jsxs("div",{style:{marginTop:4,display:"flex",alignItems:"center",gap:8},children:[o.jsx("div",{style:{width:80,height:22,borderRadius:6,backgroundImage:`url(${e.textureUrl})`,backgroundSize:`${Math.round(256*e.textureScale)}px`,border:"1px solid #aaa"}}),o.jsx("span",{style:{fontSize:11,color:"#666"},children:e.textureUrl.split("/").pop()})]})]}),e.textureUrl&&o.jsxs(o.Fragment,{children:[o.jsxs(Ge.Form.Label,{style:{fontSize:13,color:"#ccc"},children:[a("playerForm.textureScale","Texture scale"),": ",e.textureScale.toFixed(1),"×"]}),o.jsx(Ge.Form.Range,{min:10,max:200,step:10,value:Math.round(e.textureScale*100),onChange:g=>l("textureScale",parseInt(g.target.value)/100),className:"mb-2"})]})]})},ze="[AudioPitchAnalyzer]";function yc({onSegments:e,defaultCompareAll:t=!1,externalFile:n=null,postPitch:r,postLibrosaPitchTrack:a}){const{t:s}=Ce(),[i,l]=h.useState("pitchy"),[c,d]=h.useState(null),[u,p]=h.useState(t),[m,f]=h.useState({}),[y,g]=h.useState({}),[v,S]=h.useState([]),[b,x]=h.useState([]),[w,k]=h.useState(!1),[j,T]=h.useState(null),[D]=h.useState(null),[C]=h.useState(null),[L,G]=h.useState(null),q=h.useRef(null);function A(N){try{if(N instanceof Error){let M=`${N.message}
40
+ ${N.stack??""}`;const O=N;if(O!=null&&O.attemptedUrls)try{M+=`
41
+ Attempted URLs: ${Array.isArray(O.attemptedUrls)?O.attemptedUrls.join(", "):String(O.attemptedUrls)}`}catch{M+=`
42
+ Attempted URLs: ${String(O.attemptedUrls)}`}return M}const $=N;return $!=null&&$.attemptedUrls?`Error: ${String($.message??$)}
43
+ Attempted URLs: ${Array.isArray($.attemptedUrls)?$.attemptedUrls.join(", "):String($.attemptedUrls)}`:String(N)}catch{return"Unknown error"}}function V(N){if(!N||N<=0)return null;const $=12*Math.log2(N/440)+69;return Math.round($-12)}async function te(N){var M;const $=(M=N.target.files)==null?void 0:M[0];$&&await ee($,u)}async function ee(N,$){T(null),x([]),k(!0);try{const M=await N.arrayBuffer(),O=window.AudioContext??window.webkitAudioContext,_=await new O().decodeAudioData(M),I=_.getChannelData(0);d(I);const B=_.sampleRate,Z=Math.floor(B*.1),z=Z,H=()=>{const J=[],oe=ur.PitchDetector.forFloat32Array(Z);for(let ie=0;ie<I.length-Z;ie+=z){const ue=I.slice(ie,ie+Z),[U,fe]=oe.findPitch(ue,B),me=V(U);me&&U>50&&U<2e3&&fe>.7&&J.push({start:ie/B,duration:Z/B,pitch:me,freq:U})}return J},ae=()=>{const J=[];for(let oe=0;oe<I.length-Z;oe+=z){const ie=I.slice(oe,oe+Z),ue=Q(ie,B),U=V(ue);U&&ue>50&&ue<2e3&&J.push({start:oe/B,duration:Z/B,pitch:U,freq:ue})}return J};if($){k(!0),T(null);const J={};try{const oe={};try{J.pitchy=H(),oe.pitchy=null}catch(ie){J.pitchy=[],oe.pitchy=A(ie),console.warn(ze,"pitchy failed",ie)}try{J["ultrastar-wp"]=ae(),oe["ultrastar-wp"]=null}catch(ie){J["ultrastar-wp"]=[],oe["ultrastar-wp"]=A(ie),console.warn(ze,"ultrastar-wp failed",ie)}J.aubio=[],oe.aubio="disabled";try{if(!r)throw new Error("CREPE backend not configured");const ue=(await r(N)).track??[];J.crepe=ue.map((U,fe)=>{var me;return{start:U.t,duration:(me=ue[fe+1])!=null&&me.t?ue[fe+1].t-U.t:.1,pitch:V(U.hz)??0,freq:U.hz}}),oe.crepe=null}catch(ie){J.crepe=[],oe.crepe=A(ie),console.warn(ze,"crepe failed",ie)}try{if(!a)throw new Error("Librosa backend not configured");const ue=(await a(new File([N],N.name,{type:N.type}))).track??[];J.librosa=ue.map((U,fe)=>{var me;return{start:U.t,duration:(me=ue[fe+1])!=null&&me.t?ue[fe+1].t-U.t:.1,pitch:V(U.hz)??0,freq:U.hz}}),oe.librosa=null}catch(ie){J.librosa=[],oe.librosa=A(ie),console.warn(ze,"librosa failed",ie)}g(oe),f(J),x(J[i]??[])}catch(oe){console.error(ze,"[AudioPitchAnalyzer] compareAll overall failed",oe);const ie=oe instanceof Error?oe.message:String(oe);T(s("audioPitch.errorComparing")+ie)}finally{k(!1)}return}const le=[],ne=[];let X=0;if(i==="pitchy"){const J=ur.PitchDetector.forFloat32Array(Z);for(let oe=0;oe<I.length-Z;oe+=z){const ie=I.slice(oe,oe+Z);let ue=0;for(let xe=0;xe<ie.length;xe++)ue+=ie[xe]*ie[xe];ue=Math.sqrt(ue/ie.length),ne.push(ue);const[U,fe]=J.findPitch(ie,B),me=V(U);me&&U>50&&U<2e3&&fe>.7&&(le.push({start:oe/B,duration:Z/B,pitch:me,freq:U}),X++)}}else if(i==="crepe")try{if(!r)throw new Error("CREPE backend not configured");const J=await r(N);if(!J.track||J.track.length===0)T(s("audioPitch.crepeNoNotes")),console.warn(ze,"[AudioPitchAnalyzer] Crepe: No notes detected in audio file.");else{const oe=J.track.map((ie,ue)=>{const U=V(ie.hz);return U&&ie.hz>50&&ie.hz<2e3?{start:ie.t,duration:ue<J.track.length-1?J.track[ue+1].t-ie.t:.1,pitch:U,freq:ie.hz}:null}).filter(ie=>ie!==null);if(x(oe),e)try{e(oe)}catch(ie){console.error(ze,"[AudioPitchAnalyzer] Error in onSegments:",ie)}S([]),d(null);return}}catch(J){T(s("audioPitch.crepeBackendError")),G(A(J)),console.error(ze,"[AudioPitchAnalyzer] Crepe: Error calling backend:",J)}else if(i==="librosa")try{await W(N),S([]),d(null);return}catch(J){T(s("audioPitch.librosaBackendError")),G(A(J)),console.error(ze,"[AudioPitchAnalyzer] Librosa: Error calling backend:",J)}else if(i==="ultrastar-wp")for(let J=0;J<I.length-Z;J+=z){const oe=I.slice(J,J+Z);let ie=0;for(let fe=0;fe<oe.length;fe++)ie+=oe[fe]*oe[fe];ie=Math.sqrt(ie/oe.length),ne.push(ie);const ue=Q(oe,B),U=V(ue);U&&ue>50&&ue<2e3&&(le.push({start:J/B,duration:Z/B,pitch:U,freq:ue}),X++)}S(ne);const K=E(le);if(x(K),e)try{e(K)}catch(J){console.error(ze,"[AudioPitchAnalyzer] Error in onSegments:",J)}K.length===0&&i!=="crepe"&&(T(s("audioPitch.noNotesDetected")),console.warn(ze,"[AudioPitchAnalyzer] No notes detected in audio file."))}catch(M){T(s("audioPitch.errorAnalyzing")+(M instanceof Error?M.message:String(M))),G(A(M)),console.error(ze,"[AudioPitchAnalyzer] Error analyzing audio file:",M)}finally{k(!1)}}h.useEffect(()=>{n&&ee(n,!0)},[n]);async function W(N){try{if(!a)throw new Error("Librosa backend not configured");const $=new File([N],"capture.wav",{type:"audio/wav"}),O=((await a($)).track??[]).map(R=>({t:R.t,hz:R.hz}));if(e){const R=O.map((_,I)=>{var z;const B=((z=O[I+1])==null?void 0:z.t)??_.t+.1,Z=V(_.hz)??0;return{start:_.t,duration:Math.max(.05,B-_.t),pitch:Z,freq:_.hz}});e(R),x(R)}}catch($){console.warn(ze,"Librosa analysis failed, falling back to local detectors",$);const O=(typeof $=="object"&&$!==null?$:{}).attemptedUrls;O&&console.error(ze,"[AudioPitchAnalyzer] Librosa attempted URLs:",O);const R=O?Array.isArray(O)?O.join(", "):String(O):null,_=$ instanceof Error?$.message:String($);T(s("audioPitch.librosaBackendError")+": "+_+(R?" (attempted: "+R+")":"")),G(A($))}}function Q(N,$){const R=Math.floor($/50),_=Math.max(2,Math.floor($/2e3));let I=0;for(let H=0;H<N.length;H++)I+=N[H]*N[H];if(I<=1e-8)return 0;let B=-1,Z=0;const z=1e-10;for(let H=_;H<=Math.min(R,N.length-2);H++){let ae=0;const le=N.length-H;for(let X=0;X<le;X++)ae+=N[X]*N[X+H];const ne=ae/(le+z)/(I/N.length+z);ne>Z&&(Z=ne,B=H)}return B>0&&Z>.01?$/B:0}function E(N){if(N.length===0)return[];const $=[];let M=N[0];for(let O=1;O<N.length;O++){const R=N[O];R.pitch===M.pitch&&Math.abs(R.freq-M.freq)<1?M.duration+=R.duration:($.push(M),M=R)}return $.push(M),$}function F(){try{const N=Object.keys(m).length>0?Object.keys(m):["pitchy","ultrastar-wp","aubio","crepe","librosa"],$=(()=>{let X=0;for(const K of N){const J=m[K]??[];for(const oe of J)X=Math.max(X,oe.start+(oe.duration||0))}return X||0})(),M=(X,K)=>!X||!K?1/0:1200*Math.log2(X/K),O=(X,K)=>{if(!X||!K)return!1;const J=Math.round(Math.log2(K/X)),oe=X*Math.pow(2,J),ie=Math.abs(M(oe,K));return Math.abs(J)>=1&&ie<50},R=X=>{const K={count:0,totalDur:0,meanFreq:0,stdFreq:0,meanDur:0,voicedFraction:null};if(!X||X.length===0)return K;K.count=X.length,K.totalDur=X.reduce((ue,U)=>ue+(U.duration||0),0);const J=X.map(ue=>ue.freq).filter(Boolean);if(J.length===0)return K;const oe=J.reduce((ue,U)=>ue+U,0)/J.length,ie=J.reduce((ue,U)=>ue+(U-oe)*(U-oe),0)/J.length;return K.meanFreq=oe,K.stdFreq=Math.sqrt(ie||0),K.meanDur=K.totalDur/K.count,K.voicedFraction=$>0?K.totalDur/$:null,K},_=(X,K)=>{let J=0,oe=0;const ie=[];for(const U of X){const fe=U.start,me=U.start+(U.duration||.05);let xe=null,De=0;for(const Te of K){const Me=Te.start,Y=Te.start+(Te.duration||.05),re=Math.max(0,Math.min(me,Y)-Math.max(fe,Me));re>De&&(De=re,xe=Te)}if(xe&&De>0){const Te=Math.abs(M(U.freq,xe.freq));ie.push(Te),Te<50&&J++,O(U.freq,xe.freq)&&oe++}}const ue=ie.length?ie.reduce((U,fe)=>U+fe,0)/ie.length:null;return{matches:J,compared:X.length,meanCents:ue,octaveErrors:oe}},I=[];I.push("# AudioPitchAnalyzer � Comparative Report"),I.push(`Generated: ${new Date().toISOString()}`),I.push(""),I.push("## Summary"),I.push(`- Selected algorithm in UI: **${i}**`),I.push(`- Total analyzed duration (approx): **${$.toFixed(3)} s**`),I.push(""),I.push("## Per-algorithm statistics"),I.push("| Algorithm | Segments | Total voiced (s) | Voiced fraction | Mean freq (Hz) | Std freq (Hz) | Mean dur (s) |"),I.push("|---|---:|---:|---:|---:|---:|---:|");const B={};for(const X of N){const K=m[X]??[],J=R(K);B[X]=J,I.push(`| ${X} | ${J.count||0} | ${(J.totalDur||0).toFixed(3)} | ${J.voicedFraction!==null?(J.voicedFraction*100).toFixed(1)+"%":"N/A"} | ${J.meanFreq?J.meanFreq.toFixed(1):"N/A"} | ${J.stdFreq?J.stdFreq.toFixed(1):"N/A"} | ${J.meanDur?J.meanDur.toFixed(3):"N/A"} |`)}I.push(""),I.push("## Pairwise agreement (reference -> test)");const Z=N.includes("crepe")?"crepe":N.includes("librosa")?"librosa":N.includes("pitchy")?"pitchy":N[0];I.push(`Reference algorithm: **${Z}**`),I.push(""),I.push("| Reference -> Test | Matches | Compared (ref) | Match % | Mean cents diff | Octave errors |"),I.push("|---|---:|---:|---:|---:|---:|");for(const X of N){if(X===Z)continue;const K=_(m[Z]??[],m[X]??[]),J=K.compared?(K.matches/K.compared*100).toFixed(1)+"%":"N/A";I.push(`| ${Z} -> ${X} | ${K.matches} | ${K.compared} | ${J} | ${K.meanCents!==null?K.meanCents.toFixed(1):"N/A"} | ${K.octaveErrors} |`)}I.push(""),I.push("## Observations and analysis"),I.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."),I.push("- Pairwise match rate shows how often algorithms agree on the same regions (within ~50 cents). Octave error counts highlight typical autocorrelation octave mistakes."),I.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."),I.push("");for(const X of N){I.push(`### ${X}`);const K=B[X];I.push(`- Segments: ${K.count||0}`),I.push(`- Total voiced (s): ${(K.totalDur||0).toFixed(3)}`),I.push(`- Voiced fraction: ${K.voicedFraction!==null?(K.voicedFraction*100).toFixed(1)+"%":"N/A"}`),I.push(`- Mean frequency: ${K.meanFreq?K.meanFreq.toFixed(2)+" Hz":"N/A"}`),I.push(`- Std frequency: ${K.stdFreq?K.stdFreq.toFixed(2)+" Hz":"N/A"}`),I.push("")}I.push("## Conclusions & recommendation");const z=[];for(const X of N){if(X===Z){z.push({alg:X,score:100});continue}const K=_(m[Z]??[],m[X]??[]),J=K.compared?K.matches/K.compared:0,oe=K.compared?K.octaveErrors/K.compared:0,ie=J-oe*.5;z.push({alg:X,score:ie})}z.sort((X,K)=>K.score-X.score),I.push(`- Based on this recording, recommended authoritative detector: **${z[0].alg}** (best agreement with reference).`),I.push("- For live, low-latency feedback use Pitchy (YIN) with smoothing/hysteresis; use Crepe/Librosa for authoritative scoring or post-processing."),I.push("- If octave errors are frequent, consider octave-correction heuristics (prefer lower octave when ambiguity) or combine detectors via voting."),I.push(""),I.push("## Raw data (per-algorithm segments)");for(const X of N){const K=m[X]??[];I.push(`### ${X} � ${K.length} segments`);for(const oe of K)I.push(`- ${oe.start.toFixed(3)} .. ${(oe.start+(oe.duration||0)).toFixed(3)} : ${oe.freq.toFixed(2)} Hz (pitch ${oe.pitch})`);const J=y[X];J&&I.push(`- Error: ${J}`),I.push("")}const H=I.join(`
44
+ `),ae=new Blob([H],{type:"text/markdown;charset=utf-8"}),le=URL.createObjectURL(ae),ne=document.createElement("a");ne.href=le,ne.download="audiopitch_scientific_report_"+(n?n.name:"capture")+".md",document.body.appendChild(ne),ne.click(),ne.remove(),URL.revokeObjectURL(le)}catch(N){console.error(ze,"[AudioPitchAnalyzer] generateScientificReport error",N),console.warn(s("audioPitch.reportError")+String(N),"error")}}return o.jsxs("div",{style:{marginTop:32,padding:16,border:"1px solid #ccc",borderRadius:8},children:[o.jsx("h3",{children:s("audioPitch.title")}),o.jsxs("div",{style:{marginBottom:12},children:[o.jsx("label",{htmlFor:"pitch-algorithm-select",style:{marginRight:8},children:s("audioPitch.algorithm")}),o.jsxs("select",{id:"pitch-algorithm-select",value:i,onChange:N=>l(N.target.value),style:{marginRight:16},children:[o.jsx("option",{value:"ultrastar-wp",children:"Ultrastar WP (autokorelacja)"}),o.jsx("option",{value:"crepe",children:"crepe (AI)"}),o.jsx("option",{value:"pitchy",children:"pitchy (YIN)"}),o.jsx("option",{value:"librosa",children:"Librosa (PYIN)"})]}),o.jsxs("label",{style:{marginRight:8},children:[o.jsx("input",{type:"checkbox",checked:u,onChange:N=>p(N.target.checked)})," ",s("audioPitch.compareAll")]}),o.jsx("input",{type:"file",accept:"audio/*",ref:q,onChange:te,disabled:w})]}),w&&o.jsx("div",{children:s("audioPitch.analyzing")}),o.jsxs("div",{style:{marginTop:8},children:[o.jsx("b",{children:s("audioPitch.method")})," ",i]}),j&&o.jsxs("div",{style:{color:"red",marginTop:8},children:[o.jsxs("b",{children:[i,": "]}),o.jsx("div",{children:j}),L&&o.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap",marginTop:8},children:L})]}),D&&o.jsxs("div",{style:{marginTop:12},children:[o.jsx("b",{children:"Aubio diagnostics"}),o.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:D}),C&&o.jsxs("div",{style:{marginTop:8},children:[o.jsx("b",{children:"Probe:"})," ",C]})]}),(Object.keys(m).length>0||Object.keys(y).length>0)&&o.jsxs("div",{style:{marginTop:12},children:[o.jsx("button",{onClick:()=>F(),children:s("audioPitch.downloadReport")}),Object.entries(y).length>0&&o.jsxs("div",{style:{marginTop:8},children:[o.jsx("b",{children:"Per-algorithm errors:"}),Object.entries(y).filter(([N,$])=>$).map(([N,$])=>o.jsxs("div",{style:{marginTop:6},children:[o.jsxs("b",{children:[N,":"]}),o.jsx("pre",{style:{background:"#111",color:"#f88",padding:8,borderRadius:4,whiteSpace:"pre-wrap"},children:$})]},N))]})]}),b.length>0&&o.jsxs("div",{style:{marginTop:16},children:[o.jsx("b",{children:s("audioPitch.resultUltrastar")}),o.jsxs("pre",{style:{background:"#222",color:"#fff",padding:8,borderRadius:4},children:[b.map(N=>`: ${Math.round(N.start*10)} ${Math.round(N.duration*10)} ${N.pitch} [${N.freq.toFixed(1)} Hz]`).join(`
45
+ `),`
46
+ -`]})]}),c&&c.length>0&&o.jsxs("div",{style:{marginTop:24},children:[o.jsx("b",{children:s("audioPitch.waveformRms")}),o.jsx("canvas",{width:600,height:100,style:{background:"#222",borderRadius:4,width:"100%",maxWidth:600,display:"block"},role:"img","aria-label":"Waveform and RMS visualization canvas",ref:N=>{if(!N)return;const $=N.getContext("2d");if($){$.clearRect(0,0,600,100),$.strokeStyle="#0ff",$.beginPath();for(let M=0;M<c.length;M+=Math.ceil(c.length/600)){const O=M/c.length*600,R=50-c[M]*48;M===0?$.moveTo(O,R):$.lineTo(O,R)}if($.stroke(),v.length>0){$.strokeStyle="#ff0",$.beginPath();for(let M=0;M<v.length;M++){const O=M/v.length*600,R=100-v[M]*90;M===0?$.moveTo(O,R):$.lineTo(O,R)}$.stroke()}}}}),o.jsxs("div",{style:{color:"#aaa",fontSize:12,marginTop:4},children:[o.jsx("span",{style:{color:"#0ff"},children:"Waveform"}),"  |  ",o.jsx("span",{style:{color:"#ff0"},children:"RMS"})]})]}),!w&&b.length===0&&!j&&o.jsx("div",{style:{marginTop:16,color:"#aaa"},children:o.jsx("i",{children:s("audioPitch.noNotesDetected")})}),u&&Object.keys(m).length>0&&o.jsxs("div",{style:{marginTop:16},children:[o.jsx("h4",{children:s("audioPitch.algorithmComparison")}),Object.entries(m).map(([N,$])=>o.jsxs("div",{style:{marginBottom:12},children:[o.jsx("b",{children:N}),": ",s("audioPitch.detectedSegments")," ",$.length,o.jsx("pre",{style:{background:"#111",color:"#ddd",padding:8,borderRadius:4,marginTop:8},children:$.map(M=>`: ${Math.round(M.start*10)} ${Math.round(M.duration*10)} ${M.pitch} [${M.freq.toFixed(1)} Hz]`).join(`
47
+ `)})]},N))]})]})}function ke(e,t){var a;const n=((a=t.split(".").pop())==null?void 0:a.toLowerCase())??"",r=n==="otf"?"opentype":n==="woff2"?"woff2":n==="woff"?"woff":"truetype";return{family:e,url:`/fonts/${t}`,format:r}}const bc=[ke("Belagak","BelagakRegular-dr1zE.otf"),ke("Big Scratch Brush","BigScratchBrush-PVY9g.ttf"),ke("Gerhaus","Gerhaus-PK69E.ttf"),ke("Gerhaus Italic","GerhausItalic-d96l7.ttf"),ke("Handone Medium","HandoneMedium-nAevO.otf"),ke("Handson Bold","HandsonBold-9MnrL.otf"),ke("Kineks Round Bold","KineksRoundBold-7OR34.ttf"),ke("Kineks Round Light","KineksRoundLight-m2r35.ttf"),ke("Kineks Round Medium","KineksRoundMedium-drejZ.ttf"),ke("Kineks Round","KineksRoundRegular-PVRl7.ttf"),ke("Kineks Round SemiBold","KineksRoundSemiBold-LVWG3.ttf"),ke("Lemon Jelly","LemonJellyPersonalUse-dEqR.ttf"),ke("Lemon Milk Bold","LemonMilkBold-gx2B3.otf"),ke("Lemon Milk Bold Italic","LemonMilkBoldItalic-PKZ3P.otf"),ke("Lemon Milk Light","LemonMilkLight-owxMq.otf"),ke("Lemon Milk Light Italic","LemonMilkLightItalic-7BjPE.otf"),ke("Lemon Milk Medium","LemonMilkMedium-mLZYV.otf"),ke("Lemon Milk Medium Italic","LemonMilkMediumItalic-d95nl.otf"),ke("Lemon Milk","LemonMilkRegular-X3XE2.otf"),ke("Lemon Milk Italic","LemonMilkRegularItalic-L3AEy.otf"),ke("Pemage","PemageRegular-YqrdO.otf"),ke("Rosmatika","RosmatikaRegular-BWA45.ttf"),ke("Scabber","Scabber-q2Mn0.ttf"),ke("Stylish Calligraphy","StylishCalligraphyDemo-XPZZ.ttf"),ke("Super Adorable","SuperAdorable-MAvyp.ttf"),ke("Super Chiby","SuperChiby-BL62V.ttf"),ke("Super Joyful","SuperJoyful-lxwPq.ttf"),ke("Super Kindly","SuperKindly-drE8E.ttf"),ke("Super Meatball","SuperMeatball-Yq1Gy.ttf")],_r="nice2dev-karaoke-display",vc=[{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"},...bc.map(e=>({value:e.family,label:e.family}))],ks=[{id:"default",name:"Cyan ? Yellow ? Amber",sungGradient:["#00e5ff","#ffe600","#ffab00"],goldGradient:["#FFD700","#FFA000","#FFD700"],glowColor:"rgba(0,229,255,0.6)"},{id:"neon-pink",name:"Neon Pink ? Violet ? Blue",sungGradient:["#ff1493","#9b59b6","#3498db"],goldGradient:["#FFD700","#FF69B4","#FFD700"],glowColor:"rgba(255,20,147,0.6)"},{id:"fire",name:"Red ? Orange ? Yellow",sungGradient:["#ff1744","#ff9100","#ffea00"],goldGradient:["#FFD700","#FF6D00","#FFD700"],glowColor:"rgba(255,23,68,0.6)"},{id:"ocean",name:"Deep Blue ? Teal ? Aqua",sungGradient:["#1a237e","#00897b","#00e5ff"],goldGradient:["#FFD700","#00BCD4","#FFD700"],glowColor:"rgba(0,137,123,0.6)"},{id:"forest",name:"Green ? Lime ? Yellow",sungGradient:["#1b5e20","#76ff03","#ffea00"],goldGradient:["#FFD700","#76ff03","#FFD700"],glowColor:"rgba(118,255,3,0.6)"},{id:"retro",name:"Orange ? Pink ? Purple",sungGradient:["#ff6d00","#e91e63","#7b1fa2"],goldGradient:["#FFD700","#E91E63","#FFD700"],glowColor:"rgba(233,30,99,0.6)"}],zt={presetId:"default",customSungGradient:["#00e5ff","#ffe600","#ffab00"],customGoldGradient:["#FFD700","#FFA000","#FFD700"],customGlowColor:"rgba(0,229,255,0.6)",animationMode:"ball",fontFamily:"Arial",transitionEffect:"none",curtainPrimaryColor:"#8b0000",curtainSecondaryColor:"#1a0000",curtainDurationMs:900,immersiveMode:!1};let ya=!1;function $s(){try{const e=localStorage.getItem(_r);if(e){const t=JSON.parse(e);return{...zt,...t}}}catch{}return{...zt}}async function xc(e){if(ya||(ya=!0,!e))return;const t=await e();if(t)try{const n=JSON.parse(t),r={...zt,...n};localStorage.setItem(_r,JSON.stringify(r))}catch{}}function Sc(e){const t=JSON.stringify(e);localStorage.setItem(_r,t),Br(e)}function Rs(e){if(e.presetId==="custom")return{sungGradient:e.customSungGradient,goldGradient:e.customGoldGradient,glowColor:e.customGlowColor};const t=ks.find(n=>n.id===e.presetId);return t?{sungGradient:t.sungGradient,goldGradient:t.goldGradient,glowColor:t.glowColor}:{sungGradient:zt.customSungGradient,goldGradient:zt.customGoldGradient,glowColor:zt.customGlowColor}}function Br(e){const{sungGradient:t,goldGradient:n,glowColor:r}=Rs(e),a=document.documentElement;a.style.setProperty("--karaoke-sung-gradient",`linear-gradient(90deg, ${t[0]} 0%, ${t[1]} 60%, ${t[2]} 100%)`),a.style.setProperty("--karaoke-gold-gradient",`linear-gradient(90deg, ${n[0]}, ${n[1]}, ${n[2]})`),a.style.setProperty("--karaoke-gold-glow-first",`0 0 12px ${n[0]}`),a.style.setProperty("--karaoke-active-glow",`0 0 10px ${r}, 0 0 4px ${t[1]}80`),a.style.setProperty("--karaoke-active-drop-first",`0 0 6px ${r}`),a.style.setProperty("--karaoke-active-bg",`linear-gradient(90deg, transparent 0%, ${t[0]}14 20%, ${t[1]}10 80%, transparent 100%)`),a.style.setProperty("--karaoke-font-family",e.fontFamily||"Arial")}function wc(){const e=$s();Br(e)}const ln=["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)"],js={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 yr(e){return 440*Math.pow(2,(e-69)/12)}function Ts(e,t){const n=js[t],r=n.keys.length,a=[];for(const d of e)for(const u of d)a.includes(u.pitch)||a.push(u.pitch);if(a.sort((d,u)=>d-u),a.length===0)return n.keys.map((d,u)=>({index:u,key:d,gamepadButton:n.buttons[u],label:n.labels[u],minPitch:-999,maxPitch:999,color:ln[u%ln.length]}));const s=a[0],l=a[a.length-1]-s+1,c=[];for(let d=0;d<r;d++){const u=s+Math.floor(l*d/r),p=s+Math.floor(l*(d+1)/r)-1;c.push({index:d,key:n.keys[d],gamepadButton:n.buttons[d],label:n.labels[d],minPitch:d===0?-999:u,maxPitch:d===r-1?999:p,color:ln[d%ln.length]})}return c}function Ps(e,t){for(const a of t)if(e>=a.minPitch&&e<=a.maxPitch)return a.index;let n=0,r=1/0;for(const a of t){const s=(a.minPitch+a.maxPitch)/2,i=Math.abs(e-s);i<r&&(r=i,n=a.index)}return n}function Es(e,t,n){const r=[];for(let a=0;a<e.length;a++)for(let s=0;s<e[a].length;s++){const i={...e[a][s]};i.startTime+=n,r.push({note:i,lane:Ps(i.pitch,t),lineIndex:a,noteIndex:s})}return r.sort((a,s)=>a.note.startTime-s.note.startTime),r}class Cc{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,u,p,m,f,y,g;if(!this.running)return;const a=this.getCurrentTime();this.pollGamepad();const s=this.getActiveLanes();(d=(c=this.config).onLaneActive)==null||d.call(c,s);const i=this.findActiveNote(a);if(i!==this.lastActiveNote&&(this.lastActiveNote=i,(p=(u=this.config).onCurrentNote)==null||p.call(u,i)),s.some(Boolean)&&i){const v=i.lane,S=s.indexOf(!0);if(s[v]){const b=yr(i.note.pitch);this.config.onPitch(b),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(f=(m=this.config).onHitFeedback)==null||f.call(m,{type:"perfect",lane:v,time:a}))}else if(S>=0){const x=Math.abs(S-v)*3,w=yr(i.note.pitch+x);this.config.onPitch(w),a-this.lastFeedbackTime>.3&&(this.lastFeedbackTime=a,(g=(y=this.config).onHitFeedback)==null||g.call(y,{type:"miss",lane:S,time:a}))}}this.raf=requestAnimationFrame(this.loop)},this.config=t;const n=Pr(t.noteLines,t.bpm),r=(t.gap??0)/1e3;switch(this.lanes=Ts(n,t.difficulty),this.events=Es(n,this.lanes,r),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 r;const n=(r=t.target)==null?void 0:r.tagName;n&&["INPUT","TEXTAREA","SELECT"].includes(n)||this.keysDown.add(t.key.toLowerCase())}handleKeyUp(t){this.keysDown.delete(t.key.toLowerCase())}pollGamepad(){var r;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 a=0;a<n.buttons.length;a++)(r=n.buttons[a])!=null&&r.pressed&&this.gamepadButtonsDown.add(a)}}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 r=n.note.startTime-this.preWindow,a=n.note.startTime+n.note.duration+this.postWindow;if(t>=r&&t<=a)return n}return null}}function Mc(e){const t=(e||"").split(/\r?\n/),n=[];for(let r=0;r<t.length;r++){const a=t[r].trim();if(a&&/^[:*F]\s/.test(a)){const s=a.slice(1).trim().split(/\s+/),i=parseInt(s[0]||"0",10),l=parseInt(s[1]||"0",10),c=isNaN(i)?0:i/10,d=isNaN(l)?0:l/10;n.push({lineIndex:r,start:c,duration:d,raw:t[r]})}}return n}const kc=({index:e,style:t,lines:n,notes:r,currentIndex:a,animationConfig:s})=>{const i=n[e]??"",l=r.findIndex(S=>S.lineIndex===e),c=l>=0&&l===a,d=(s==null?void 0:s.enabled)??!0,u=(s==null?void 0:s.durationMs)??300,p=(s==null?void 0:s.translateX)??8,m=(s==null?void 0:s.scale)??1.01,f=(s==null?void 0:s.easing)??"cubic-bezier(.22,1,.36,1)",y=(s==null?void 0:s.opacityInactive)??.9,g=(s==null?void 0:s.boxShadow)??"0 6px 18px rgba(3,102,214,0.08)",v={transition:d?`transform ${u}ms ${f}, opacity ${u}ms ${f}`:"none",transform:c?`translateX(${p}px) scale(${m})`:"translateX(0px) scale(1)",opacity:c?1:y,boxShadow:c?g:"none"};return o.jsx("div",{style:{...t,padding:"4px 6px",borderRadius:4},"data-note-idx":l>=0?l:void 0,children:o.jsx("div",{style:{...v,background:c?"rgba(0,130,200,0.12)":"transparent",padding:"4px 6px",borderRadius:4},children:o.jsx("code",{style:{fontFamily:"monospace",whiteSpace:"pre-wrap"},children:i})})})},$c=({ultrastarText:e,audioUrl:t,audioRef:n,animationConfig:r})=>{const{t:a}=Ce(),s=h.useRef(null),i=n??s,[l,c]=h.useState(!1),d=h.useMemo(()=>Mc(e),[e]),u=h.useRef(null),p=h.useRef(null),m=h.useRef(0),f=h.useRef(0),[y,g]=h.useState(-1),v=h.useMemo(()=>(e||"").split(/\r?\n/),[e]),S=28,b=v.length*S,x=h.useMemo(()=>({lines:v,notes:d,currentIndex:y,animationConfig:r}),[v,d,y,r]);return h.useEffect(()=>{const w=i.current;w&&(l?w.play().catch(()=>c(!1)):w.pause())},[l,i]),h.useEffect(()=>{const w=i.current;if(!w)return;let k=-1;const j=r??null,T=j&&typeof j.scrollSmooth=="number"?j.scrollSmooth:.18;let D=performance.now();const C=()=>{var F,N,$,M;const L=performance.now(),G=Math.max(0,Math.min(.2,(L-D)/1e3));D=L;const q=w.currentTime||0;m.current=q;let A=-1;for(let O=0;O<d.length;O++){const R=d[O];if(q>=R.start&&q<R.start+Math.max(.001,R.duration)){A=O;break}}A!==k&&(k=A,g(A));let V=0;if(k>=0){const O=((F=d[k])==null?void 0:F.lineIndex)??0,R=(($=(N=u.current)==null?void 0:N.element)==null?void 0:$.clientHeight)??220;V=O*S-R/2+S/2;const _=Math.max(0,b-R);(isNaN(V)||!isFinite(V))&&(V=0),V=Math.max(0,Math.min(V,_))}const te=1-Math.pow(Math.max(0,1-T),Math.min(4,G*60)),E=(((r==null?void 0:r.scrollEasing)||"easeOutCubic")==="linear"?(O=>O):O=>1-Math.pow(1-O,3))(te);f.current=f.current+(V-f.current)*E;try{const O=(M=u.current)==null?void 0:M.element;O&&typeof O.scrollTop=="number"&&(O.scrollTop=Math.round(f.current))}catch{}p.current=requestAnimationFrame(C)};return p.current=requestAnimationFrame(C),()=>{p.current&&cancelAnimationFrame(p.current)}},[i,d,b,r,u]),o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:8},children:[o.jsx("button",{onClick:()=>c(w=>!w),disabled:!t,children:l?"Pause":"Play"}),o.jsxs("div",{style:{fontSize:13,color:"#666"},children:[(m.current||0).toFixed(2),"s"]}),o.jsxs("div",{style:{marginLeft:"auto",fontSize:13,color:"#666"},children:["Notes: ",d.length]})]}),o.jsx("div",{style:{border:"1px solid #ddd",height:220,overflow:"hidden",padding:8,position:"relative"},children:e?o.jsx(ni.List,{defaultHeight:220,rowCount:v.length,rowHeight:S,listRef:u,rowComponent:kc,rowProps:x,style:{width:"100%"}}):o.jsx("div",{style:{color:"#888"},children:a("karaokeEditor.noText","No text")})}),!n&&o.jsx("audio",{ref:s,src:t||void 0,preload:"metadata",style:{display:"none"}})]})};function Rc(e){const t=(e||"").split(/\r?\n/).map(r=>r.replace(/\s+$/,"")),n=[];for(let r=0;r<t.length;r++){const a=t[r].trim();if(/^[:*F]\s/.test(a)){const s=a.slice(1).trim().split(/\s+/),i=parseInt(s[0]||"0",10)/10||0,l=parseInt(s[1]||"0",10)/10||.1;n.push({lineIndex:r,start:i,duration:l})}}return{lines:t,notes:n}}function jc({ultrastarText:e,audioUrl:t,audioRef:n,ytRef:r}){const a=h.useRef(null),s=h.useRef(null),i=h.useRef([]),l=h.useRef([]),c=h.useRef(null),d=h.useRef(t);return d.current=t,h.useEffect(()=>{const{lines:u,notes:p}=Rc(e);i.current=u,l.current=p;const m=c.current;m&&"rebuildTexts"in m&&typeof m.rebuildTexts=="function"&&m.rebuildTexts()},[e]),h.useEffect(()=>{let u=!0;return(async()=>{var j;if(!u||!a.current)return;const p=await import("phaser"),m="default"in p?p.default:p;if(!a.current||!u)return;const f=i,y=l,g=c,v=n,S=r,b=d;class x extends m.Scene{constructor(){super({key:"preview"}),this.texts=[],this.audioEl=null}create(){if(g.current=this,this.rebuildTexts(),S!=null&&S.current)this.audioEl=null;else if(v!=null&&v.current)this.audioEl=v.current;else{const D=document.querySelector("audio");D instanceof HTMLAudioElement?this.audioEl=D:b.current?(this.audioEl=document.createElement("audio"),this.audioEl.src=b.current,this.audioEl.preload="metadata",this.audioEl.style.display="none",document.body.appendChild(this.audioEl)):this.audioEl=null}}rebuildTexts(){for(const q of this.texts)q.destroy();this.texts=[];const D={font:"18px monospace",color:"#ffffff"},C=22;let L=20;const G=f.current;for(let q=0;q<G.length;q++){const A=this.add.text(10,L,G[q]||" ",D).setOrigin(0,0);this.texts.push(A),L+=C}}update(){let D=0;if(S!=null&&S.current&&typeof S.current.getCurrentTime=="function")try{D=S.current.getCurrentTime()||0}catch{D=0}else D=this.audioEl&&this.audioEl.currentTime||0;for(let L=0;L<this.texts.length;L++)this.texts[L].setStyle({backgroundColor:void 0,color:"#ffffff"});const C=y.current;for(const L of C)if(D>=L.start&&D<L.start+Math.max(.001,L.duration)){const G=this.texts[L.lineIndex];G&&G.setStyle({backgroundColor:"rgba(0,130,200,0.16)",color:"#00aaff"})}}}const w=((j=a.current)==null?void 0:j.clientWidth)??640,k={type:m.AUTO,parent:a.current,width:w,height:Math.round(w/2),backgroundColor:"#101010",scene:[x]};s.current=new m.Game(k)})(),()=>{u=!1,c.current=null;try{const p=s.current;p&&typeof p.destroy=="function"&&p.destroy(!0)}catch{}}},[]),o.jsx("div",{ref:a,style:{width:"100%",height:340}})}const Tc="GenericPlayer",Pc=e=>/youtu(\.be|be\.com)/i.test(e),As=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),Ec=e=>!!e&&/\.(mp3|aac|m4a|flac|wav|ogg)(\?.*)?$/i.test(e),Ac=e=>{if(!e)return null;const t=s=>e.sources.find(i=>i.kind===s),n=e.sources.find(s=>s.kind==="youtube"&&(s.videoId||s.url&&Pc(s.url)))??null;if(n)return n;const r=t("hls")||e.sources.find(s=>s.url&&As(s.url))||null;if(r)return r;const a=t("audio")||e.sources.find(s=>s.url&&Ec(s.url))||null;return a||(e.sources[0]??null)},ba=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")}`},Lc=({tracks:e=[],initialIndex:t=0,autoPlay:n=!0,countdownSeconds:r=0,height:a=360,onIndexChange:s,onPlayingChange:i,onTimeUpdate:l,externalRef:c,uiMode:d="full",compactNextCount:u=3,progressBarPosition:p="inline",loop:m=!1,onEnded:f})=>{const{t:y}=Ce(),[g,v]=h.useState(Math.min(Math.max(0,t),Math.max(0,e.length-1))),S=e[g],b=h.useMemo(()=>Ac(S),[S]),[x,w]=h.useState(!1),[k,j]=h.useState(0),[T,D]=h.useState(0),[C,L]=h.useState(.9),[G,q]=h.useState(null),A=h.useRef(null),[V,te]=h.useState(()=>Wa()),ee=h.useRef(null),W=h.useRef(null),Q=h.useRef(null),E=h.useCallback(z=>{const H=Math.min(Math.max(0,z),Math.max(0,e.length-1));v(H),s==null||s(H)},[e.length,s]),F=h.useCallback(()=>E(g+1),[g,E]),N=h.useCallback(()=>E(g-1),[g,E]),$=h.useCallback(async()=>{var z,H;await Vt(),te(!0),(b==null?void 0:b.kind)==="youtube"?(z=ee.current)==null||z.playVideo():(H=W.current)==null||H.play(),w(!0),i==null||i(!0)},[b,i]),M=h.useCallback(()=>{var z,H;(b==null?void 0:b.kind)==="youtube"?(z=ee.current)==null||z.pauseVideo():(H=W.current)==null||H.pause(),w(!1),i==null||i(!1)},[b,i]),O=h.useCallback(()=>x?M():$(),[x,$,M]),R=h.useCallback(z=>{var ne;const H=(S==null?void 0:S.startOffset)??0,ae=z+H;(b==null?void 0:b.kind)==="youtube"?(ne=ee.current)==null||ne.seekTo(ae,!0):W.current&&(W.current.currentTime=ae);const le=Math.max(0,z);D(le),l==null||l(le)},[b,l]),_=h.useCallback(z=>{var H,ae;L(z),(b==null?void 0:b.kind)==="youtube"?(ae=(H=ee.current)==null?void 0:H.setVolume)==null||ae.call(H,Math.round(z*100)):W.current&&(W.current.volume=z)},[b]);h.useImperativeHandle(c,()=>({play:$,pause:M,toggle:O,seekTo:R,setVolume:_,getUnderlyingPlayer:()=>(b==null?void 0:b.kind)==="youtube"?ee.current:(b==null?void 0:b.kind)==="hls"||(b==null?void 0:b.kind)==="audio"?W.current:null}),[$,M,O,R,_,b==null?void 0:b.kind]),h.useEffect(()=>{const z=window.setInterval(()=>{let H=0,ae=0;(b==null?void 0:b.kind)==="youtube"&&ee.current?(H=ee.current.getCurrentTime()||0,ae=ee.current.getDuration()||0):W.current&&(H=W.current.currentTime||0,ae=W.current.duration||0);const le=(S==null?void 0:S.startOffset)??0,ne=Math.max(0,H-le);D(ne),j(ae),l==null||l(ne)},250);return()=>window.clearInterval(z)},[b==null?void 0:b.kind,l]),h.useEffect(()=>()=>{A.current&&(window.clearInterval(A.current),A.current=null)},[]),h.useEffect(()=>{if(Q.current){try{Q.current.destroy()}catch{}Q.current=null}if(W.current&&(W.current.volume=C,W.current.crossOrigin=b!=null&&b.withCredentials?"use-credentials":"anonymous"),(b==null?void 0:b.kind)==="hls"&&As(b.url)){const z=W.current;if(!z)return;const H=()=>{z.src=b.url,z.load();const ae=(S==null?void 0:S.startOffset)??0;try{ae&&!isNaN(ae)&&(z.currentTime=ae)}catch{}n&&z.play().catch(()=>{})};z.canPlayType("application/vnd.apple.mpegurl")?H():(async()=>{var ae;try{const ne=(await import("hls.js")).default;if((ae=ne==null?void 0:ne.isSupported)!=null&&ae.call(ne)){const X=new ne({xhrSetup:K=>{if(b!=null&&b.withCredentials&&(K.withCredentials=!0),b!=null&&b.headers)for(const[J,oe]of Object.entries(b.headers))try{K.setRequestHeader(J,oe)}catch{}}});Q.current=X,X.loadSource(b.url),X.attachMedia(z),X.on(ne.Events.MANIFEST_PARSED,()=>{n&&z.play().catch(()=>{})})}else H()}catch(le){console.debug(Tc,"HLS.js setup failed, falling back to native playback",le),H()}})()}else if((b==null?void 0:b.kind)==="audio"&&b.url&&W.current){const z=W.current;z.src=b.url,z.load();const H=(S==null?void 0:S.startOffset)??0;try{H&&!isNaN(H)&&(z.currentTime=H)}catch{}n&&z.play().catch(()=>{})}A.current&&(window.clearInterval(A.current),A.current=null),q(null),D(0),j(0),n&&(b==null?void 0:b.kind)==="youtube"&&r>0?(q(r),A.current=window.setInterval(()=>{q(z=>{var H;if(!z)return null;if(z<=1){A.current&&(window.clearInterval(A.current),A.current=null);try{(H=ee.current)==null||H.playVideo()}catch{}return w(!0),i==null||i(!0),null}return z-1})},1e3)):w(!!n)},[b==null?void 0:b.url,b==null?void 0:b.kind,b==null?void 0:b.withCredentials,JSON.stringify(b==null?void 0:b.headers),n,C]);const I=h.useCallback(()=>{g<e.length-1?F():(w(!1),i==null||i(!1),R(0),f==null||f())},[g,e.length,F,i,R,f]),B=(b==null?void 0:b.kind)==="youtube"||d==="full"||d==="nobuttons",Z=u>0?e.slice(g+1,g+1+u):[];return o.jsxs("div",{className:"gp-player",style:{display:"grid",gap:12},children:[n&&!V&&o.jsx("div",{className:"gp-audio-activation",onClick:()=>{te(!0),$()},style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",cursor:"pointer"},children:o.jsx("span",{style:{color:"#fff",fontSize:24},children:"Click to activate audio"})}),B&&o.jsxs("div",{className:"gp-stage",style:{width:"100%",height:a,background:(b==null?void 0:b.kind)==="youtube"?"transparent":"var(--player-bg, #0f172a)",borderRadius:8,overflow:"hidden",position:"relative",display:"grid",placeItems:"center"},children:[(b==null?void 0:b.kind)==="youtube"&&o.jsx($r,{videoId:b.videoId??Dc(b.url),onReady:z=>{ee.current=z.target,_(C);const H=(S==null?void 0:S.startOffset)??0;try{H&&z.target.seekTo(H,!0)}catch{}if(d==="nobuttons"){try{z.target.playVideo()}catch{}w(!0)}},onEnd:I,opts:{width:"100%",height:"100%",playerVars:{autoplay:n||d==="nobuttons"?1:0,controls:0,modestbranding:1,rel:0,showinfo:0,fs:0,disablekb:1,iv_load_policy:3,loop:m?1:0}},style:{width:"100%",height:"100%"}}),G!==null&&o.jsx("div",{style:{position:"absolute",inset:0,zIndex:120,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.7)"},children:o.jsx("span",{style:{color:"#fff",fontSize:72,fontWeight:"bold"},children:G})}),d==="nobuttons"&&o.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"auto",zIndex:100,cursor:"default"}}),((b==null?void 0:b.kind)==="audio"||(b==null?void 0:b.kind)==="hls")&&o.jsxs(o.Fragment,{children:[d==="full"&&o.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:S!=null&&S.coverUrl?o.jsx("img",{alt:"cover",src:S.coverUrl,style:{height:a-24,objectFit:"contain"}}):o.jsxs("div",{style:{opacity:.8},children:[o.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[S==null?void 0:S.artist," � ",S==null?void 0:S.title]}),o.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(b==null?void 0:b.label)??`${(b==null?void 0:b.codec)??""} ${(b==null?void 0:b.quality)??""}`.trim()})]})}),o.jsx("audio",{ref:W,onEnded:I,onLoadedMetadata:()=>{const z=W.current;z&&j(z.duration||0)},crossOrigin:b!=null&&b.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]})]}),(d==="minimal"||d==="compact")&&o.jsx("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:o.jsxs("div",{children:[o.jsx("div",{style:{fontWeight:600},children:(S==null?void 0:S.title)??"�"}),o.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:13},children:(S==null?void 0:S.artist)??"�"})]})}),d==="full"&&o.jsxs(o.Fragment,{children:[o.jsx(Ls,{currentTime:T,duration:k}),o.jsx(Nc,{isPlaying:x,index:g,count:e.length,currentTime:T,duration:k,volume:C,onPrev:N,onNext:F,onToggle:O,onSeek:R,onVolume:_})]}),d==="progressOnly"&&o.jsx("div",{style:p==="fixedBottom"?{position:"fixed",left:0,right:0,bottom:0,padding:"8px 12px",background:"rgba(15, 23, 42, 0.9)",backdropFilter:"blur(2px)",zIndex:1e3}:{},children:o.jsx(Ic,{currentTime:T,duration:k,onSeek:R})}),(d==="minimal"||d==="compact")&&o.jsx(Fc,{isPlaying:x,canPrev:g>0,canNext:g<e.length-1,onPrev:N,onNext:F,onToggle:O}),d==="compact"&&Z.length>0&&o.jsx(Oc,{items:Z,onPick:z=>E(g+1+z)}),d==="nobuttons"&&o.jsx(o.Fragment,{}),d==="full"&&e.length>0&&o.jsx("div",{className:"gp-list",style:{display:"grid",gap:4},children:e.map((z,H)=>o.jsxs("button",{onClick:()=>E(H),style:{textAlign:"left",border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:"8px 10px",background:H===g?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",cursor:"pointer"},title:z.sources.map(ae=>ae.kind).join(", "),children:[o.jsx("div",{style:{fontWeight:600},children:z.title}),o.jsx("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:z.artist})]},z.id))})]})},Wt={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},Ls=({currentTime:e,duration:t})=>o.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[o.jsx("div",{}),o.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[ba(e)," / ",ba(t)]})]}),Nc=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:s,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:u})=>{const{t:p}=Ce();return o.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[o.jsxs("div",{style:{display:"flex",gap:8},children:[o.jsx("button",{onClick:i,disabled:t<=0,title:p("player.previousTrack"),"aria-label":p("player.previousTrack"),style:Wt,children:"?"}),o.jsx("button",{onClick:c,title:p(e?"player.pause":"player.play"),"aria-label":p(e?"player.pause":"player.play"),style:Wt,children:"?"}),o.jsx("button",{onClick:l,disabled:t>=n-1,title:p("player.nextTrack"),"aria-label":p("player.nextTrack"),style:Wt,children:"?"})]}),o.jsx("input",{type:"range",min:0,max:Math.max(1,a),step:.1,value:r,onChange:m=>d(parseFloat(m.target.value)),"aria-label":"Seek position"}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{children:"??"}),o.jsx("input",{type:"range",min:0,max:1,step:.01,value:s,onChange:m=>u(parseFloat(m.target.value)),"aria-label":"Volume"})]})]})},Ic=({currentTime:e,duration:t,onSeek:n})=>o.jsxs(o.Fragment,{children:[o.jsx(Ls,{currentTime:e,duration:t}),o.jsx("input",{type:"range",min:0,max:Math.max(1,t),step:.1,value:e,onChange:r=>n(parseFloat(r.target.value)),"aria-label":"Seek position"})]}),Fc=({isPlaying:e,canPrev:t,canNext:n,onPrev:r,onNext:a,onToggle:s})=>{const{t:i}=Ce();return o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("button",{onClick:r,disabled:!t,title:i("player.previousTrack"),"aria-label":i("player.previousTrack"),style:Wt,children:"?"}),o.jsx("button",{onClick:s,title:i(e?"player.pause":"player.play"),"aria-label":i(e?"player.pause":"player.play"),style:Wt,children:"?"}),o.jsx("button",{onClick:a,disabled:!n,title:i("player.nextTrack"),"aria-label":i("player.nextTrack"),style:Wt,children:"?"})]})},Oc=({items:e,onPick:t})=>{const{t:n}=Ce();return o.jsxs("div",{style:{border:"1px solid var(--border-light, #e5e7eb)",borderRadius:8,padding:10,background:"var(--bg, #fff)"},children:[o.jsx("div",{style:{fontWeight:600,marginBottom:6},children:n("player.upNext")}),o.jsx("ol",{style:{margin:0,paddingLeft:18},children:e.map((r,a)=>o.jsx("li",{style:{marginBottom:4},children:o.jsxs("button",{type:"button",onClick:()=>t(a),style:{border:"none",padding:0,background:"transparent",cursor:"pointer",color:"var(--text, #111827)"},title:r.sources.map(s=>s.kind).join(", "),children:[o.jsx("span",{style:{fontWeight:600},children:r.artist})," � ",r.title]})},r.id))})]})};function Dc(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]}const Gc=e=>!!e&&/\.m3u8(\?.*)?$/i.test(e),va=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")}`},rr={border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",background:"#fff",cursor:"pointer"},_c=({isPlaying:e,index:t,count:n,currentTime:r,duration:a,volume:s,onPrev:i,onNext:l,onToggle:c,onSeek:d,onVolume:u})=>{const{t:p}=Ce();return o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,justifyContent:"space-between"},children:[o.jsx("div",{}),o.jsxs("div",{style:{fontSize:12,color:"#64748b"},children:[va(r)," / ",va(a)]})]}),o.jsxs("div",{className:"gp-controls",style:{display:"grid",gridTemplateColumns:"auto 1fr auto",gap:12,alignItems:"center"},children:[o.jsxs("div",{style:{display:"flex",gap:8},children:[o.jsx("button",{onClick:i,disabled:t<=0,title:p("playerControls.prev","Prev"),"aria-label":p("playerControls.previousTrack","Previous track"),style:rr,children:"⏮"}),o.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:rr,children:e?"⏸":"▶"}),o.jsx("button",{onClick:l,disabled:t>=n-1,title:p("playerControls.next","Next"),"aria-label":p("playerControls.nextTrack","Next track"),style:rr,children:"⏭"})]}),o.jsx("input",{type:"range",min:0,max:Math.max(1,a),step:.1,value:r,"aria-label":p("playerControls.seekPosition","Seek position"),onChange:m=>d(parseFloat(m.target.value))}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{children:"🔊"}),o.jsx("input",{type:"range",min:0,max:1,step:.01,value:s,"aria-label":p("playerControls.volume","Volume"),onChange:m=>u(parseFloat(m.target.value))})]})]})]})},Bc=h.memo(_c);function zc(e,t){const[n,r]=h.useState(()=>{try{const a=localStorage.getItem(e);return a?JSON.parse(a):t}catch{return t}});return h.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,r]}const Wc=({active:e,onClick:t,title:n,children:r})=>o.jsx("button",{type:"button",onClick:t,title:n,"aria-pressed":e,style:{padding:"4px 8px",borderRadius:6,fontSize:12,border:`1px solid ${e?"#6366f1":"#334155"}`,background:e?"rgba(99,102,241,.12)":"rgba(15,23,42,.6)",color:e?"#e2e8f0":"#cbd5e1",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.2},children:r}),Ns=({modes:e,active:t,setActive:n,rows:r=2})=>{const a=Math.max(1,r);return o.jsx("div",{style:{position:"absolute",top:10,right:10,pointerEvents:"auto",zIndex:9999},children:o.jsx("div",{style:{display:"grid",gridAutoFlow:"column",gridTemplateRows:`repeat(${a}, auto)`,gridAutoColumns:"max-content",gap:6,background:"rgba(2,6,23,.5)",padding:6,borderRadius:10,border:"1px solid #334155",backdropFilter:"blur(2px)",justifyItems:"end",alignItems:"start"},children:e.map(s=>o.jsx(Wc,{active:t===s,onClick:()=>n(s),title:`Tryb: ${s}`,children:s},s))})})},Uc=({vu:e,hide:t})=>{if(t)return null;const n=12,r=Math.round(e*n);return o.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"rgba(2,6,23,.5)",padding:"6px 8px",borderRadius:8,border:"1px solid #334155",backdropFilter:"blur(2px)",pointerEvents:"none",zIndex:9998},children:Array.from({length:n}).map((a,s)=>{const i=120*(s/n);return o.jsx("div",{style:{width:6,height:18,borderRadius:2,background:s<r?`hsl(${i}, 80%, 50%)`:"#1f2937"}},s)})})},qc="#94a3b8",Vc=({height:e,coverUrl:t,title:n,subtitle:r,label:a})=>o.jsx("div",{style:{textAlign:"center",color:"#e2e8f0"},children:t?o.jsx("img",{alt:"cover",src:t,style:{height:e-24,objectFit:"contain"}}):o.jsxs("div",{style:{opacity:.8},children:[o.jsx("div",{style:{fontSize:18,fontWeight:600},children:n??"—"}),o.jsx("div",{style:{marginTop:8,fontSize:12,color:qc},children:a??r??"—"})]})});function Kc(e,t,n,r,a){const s=Math.min(r.length,256),i=Math.max(1,Math.floor(r.length/s)),l=t/s;for(let c=0;c<s;c++){const d=r[c*i]/255,u=d*(n-6),p=c*l,m=n-u,f=c/s*240+a;e.fillStyle=`hsl(${f%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(p+1,m,l-2,u)}}function Hc(e,t,n,r,a){const i=Math.max(1,Math.floor(r.length/48)),l=t/48;for(let c=0;c<48;c++){const d=r[c*i]/255,u=d*(n-6),p=c*l,m=n-u,f=c/48*240+a;e.fillStyle=`hsl(${f%360}, 80%, ${Math.max(30,40+d*30)}%)`,e.fillRect(p+1,m,l-2,u)}}function Yc(e,t,n,r){e.lineWidth=2,e.strokeStyle="#c7d2fe",e.beginPath();const a=t/r.length;for(let s=0;s<r.length;s++){const i=(r[s]-128)/128,l=s*a,c=n/2+i*(n*.45);s===0?e.moveTo(l,c):e.lineTo(l,c)}e.stroke()}function Zc(e,t,n,r,a){const l=t/12,c=n/6;for(let d=0;d<6;d++)for(let u=0;u<12;u++){const p=(d*12+u)%r.length,m=r[p]/255,f=(a+u/12*180+d/6*90)%360,y=70+m*25,g=25+m*35;e.fillStyle=`hsl(${f}, ${y}%, ${g}%)`,e.fillRect(u*l,d*c,Math.ceil(l),Math.ceil(c))}}function Xc(e,t,n,r,a){const i=Math.max(1,Math.floor(r.length/96)),l=t/2,c=n/2,d=Math.min(t,n)*.22,u=Math.min(t,n)*.48;for(let p=0;p<96;p++){const m=r[p*i]/255,f=p/96*Math.PI*2,y=d,g=d+m*(u-d),v=l+Math.cos(f)*y,S=c+Math.sin(f)*y,b=l+Math.cos(f)*g,x=c+Math.sin(f)*g;e.strokeStyle=`hsl(${p/96*360+a},85%,60%)`,e.lineWidth=3,e.beginPath(),e.moveTo(v,S),e.lineTo(b,x),e.stroke()}e.fillStyle="rgba(255,255,255,0.08)",e.beginPath(),e.arc(l,c,d*.85,0,Math.PI*2),e.fill()}function Jc(e,t,n,r,a,s){const i=t/2,l=n/2,c=Math.min(t,n)*.5,d=xa(r,0,Math.floor(r.length*.1))/255,u=xa(r,Math.floor(r.length*.6),r.length)/255;s.current+=.01+u*.03;const p=24;for(let m=0;m<p;m++){const f=s.current+m/p*Math.PI*2,y=(.35+d*.55)*c,g=i+Math.cos(f)*y,v=l+Math.sin(f)*y,S=e.createRadialGradient(i,l,0,i,l,y),b=m/p*360+a;S.addColorStop(0,`hsla(${b},85%,65%,0.0)`),S.addColorStop(1,`hsla(${b},85%,65%,0.9)`),e.strokeStyle=S,e.lineWidth=6+u*8,e.beginPath(),e.moveTo(i,l),e.lineTo(g,v),e.stroke()}e.fillStyle="rgba(2,6,23,0.25)",e.fillRect(0,0,t,n)}function xa(e,t,n){let r=0,a=0;for(let s=t;s<n;s++)r+=e[s],a++;return a?r/a:0}function Qc(e,t,n,r,a,s){const i=t/2,l=n/2,c=2+Math.floor(r*14);for(let u=0;u<c;u++){const p=Math.random()*Math.PI*2,m=.5+Math.random()*(2.5+r*4);s.current.push({x:i,y:l,vx:Math.cos(p)*m,vy:Math.sin(p)*m,life:0,max:40+Math.random()*60,hue:(a+Math.random()*60)%360})}e.fillStyle="rgba(2,6,23,0.2)",e.fillRect(0,0,t,n);const d=s.current;for(let u=d.length-1;u>=0;u--){const p=d[u];p.x+=p.vx,p.y+=p.vy,p.life+=1;const m=1-p.life/p.max;e.fillStyle=`hsla(${p.hue},85%,60%,${Math.max(0,m)})`,e.beginPath(),e.arc(p.x,p.y,2+m*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)&&d.splice(u,1)}d.length>1200&&d.splice(0,d.length-1200)}function ed(e,t,n,r,a,s){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.12;for(let u=0;u<c;u++){const p=Math.floor(u/c*r.length),m=r[p]/255,f=d+u*d*.55+m*d*.5,y=(s+u*40)%360;e.lineWidth=3+m*6,e.strokeStyle=`hsla(${y},80%,60%,${.5+.5*a})`,e.beginPath(),e.arc(i,l,f,0,Math.PI*2),e.stroke()}}function td(e,t,n,r,a){const l=t/14,c=n/8;for(let d=0;d<8;d++)for(let u=0;u<14;u++){const p=Math.min(r.length-1,d*14+u),m=r[p]/255,f=(a+u/14*210+d/8*90)%360,y=65+m*30,g=20+m*40,v=(1-m)*4;e.fillStyle=`hsl(${f}, ${y}%, ${g}%)`,e.fillRect(u*l+v,d*c+v,Math.max(1,l-2*v),Math.max(1,c-2*v))}}function nd(e){const n=Array.from(new Set(e.filter(Boolean))).map(r=>new Promise(a=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>a(s),s.onerror=()=>a(s),s.src=r}));return Promise.all(n)}async function rd(e,t,n,r,a){e.current||(e.current={sprites:[],loadedUrls:[],ready:!1});const s=e.current,i=t.join("|")!==s.loadedUrls.join("|");if(!s.ready||i){const l=await nd(t.length?t:[]);s.loadedUrls=t,s.sprites=[],s.ready=!0;const c=d=>l[d%Math.max(1,l.length)]??new Image;for(let d=0;d<n;d++){const u=Math.random()*Math.min(r,a)*.38+40;s.sprites.push({img:c(d),x:(Math.random()-.5)*u*.4,y:(Math.random()-.5)*u*.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 ad(e,t,n,r,a,s,i,l){const c=s.current;if(!(c!=null&&c.ready))return;const d=t/2,u=n/2,p=900,m=1+r*2;for(const y of c.sprites){y.ang+=y.spin*m,y.z-=y.vz*(.8+r*2.4),y.z<40&&(y.z=p);const g=Math.min(t,n)*.32+Math.sin(y.ang*.8)*18;y.x=Math.cos(y.ang)*g,y.y=Math.sin(y.ang*1.1)*g*.6}const f=[...c.sprites].sort((y,g)=>g.z-y.z);for(const y of f){const g=p/(p-y.z)*.6*y.size,v=d+y.x*g,S=u+y.y*g,b=64*g,x=64*g;e.save(),e.globalAlpha=.12+(1-y.z/p)*.2,e.fillStyle=`hsl(${(a+(1-y.z/p)*60)%360}, 90%, 60%)`,e.beginPath(),e.ellipse(v,S,b*.7,x*.7,0,0,Math.PI*2),e.fill(),e.restore(),y.img&&y.img.width?e.drawImage(y.img,v-b/2,S-x/2,b,x):(e.save(),e.fillStyle=`hsl(${(a+180)%360}, 40%, 55%)`,e.fillRect(v-b/2,S-x/2,b,x),e.restore())}}function sd(e,t,n,r,a,s){s.current||(s.current={items:[]});const i=s.current;Math.random()<.06+r*.25&&i.items.push({x:Math.random()*t,y:Math.random()*n,r:8+Math.random()*24,life:1,hue:(a+Math.random()*120)%360});const l=[];for(const c of i.items){c.r+=2+r*14,c.life*=.975-r*.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()}i.items=l}function od(e,t,n,r){e.current||(e.current={stars:[],ready:!1});const a=e.current;if(!a.ready||a.stars.length!==t){const s=[];for(let i=0;i<t;i++){const l={x:(Math.random()-.5)*n,y:(Math.random()-.5)*r,z:Math.random()*800+100,pz:0};s.push(l)}a.stars=s,a.ready=!0}}function id(e,t,n,r,a,s){const i=s.current,l=t/2,c=n/2,d=4+r*18;e.save(),e.translate(l,c);for(const u of i.stars){u.z-=d,u.z<20&&(u.x=(Math.random()-.5)*t,u.y=(Math.random()-.5)*n,u.z=900,u.pz=u.z);const p=u.x/u.z*600,m=u.y/u.z*600,f=u.x/u.pz*600,y=u.y/u.pz*600;u.pz=u.z,e.strokeStyle=`hsla(${(a+200)%360}, 90%, 70%, 0.7)`,e.lineWidth=Math.max(1,(1-u.z/900)*2),e.beginPath(),e.moveTo(f,y),e.lineTo(p,m),e.stroke()}e.restore()}function ld(e,t,n,r,a,s){const i=t/2,l=n/2,c=5,d=Math.min(t,n)*.42;s.current+=.01;for(let u=0;u<c;u++){const p=(u+1)/(c+1),m=p*d;e.strokeStyle=`hsla(${(a+u*30)%360}, 70%, 45%, 0.35)`,e.lineWidth=1,e.beginPath(),e.arc(i,l,m,0,Math.PI*2),e.stroke();const f=Math.floor(r.length*p|0),y=(r[f]??0)/255,g=6+u*2;for(let v=0;v<g;v++){const S=s.current*(1+u*.15)+v/g*Math.PI*2,b=m+Math.sin(S*2)*6*y,x=i+Math.cos(S)*b,w=l+Math.sin(S)*b;e.fillStyle=`hsla(${(a+u*30+v*6)%360}, 90%, ${55+y*30}%, ${.6+y*.3})`,e.beginPath(),e.arc(x,w,2+y*4,0,Math.PI*2),e.fill()}}}function cd(e,t,n,r,a){const s=t/2,i=n/2,l=Math.min(t,n)*.28,c=96,d=Math.max(1,Math.floor(r.length/c));for(let u=0;u<c;u++){const p=(r[u*d]??0)/255,m=u/c*Math.PI*2,f=p*(Math.min(t,n)*.22)+6,y=s+Math.cos(m)*l,g=i+Math.sin(m)*l,v=s+Math.cos(m)*(l+f),S=i+Math.sin(m)*(l+f);e.strokeStyle=`hsl(${(a+u*3)%360}, 90%, ${40+p*40}%)`,e.lineWidth=3,e.beginPath(),e.moveTo(y,g),e.lineTo(v,S),e.stroke()}e.fillStyle=`hsla(${(a+180)%360}, 60%, 15%, .4)`,e.beginPath(),e.arc(s,i,l-8,0,Math.PI*2),e.fill()}function dd(e,t,n,r,a,s){s.current||(s.current={tris:[]});const i=s.current,l=6;for(;i.tris.length<l;)i.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,d=n/2;for(const u of i.tris){u.a+=.002+r*.02*(u.dr>0?1:-1),u.r+=Math.sin(u.a*2)*(.3+r*1.4);const p=Math.max(40,Math.min(u.r,Math.min(t,n)*.48));e.save(),e.translate(c,d),e.rotate(u.a),e.strokeStyle=`hsla(${(a+p*.2)%360}, 90%, 60%, .9)`,e.lineWidth=2.5,e.beginPath(),e.moveTo(p,0);for(let m=1;m<3;m++){const f=m*Math.PI*2/3;e.lineTo(Math.cos(f)*p,Math.sin(f)*p)}e.closePath(),e.shadowBlur=12,e.shadowColor=e.strokeStyle,e.stroke(),e.restore()}}function ud(e,t,n,r,a,s){if(!s.current){const p=[];for(let f=0;f<24;f++)p.push({ang:f/24*Math.PI*2,phase:Math.random()*Math.PI*2,baseR:Math.min(t,n)*.22+Math.random()*30});s.current={nodes:p}}const i=s.current,l=t/2,c=n/2,d=26+r*80,u=[];for(const p of i.nodes){p.phase+=.02+r*.06;const m=p.baseR+Math.sin(p.phase)*d,f=l+Math.cos(p.ang)*m,y=c+Math.sin(p.ang)*m;u.push([f,y])}e.fillStyle=`hsla(${a}, 70%, 55%, .22)`,e.strokeStyle=`hsla(${(a+40)%360}, 90%, 65%, .9)`,e.lineWidth=2,e.beginPath();for(let p=0;p<u.length;p++){const[m,f]=u[p],[y,g]=u[(p+1)%u.length],v=(m+y)/2,S=(f+g)/2;p===0?e.moveTo(v,S):e.quadraticCurveTo(m,f,v,S)}e.closePath(),e.fill(),e.stroke()}function hd(e,t,n,r,a,s){e.fillStyle="rgba(10,16,28,0.25)",e.fillRect(0,0,t,n);const i=t/2,l=n/2,c=Math.min(t,n)*(.38+a*.12),d=e.createRadialGradient(i,l,c*.1,i,l,c);d.addColorStop(0,`hsla(${(s+200)%360},90%,70%,0.95)`),d.addColorStop(.5,`hsla(${(s+260)%360},80%,55%,0.6)`),d.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=d,e.beginPath(),e.arc(i,l,c,0,Math.PI*2),e.fill();const u=18+Math.floor(a*50);for(let p=0;p<u;p++){const m=p/u*Math.PI*2+r*(.6+a*1.4),f=(Math.sin(r*2+p*1.7)+Math.cos(r*1.3+p*2.1))*.15,y=c*(.4+.55*Math.abs(Math.sin(r*1.2+p))),g=6;e.save(),e.translate(i,l),e.rotate(m+f),e.beginPath(),e.moveTo(0,0);for(let S=1;S<=g;S++){const b=y/g*S,x=(Math.sin(r*3+p*.8+S)*.6+Math.cos(r*2+p+S*.7))*(8+24*a),w=b,k=x;e.lineTo(k,w)}e.globalCompositeOperation="lighter";const v=(s+p*(240/u))%360;e.strokeStyle=`hsla(${v}, 90%, ${60+a*20}%, ${.35+a*.4})`,e.lineWidth=2+a*2,e.stroke(),e.restore()}e.beginPath(),e.arc(i,l,c*(.98+.02*Math.sin(r*2)),0,Math.PI*2),e.strokeStyle=`hsla(${(s+40)%360},90%,70%,${.25+a*.25})`,e.lineWidth=1.5,e.stroke(),e.globalCompositeOperation="source-over"}function Zt(e,t){return e+Math.random()*(t-e)}function fd(e,t,n,r,a,s){s.current||(s.current={blobs:Array.from({length:7},(d,u)=>({x:Zt(t*.2,t*.8),y:Zt(n*.2,n*.8),r:Zt(Math.min(t,n)*.05,Math.min(t,n)*.12),vx:Zt(-.6,.6),vy:Zt(-.6,.6),hue:(a+u*10)%360}))});const i=s.current,l=.6+r*2.2;e.save(),e.globalCompositeOperation="lighter";for(const c of i.blobs){c.x+=c.vx*l,c.y+=c.vy*l,c.vy-=.01-r*.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 d=(c.hue+r*120)%360,u=e.createRadialGradient(c.x,c.y,c.r*.2,c.x,c.y,c.r);u.addColorStop(0,`hsla(${d}, 95%, 70%, .8)`),u.addColorStop(1,`hsla(${(d+40)%360}, 90%, 30%, 0)`),e.fillStyle=u,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="rgba(255,255,255,.06)",e.lineWidth=2,e.strokeRect(1,1,t-2,n-2)}function jt(e,t){return e+Math.random()*(t-e)}function pd(e,t,n,r,a,s,i){i.current||(i.current={embers:[],t:0});const l=i.current,c=e.createLinearGradient(0,n,0,n*.4);c.addColorStop(0,`hsla(${(s+30)%360}, 90%, 50%, .35)`),c.addColorStop(1,`hsla(${(s+10)%360}, 90%, 50%, 0)`),e.fillStyle=c,e.fillRect(0,0,t,n);const d=6;for(let p=0;p<d;p++){const m=(p+.5)/d*t,f=(r[Math.floor((p+1)/(d+1)*r.length)]||0)/255,y=n*.18+(.25+a*.6+f*.7)*n*.55,g=e.createLinearGradient(m,n,m,n-y);g.addColorStop(0,`hsla(${(s+40)%360},100%,55%,.9)`),g.addColorStop(.5,`hsla(${(s+10)%360},100%,60%,.75)`),g.addColorStop(1,`hsla(${(s-20)%360},100%,80%,.05)`);const v=Math.sin(l.t*1.2+p*.8)*(15+a*30);e.fillStyle=g,e.beginPath(),e.moveTo(m-20,n),e.bezierCurveTo(m-35,n-y*.45,m-25+v,n-y*.75,m+v,n-y),e.bezierCurveTo(m+25+v*.3,n-y*.65,m+35,n-y*.35,m+20,n),e.closePath(),e.fill()}const u=Math.floor(1+a*6);for(let p=0;p<u;p++)l.embers.push({x:jt(t*.25,t*.75),y:n-jt(4,14),r:jt(1,3),vx:jt(-.15,.15),vy:-jt(.6,1.8)-a*1.2,life:jt(.8,1.6)});e.save(),e.globalCompositeOperation="lighter";for(let p=l.embers.length-1;p>=0;p--){const m=l.embers[p];if(m.x+=m.vx,m.y+=m.vy,m.vy-=.01,m.life-=.015+a*.02,m.life<=0||m.y<-10){l.embers.splice(p,1);continue}const f=e.createRadialGradient(m.x,m.y,0,m.x,m.y,m.r*3);f.addColorStop(0,`hsla(${(s+25)%360},100%,65%,.9)`),f.addColorStop(1,`hsla(${(s+25)%360},100%,65%,0)`),e.fillStyle=f,e.beginPath(),e.arc(m.x,m.y,m.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+a*.08}function md(e,t,n,r,a,s){e.fillStyle="rgba(10,16,28,0.35)",e.fillRect(0,0,t,n);const i=n/2,l=Math.max(8,18-a*10),c=n*.35*(.6+a*.7),d=r.length,u=t/(d-1);e.beginPath();for(let f=0;f<d;f++){const y=(r[f]-128)/128,g=Math.sin(s*1.5+f*.03)*.12,v=f*u,S=i-l-(y+g)*c;f===0?e.moveTo(v,S):e.lineTo(v,S)}const p=e.createLinearGradient(0,0,0,i-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 f=0;f<d;f++){const y=(r[f]-128)/128,g=Math.cos(s*1.3+f*.035)*.12,v=f*u,S=i+l+(y+g)*c;f===0?e.moveTo(v,S):e.lineTo(v,S)}const m=e.createLinearGradient(0,i+l,0,n);m.addColorStop(0,"hsla(190,90%,65%,0.9)"),m.addColorStop(1,"hsla(160,85%,55%,0.4)"),e.strokeStyle=m,e.lineWidth=2,e.stroke(),e.globalCompositeOperation="lighter",e.strokeStyle="rgba(255,255,255,0.08)",e.lineWidth=6,e.beginPath(),e.moveTo(0,i-l),e.lineTo(t,i-l),e.stroke(),e.beginPath(),e.moveTo(0,i+l),e.lineTo(t,i+l),e.stroke(),e.globalCompositeOperation="source-over"}const gd="var(--player-bg, #0f172a)",Is=({kind:e,audioRef:t,width:n="100%",height:r=360,coverUrl:a,title:s,subtitle:i,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:u,imageUrls:p,imageCount:m=14})=>{const f=h.useMemo(()=>u!=null&&u.length?u: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,u]),y=h.useMemo(()=>{const F=f.includes(c)?c:f[0];try{const N=localStorage.getItem(d);if(!N)return F;const $=JSON.parse(N);return f.includes($)?$:F}catch{return F}},[f,c,d]),[g,v]=zc(d,y),S=h.useRef(null),b=h.useRef(null),x=h.useRef(null),w=h.useRef(null),k=h.useRef(null),j=h.useRef(null),T=h.useRef(0),D=h.useRef(0),C=h.useRef([]),[L,G]=h.useState(0),q=h.useRef(null),A=h.useRef(null),V=h.useRef(null),te=h.useRef(null),ee=h.useRef(null),W=h.useRef(null),Q=h.useRef(null),E=g!=="cover"&&g!=="video";return h.useEffect(()=>{var _;if(e==="youtube"||(b.current&&(cancelAnimationFrame(b.current),b.current=null),!E))return;Vt();const F=qt(),N=t.current;if(!N)return;if(!x.current)try{x.current=F.createMediaElementSource(N)}catch{}if(!w.current){const I=F.createAnalyser();I.fftSize=2048,I.smoothingTimeConstant=.85,w.current=I;try{(_=x.current)==null||_.connect(I)}catch{}try{I.connect(F.destination)}catch{}}const $=w.current;k.current=new Uint8Array($.frequencyBinCount),j.current=new Uint8Array($.fftSize);const M=()=>{const I=S.current,B=Math.max(1,Math.floor(window.devicePixelRatio||1));I.width=Math.floor(I.clientWidth*B),I.height=Math.floor(I.clientHeight*B);const Z=I.getContext("2d");Z==null||Z.setTransform(1,0,0,1,0,0),Z==null||Z.scale(B,B)};M();const O=()=>M();window.addEventListener("resize",O),od(V,220,S.current.width,S.current.height);const R=async()=>{const I=S.current;if(!I)return;const B=I.getContext("2d");if(!B)return;const Z=Math.max(1,Math.floor(window.devicePixelRatio||1)),z=I.width/Z,H=I.height/Z,ae=performance.now()*.001,le=g==="waveform"||g==="rift";le?$.getByteTimeDomainData(j.current):$.getByteFrequencyData(k.current);let ne=0;const X=le?j.current:k.current;for(let K=0;K<X.length;K++){const J=le?(X[K]-128)/128:X[K]/255;ne+=J*J}if(ne=Math.sqrt(ne/X.length),G(Math.min(1,ne)),B.clearRect(0,0,z,H),g==="spectrum")Kc(B,z,H,k.current,T.current);else if(g==="bars")Hc(B,z,H,k.current,T.current);else if(g==="waveform")Yc(B,z,H,j.current);else if(g==="palette"){const K=(T.current+ne*120)%360;Zc(B,z,H,k.current,K)}else if(g==="radial")Xc(B,z,H,k.current,T.current);else if(g==="rays")Jc(B,z,H,k.current,T.current,D);else if(g==="particles")Qc(B,z,H,ne,T.current,C);else if(g==="rings")ed(B,z,H,k.current,ne,T.current);else if(g==="grid"){const K=(T.current+ne*160)%360;td(B,z,H,k.current,K)}else if(g==="imageTornado"){const K=p!=null&&p.length?p:a?[a]:[];await rd(q,K,m,z,H);const J=(T.current+ne*100)%360;ad(B,z,H,ne,J,q)}else if(g==="colorRipples"){const K=(T.current+ne*120)%360;sd(B,z,H,ne,K,A)}else if(g==="starfield"){const K=(T.current+60)%360;id(B,z,H,ne,K,V)}else if(g==="orbitals"){const K=(T.current+ne*180)%360;ld(B,z,H,k.current,K,D)}else if(g==="eqcircle"){const K=(T.current+120)%360;cd(B,z,H,k.current,K)}else if(g==="triangles"){const K=(T.current+40)%360;dd(B,z,H,ne,K,te)}else if(g==="blob"){const K=(T.current+90)%360;ud(B,z,H,ne,K,ee)}else if(g==="plasma"){const K=(T.current+ne*200)%360;hd(B,z,H,ae,ne,K)}else if(g==="rift")md(B,z,H,j.current,ne,ae);else if(g==="lavaLamp"){const K=(T.current+ne*80)%360;fd(B,z,H,ne,K,W)}else if(g==="cozyFire"){const K=(T.current+ne*140)%360;pd(B,z,H,k.current,ne,K,Q)}T.current=(T.current+.4)%360,b.current=requestAnimationFrame(R)};return b.current=requestAnimationFrame(R),()=>{window.removeEventListener("resize",O),b.current&&cancelAnimationFrame(b.current)}},[E,e,t,g,p,m,a]),o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none",background:g==="cover"?"transparent":gd},children:g==="cover"?o.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:o.jsx(Vc,{height:r,coverUrl:a,title:s,subtitle:i,label:l})}):o.jsx("canvas",{ref:S,style:{width:typeof n=="number"?`${n}px`:n,height:r,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),o.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o.jsx(Ns,{modes:f,active:g,setActive:v,rows:2}),o.jsx(Uc,{vu:L,hide:e==="youtube"})]})]})},yd=({height:e,autoPlay:t,track:n,source:r,ytRef:a,audioRef:s,hlsRef:i,setVol:l,onEnd:c,volume:d,extractVideoId:u})=>{h.useEffect(()=>{const y=s.current;if(y){if(y.volume=d,y.crossOrigin=r!=null&&r.withCredentials?"use-credentials":"anonymous",(r==null?void 0:r.kind)==="hls"&&Gc(r.url)){const g=()=>{y.src=r.url,y.load(),t&&y.play().catch(()=>{})};if(y.canPlayType("application/vnd.apple.mpegurl")){g();return}(async()=>{const S=(await import("hls.js")).default;if(S.isSupported()){const b=new S({xhrSetup:x=>{if(r!=null&&r.withCredentials&&(x.withCredentials=!0),r!=null&&r.headers)for(const[w,k]of Object.entries(r.headers))x.setRequestHeader(w,String(k))}});i.current=b,b.loadSource(r.url),b.attachMedia(y),b.on(S.Events.MANIFEST_PARSED,()=>t&&y.play().catch(()=>{}))}else g()})()}(r==null?void 0:r.kind)==="audio"&&r.url&&(y.src=r.url,y.load(),t&&y.play().catch(()=>{}))}},[r==null?void 0:r.url,r==null?void 0:r.kind,r==null?void 0:r.withCredentials,d,t]);const p=(r==null?void 0:r.kind)==="youtube",m=p?"video":"cover",f=`gp-stage:mode:${(r==null?void 0:r.kind)??"none"}`;return o.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:[(r==null?void 0:r.kind)==="youtube"&&o.jsx($r,{videoId:r.videoId??u(r.url),onReady:y=>{a.current=y.target,l(d),t&&y.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%"}}),((r==null?void 0:r.kind)==="audio"||(r==null?void 0:r.kind)==="hls")&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{textAlign:"center",color:"var(--text, #e2e8f0)"},children:n!=null&&n.coverUrl?o.jsx("img",{alt:"cover",src:n.coverUrl,style:{height:e-24,objectFit:"contain"}}):o.jsxs("div",{style:{opacity:.8},children:[o.jsxs("div",{style:{fontSize:18,fontWeight:600},children:[n==null?void 0:n.artist," — ",n==null?void 0:n.title]}),o.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-dim, #94a3b8)"},children:(r==null?void 0:r.label)??`${(r==null?void 0:r.codec)??""} ${(r==null?void 0:r.quality)??""}`.trim()})]})}),o.jsx("audio",{ref:s,onEnded:c,onLoadedMetadata:()=>{},crossOrigin:r!=null&&r.withCredentials?"use-credentials":"anonymous",style:{display:"none"}})]}),o.jsx(Is,{kind:(r==null?void 0:r.kind)==="hls"?"hls":(r==null?void 0:r.kind)??"audio",audioRef:s,hlsRef:i,height:e,coverUrl:n==null?void 0:n.coverUrl,title:n==null?void 0:n.title,subtitle:n==null?void 0:n.artist,label:(r==null?void 0:r.label)??`${(r==null?void 0:r.codec)??""} ${(r==null?void 0:r.quality)??""}`.trim(),defaultMode:m,storageKey:f},`vis-${f}`)]})};function bd(e,t){const[n,r]=h.useState(()=>{try{const a=localStorage.getItem(e);return a?JSON.parse(a):t}catch{return t}});return h.useEffect(()=>{try{localStorage.setItem(e,JSON.stringify(n))}catch{}},[e,n]),[n,r]}const vd="var(--text-dim, #94a3b8)",xd=({active:e,onClick:t,title:n,children:r})=>o.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:r}),Sd=({kind:e,audioRef:t,width:n="100%",height:r=360,coverUrl:a,title:s,subtitle:i,label:l,defaultMode:c="cover",storageKey:d="gp-stage:mode",allowedModes:u,overlayOnly:p=!1})=>{const m=h.useMemo(()=>u!=null&&u.length?u:e==="youtube"?["video","cover"]:["cover","spectrum","bars","waveform","palette"],[e,u]),f=h.useMemo(()=>{const q=m.includes(c)?c:m[0];try{const A=localStorage.getItem(d);if(!A)return q;const V=JSON.parse(A);return m.includes(V)?V:q}catch{return q}},[m,c,d]),[y,g]=bd(d,f),v=h.useRef(null),[S,b]=h.useState(0),x=h.useRef(null),w=h.useRef(null),k=h.useRef(null),j=h.useRef(null),T=h.useRef(null),D=h.useRef(0),C=y==="spectrum"||y==="bars"||y==="waveform"||y==="palette";h.useEffect(()=>{var W;if(e==="youtube")return;if(!C){x.current&&cancelAnimationFrame(x.current);return}Vt();const q=qt(),A=t.current;if(!A)return;if(!w.current)try{w.current=q.createMediaElementSource(A)}catch{}if(!k.current){const Q=q.createAnalyser();Q.fftSize=2048,Q.smoothingTimeConstant=.85,k.current=Q;try{(W=w.current)==null||W.connect(Q)}catch{}try{Q.connect(q.destination)}catch{}}const V=k.current;j.current=new Uint8Array(V.frequencyBinCount),T.current=new Uint8Array(V.fftSize);const te=()=>{if(!v.current)return;const Q=v.current,E=Q.getContext("2d");if(!E)return;const F=Q.width,N=Q.height;E.clearRect(0,0,F,N),y==="waveform"?V.getByteTimeDomainData(T.current):V.getByteFrequencyData(j.current);let $=0;const M=y==="waveform"?T.current:j.current;for(let O=0;O<M.length;O++){const R=y==="waveform"?(M[O]-128)/128:M[O]/255;$+=R*R}if($=Math.sqrt($/M.length),b(Math.min(1,$)),y==="spectrum"||y==="bars"){const O=j.current,R=y==="bars"?48:Math.min(O.length,256),_=Math.floor(O.length/R),I=F/R;for(let B=0;B<R;B++){const Z=O[B*_]/255,z=Z*(N-6),H=B*I,ae=N-z,le=B/R*240+D.current;E.fillStyle=`hsl(${le%360}, 80%, ${Math.max(30,40+Z*30)}%)`,E.fillRect(H+1,ae,I-2,z)}}else if(y==="waveform"){const O=T.current;E.lineWidth=2,E.strokeStyle="#c7d2fe",E.beginPath();const R=F/O.length;for(let _=0;_<O.length;_++){const I=(O[_]-128)/128,B=_*R,Z=N/2+I*(N*.45);_===0?E.moveTo(B,Z):E.lineTo(B,Z)}E.stroke()}else if(y==="palette"){const _=F/12,I=N/6,B=(D.current+$*120)%360;for(let Z=0;Z<6;Z++)for(let z=0;z<12;z++){const H=(Z*12+z)%j.current.length,ae=j.current[H]/255,le=(B+z/12*180+Z/6*90)%360,ne=70+ae*25,X=25+ae*35;E.fillStyle=`hsl(${le}, ${ne}%, ${X}%)`,E.fillRect(z*_,Z*I,Math.ceil(_),Math.ceil(I))}}E.strokeStyle=getComputedStyle(document.documentElement).getPropertyValue("--waveform-stroke")||"#c7d2fe",x.current=requestAnimationFrame(te)},ee=()=>{var F;const Q=v.current,E=Math.max(1,Math.floor(window.devicePixelRatio||1));Q.width=Math.floor(Q.clientWidth*E),Q.height=Math.floor(Q.clientHeight*E),(F=Q.getContext("2d"))==null||F.scale(E,E)};return ee(),window.addEventListener("resize",ee),x.current=requestAnimationFrame(te),()=>{window.removeEventListener("resize",ee),x.current&&cancelAnimationFrame(x.current)}},[C,e,t,y]);const L=()=>{if(e==="youtube")return null;const q=12,A=Math.round(S*q);return o.jsx("div",{style:{position:"absolute",right:10,bottom:10,display:"flex",gap:2,background:"rgba(2,6,23,.5)",padding:"6px 8px",borderRadius:8,border:"1px solid #334155",backdropFilter:"blur(2px)"},children:Array.from({length:q}).map((V,te)=>{const ee=120*(te/q);return o.jsx("div",{style:{width:6,height:18,borderRadius:2,background:te<A?`hsl(${ee}, 80%, 50%)`:"#1f2937"}},te)})})},G=()=>o.jsx("div",{style:{textAlign:"center",color:"#e2e8f0"},children:a?o.jsx("img",{alt:"cover",src:a,style:{height:r-24,objectFit:"contain"}}):o.jsxs("div",{style:{opacity:.8},children:[o.jsx("div",{style:{fontSize:18,fontWeight:600},children:s??"�"}),o.jsx("div",{style:{marginTop:8,fontSize:12,color:vd},children:l??i??"�"})]})});return o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:y==="cover"?o.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"transparent"},children:G()}):o.jsx("canvas",{ref:v,style:{width:typeof n=="number"?`${n}px`:n,height:r,borderRadius:8},role:"img","aria-label":"Stage visualizer canvas"})}),o.jsxs("div",{style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o.jsx("div",{style:{position:"absolute",top:10,right:10,display:"flex",gap:6,background:"rgba(2,6,23,.5)",padding:"6px",borderRadius:10,border:"1px solid #334155",backdropFilter:"blur(2px)",pointerEvents:"auto",zIndex:9999},children:m.map(q=>o.jsx(xd,{active:y===q,onClick:()=>g(q),title:`Tryb: ${q}`,children:q},q))}),o.jsx("div",{style:{position:"absolute",right:10,bottom:10,pointerEvents:"none",zIndex:9998},children:o.jsx(L,{})})]})]})},wd=({artist:e,title:t,hideControls:n=!0,isPlaying:r,onTimeUpdate:a,searchYouTubeByArtistTitle:s})=>{const{t:i}=Ce(),[l,c]=h.useState(e||""),[d,u]=h.useState(t||""),[p,m]=h.useState(null),[f,y]=h.useState(null),g=h.useRef(null),[v,S]=h.useState({width:Math.min(560,window.innerWidth-32),height:Math.min(315,(window.innerWidth-32)*9/16)});h.useEffect(()=>{e&&t&&s&&s(e,t).then(m)},[e,t,s]),h.useEffect(()=>{f&&(r?f.playVideo():f.pauseVideo())},[r,f]),h.useEffect(()=>{if(f&&a){const x=setInterval(()=>{const w=f.getCurrentTime();a(w)},100);return()=>clearInterval(x)}},[f,a]),h.useEffect(()=>{const x=()=>{if(g.current){const w=g.current.clientWidth,k=Math.round(w*(9/16));S({width:w,height:k})}};return x(),window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[]);const b=async()=>{if(!s)return;const x=await s(l,d);m(x)};return o.jsxs("div",{ref:g,style:{width:"100%",maxWidth:"900px",margin:"0 auto"},children:[(!e||!t||!p)&&o.jsxs("div",{children:[o.jsx("input",{value:l,onChange:x=>c(x.target.value),placeholder:i("youtubePlayer.artist","Artist"),"aria-label":i("youtubePlayer.artist","Artist")}),o.jsx("input",{value:d,onChange:x=>u(x.target.value),placeholder:i("youtubePlayer.title","Title"),"aria-label":i("youtubePlayer.title","Title")}),o.jsx("button",{onClick:b,children:i("youtubePlayer.search","Search")})]}),p&&o.jsxs("div",{children:[o.jsx($r,{videoId:p,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:x=>y(x.target)}),!n&&o.jsxs("div",{style:{marginTop:"10px",display:"flex",gap:"10px"},children:[o.jsx("button",{onClick:()=>f==null?void 0:f.playVideo(),children:"? Play"}),o.jsx("button",{onClick:()=>f==null?void 0:f.pauseVideo(),children:"? Pause"})]})]})]})},Fs=({data:e,display:t,callbacks:n,state:r})=>{const{id:a,index:s,artist:i,title:l,version:c,lp:d,sourcesAvailable:u=[]}=e,{allowVersion:p=!0,dragHandleProps:m}=t,{onChange:f,onRemove:y,onMoveUp:g,onMoveDown:v,onChangeLp:S,onSelectSource:b}=n,{readOnly:x=!1,canMoveUp:w=!0,canMoveDown:k=!0,activeSource:j}=r,{t:T}=Ce(),D=h.useRef(null);h.useEffect(()=>{!i&&D.current&&D.current.focus()},[i]);const C=A=>{if(!x&&A.key==="Enter"){const V=A.target.closest("div.gpi-row"),te=V==null?void 0:V.querySelectorAll("input[data-role='field']");if(!te||te.length===0)return;const ee=Array.from(te).indexOf(A.target),W=te[ee+1]??te[0];W==null||W.focus()}},L=A=>{const V=u.includes(A),te=j===A,ee={width:30,height:30,display:"grid",placeItems:"center",borderRadius:6,border:"1px solid #e5e7eb",background:te?"var(--active-bg, #eef2ff)":"var(--bg, #fff)",opacity:V?1:.35,cursor:V&&b&&!x?"pointer":"default",transition:"transform .05s ease"},W=A==="youtube"?"#FF0000":A==="spotify"?"#1DB954":A==="tidal"?"#111827":A==="hls"?"#7C3AED":"#374151",Q=A==="youtube"?Qr.faYoutube:A==="spotify"?Qr.faSpotify:A==="tidal"?er.faGem:A==="hls"?er.faWaveSquare:er.faMusic,E=A==="youtube"?"YouTube":A==="spotify"?"Spotify":A==="tidal"?"TIDAL":A==="hls"?"HLS":"Audio",F=T("playlistItem.sourceLabel")+": "+E+(te?` ${T("playlistItem.sourceSelected")}`:""),N=()=>{!V||!b||x||b(A)};return o.jsx("button",{type:"button",title:E,onClick:N,disabled:!V||x,style:ee,"aria-pressed":te,"aria-label":F,children:o.jsx(ri.FontAwesomeIcon,{icon:Q,style:{color:W}})},A)},G=["youtube","tidal","spotify","hls","audio"],q=typeof d=="number"?d:s+1;return o.jsxs("div",{className:"gpi-row",role:"group","aria-label":T("playlistItem.trackNumber")+" "+(s+1),style:{display:"grid",gridTemplateColumns:p?"56px 1fr 1fr 1fr auto auto":"56px 1fr 1fr auto auto",gap:8,alignItems:"center"},children:[o.jsx("input",{type:"number",min:1,value:q,onChange:A=>S==null?void 0:S(Number(A.target.value)),disabled:x||!S,"aria-label":"Lp",title:T("playlistItem.positionOnList"),style:Cd}),o.jsx("input",{ref:D,"data-role":"field",type:"text",value:i,onChange:A=>f({artist:A.target.value}),placeholder:"Artist",onKeyDown:C,disabled:x,"aria-label":"Artist",className:"gpi-input",style:ar}),o.jsx("input",{"data-role":"field",type:"text",value:l,onChange:A=>f({title:A.target.value}),placeholder:"Title",onKeyDown:C,disabled:x,"aria-label":"Title",className:"gpi-input",style:ar}),p&&o.jsx("input",{"data-role":"field",type:"text",value:c??"",onChange:A=>f({version:A.target.value||void 0}),placeholder:T("playlistItem.versionOptional"),onKeyDown:C,disabled:x,"aria-label":"Version",className:"gpi-input",style:ar}),o.jsx("div",{className:"gpi-sources",style:{display:"flex",gap:6,justifyContent:"flex-end",alignItems:"center"},"aria-label":T("playlistItem.availableSources"),children:G.map(L)}),o.jsxs("div",{className:"gpi-actions",style:{display:"flex",gap:6,justifyContent:"flex-end"},children:[m&&o.jsx("button",{type:"button",...m,draggable:!0,"aria-label":T("playlistItem.dragReorder"),title:T("playlistItem.dragReorder"),style:bn,children:"≡"}),o.jsx("button",{type:"button",onClick:g,disabled:!w||x,"aria-label":T("playlistItem.moveUp"),title:T("playlistItem.moveUp"),style:bn,children:"↑"}),o.jsx("button",{type:"button",onClick:v,disabled:!k||x,"aria-label":T("playlistItem.moveDown"),title:T("playlistItem.moveDown"),style:bn,children:"↓"}),o.jsx("button",{type:"button",onClick:y,disabled:x,"aria-label":T("common.delete"),title:T("common.delete"),style:{...bn,color:"var(--danger, #b91c1c)"},children:"✕"})]})]})},Cd={width:48,border:"1px solid #e5e7eb",borderRadius:6,padding:"8px 6px",fontSize:14,textAlign:"center"},ar={width:"100%",border:"1px solid #e5e7eb",borderRadius:6,padding:"8px 10px",fontSize:14},bn={border:"1px solid #d1d5db",background:"var(--bg, #fff)",padding:"6px 8px",borderRadius:6,cursor:"pointer"},br=()=>Math.random().toString(36).slice(2,10),vn=e=>(e??[]).map(t=>({id:br(),...t})),Md=e=>e.map(({id:t,...n})=>n),kd=null,$d=e=>{const t=e.trim();if(!t)return null;const n=t.split(/\s[-–]\s/);if(n.length<2){const i=t.split(/[;|]/).map(l=>l.trim());return i.length>=2?{artist:i[0],title:i[1],version:i[2]||void 0}:null}const r=n[0].trim(),a=n.slice(1).join(" - ").trim(),s=a.match(/^(.*?)\s*[([](.+?)[)\]]\s*$/);if(s){const i=s[1].trim(),l=s[2].trim();return{artist:r,title:i,version:l||void 0}}return{artist:r,title:a,version:void 0}},Rd=({value:e,defaultValue:t,onChange:n,allowVersion:r=!0,maxItems:a,addButtonLabel:s,emptyState:i=kd,readOnly:l=!1,autoFocusNewItem:c=!0,enableBulkPaste:d=!0})=>{const{t:u}=Ce(),p=e!==void 0,[m,f]=h.useState(()=>vn(e||t)),[y,g]=h.useState(""),v=h.useRef(null),[S,b]=h.useState(null);h.useEffect(()=>{p&&f(vn(e))},[p,JSON.stringify(e)]);const x=h.useCallback(E=>{n==null||n(Md(E))},[n]),w=h.useCallback(E=>{if(p){const F=E(vn(e));x(F)}else f(F=>{const N=E(F);return x(N),N})},[x,p,e]),k=a?m.length<a:!0,j=h.useCallback(()=>{!k||l||w(E=>[...E,{id:br(),artist:"",title:"",version:void 0}])},[k,l,w]),T=h.useCallback((E,F)=>{w(N=>N.map($=>$.id===E?{...$,...F}:$))},[w]),D=h.useCallback(E=>{l||w(F=>F.filter(N=>N.id!==E))},[l,w]),C=h.useCallback((E,F)=>{w(N=>{const $=N.findIndex(_=>_.id===E);if($<0)return N;const M=$+F;if(M<0||M>=N.length)return N;const O=[...N],[R]=O.splice($,1);return O.splice(M,0,R),O})},[w]),L=h.useCallback((E,F)=>{w(N=>{const $=N.findIndex(_=>_.id===E);if($<0)return N;const M=Math.max(0,Math.min(N.length-1,F-1));if($===M)return N;const O=[...N],[R]=O.splice($,1);return O.splice(M,0,R),O})},[w]),G=E=>F=>{l||(v.current=E,F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/plain",E))},q=E=>F=>{l||(F.preventDefault(),F.dataTransfer.dropEffect="move",b(E))},A=E=>()=>b(F=>F===E?null:F),V=E=>F=>{if(l)return;F.preventDefault();const N=v.current??F.dataTransfer.getData("text/plain");b(null),v.current=null,!(!N||N===E)&&w($=>{const M=$.findIndex(I=>I.id===N),O=$.findIndex(I=>I.id===E);if(M<0||O<0||M===O)return $;const R=[...$],[_]=R.splice(M,1);return R.splice(O,0,_),R})},te=()=>{v.current=null,b(null)},ee=h.useCallback(()=>{if(!d||l)return;const F=y.split(/\r?\n/).map(N=>N.trim()).filter(Boolean).map($d).filter(N=>!!N);F.length!==0&&(w(N=>{const $=(a??1/0)-N.length,M=F.slice(0,Math.max(0,$)).map(O=>({id:br(),...O}));return[...N,...M]}),g(""))},[d,l,y,a,w]);h.useEffect(()=>{},[m.length,c]);const W=i??o.jsx("div",{style:{padding:"0.75rem",color:"#777",fontStyle:"italic"},children:u("genericPlaylist.emptyState","No songs. Add the first one below.")}),Q=s??u("genericPlaylist.addSong","Add song");return o.jsxs("div",{className:"gp-container",style:{border:"1px solid #e5e7eb",borderRadius:8,padding:12},children:[o.jsxs("div",{className:"gp-header",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[o.jsx("h3",{style:{margin:0,fontSize:16},children:u("genericPlaylist.playlist","Playlist")}),o.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:8},children:o.jsxs("button",{type:"button",onClick:j,disabled:!k||l,className:"gp-add",style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},"aria-label":Q,children:["+ ",Q]})})]}),m.length===0?o.jsx("div",{className:"gp-empty",children:W}):o.jsx("ol",{className:"gp-list",style:{listStyle:"none",padding:0,margin:0,display:"grid",gap:8},children:m.map((E,F)=>{const N=S===E.id;return o.jsx("li",{draggable:!l,onDragStart:G(E.id),onDragOver:q(E.id),onDragLeave:A(E.id),onDrop:V(E.id),onDragEnd:te,style:{border:N?"2px dashed #6366f1":"2px solid transparent",borderRadius:8,padding:N?4:0},children:o.jsx(Fs,{data:{id:E.id,index:F,lp:F+1,artist:E.artist,title:E.title,version:r?E.version??void 0:void 0,sourcesAvailable:void 0},display:{allowVersion:r,dragHandleProps:{onDragStart:G(E.id)}},callbacks:{onChange:$=>T(E.id,$),onRemove:()=>D(E.id),onMoveUp:()=>C(E.id,-1),onMoveDown:()=>C(E.id,1),onChangeLp:$=>L(E.id,$)},state:{readOnly:l,canMoveUp:F>0,canMoveDown:F<m.length-1}})},E.id)})}),d&&!l&&o.jsx("div",{style:{marginTop:12},children:o.jsxs("details",{children:[o.jsx("summary",{style:{cursor:"pointer",color:"#374151"},children:u("genericPlaylist.bulkPasteSummary","Paste multiple items at once")}),o.jsxs("div",{style:{marginTop:6},children:[o.jsx("textarea",{value:y,onChange:E=>g(E.target.value),placeholder:u("genericPlaylist.bulkPastePlaceholder",`Paste lines in format:
48
+ Artist - Title (Version)
49
+ Artist – Title [Remastered 2011]
50
+ OR: Artist;Title;Version`),rows:3,style:{width:"100%",border:"1px solid #e5e7eb",borderRadius:6,padding:8,fontFamily:"inherit"}}),o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[o.jsx("div",{style:{color:"#6b7280",fontSize:12},children:u("genericPlaylist.bulkPasteHint","Each line will be added as a separate song.")}),o.jsx("button",{type:"button",onClick:ee,disabled:!y.trim(),style:{padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb"},children:u("genericPlaylist.addFromList","Add from list")})]})]})]})})]})},Sa=["#ef4444","#f97316","#f59e0b","#eab308","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e","#78716c","#64748b","#000000"],xn=["🎵","🎸","🎹","🎤","🎧","🥁","🎷","🎺","❤️","⭐","🔥","💎","🌙","☀️","🌊","🎯"],jd=({tags:e,onCreateTag:t,onUpdateTag:n,onDeleteTag:r,selectedTracks:a,onAssignTag:s,onUnassignTag:i})=>{const{t:l}=Ce(),[c,d]=h.useState(null),[u,p]=h.useState(""),[m,f]=h.useState(Sa[8]),[y,g]=h.useState(xn[0]),[v,S]=h.useState(!1),[b,x]=h.useState(null),[w,k]=h.useState(""),[j,T]=h.useState(""),[D,C]=h.useState(""),L=h.useCallback(W=>{d(W.id),k(W.name),T(W.color),C(W.icon||xn[0])},[]),G=h.useCallback(()=>{c&&w.trim()&&(n(c,w.trim(),j,D),d(null))},[c,w,j,D,n]),q=h.useCallback(()=>{u.trim()&&(t(u.trim(),m,y),p(""),S(!1))},[u,m,y,t]),A=h.useCallback(W=>{b===W?(r(W),x(null)):(x(W),setTimeout(()=>x(null),3e3))},[b,r]),V=a&&a.length>0,te=W=>!a||a.length===0?!1:a.every(Q=>Q.tags.includes(W)),ee=W=>!a||a.length===0?!1:a.some(Q=>Q.tags.includes(W))&&!te(W);return o.jsxs("div",{style:{border:"1px solid var(--border-color, #e5e7eb)",borderRadius:10,background:"var(--card-bg, #fff)",overflow:"hidden"},children:[o.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:[o.jsx("span",{style:{fontSize:"1rem"},children:"🏷️"}),o.jsx("span",{style:{fontWeight:600,fontSize:"0.85rem"},children:l("playlistManager.tagManager")}),o.jsx("div",{style:{flex:1}}),o.jsxs("button",{onClick:()=>S(!v),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")]})]}),o.jsxs("div",{style:{padding:12},children:[v&&o.jsxs("div",{style:{border:"1px solid var(--border-color, #d1d5db)",borderRadius:8,padding:10,marginBottom:12,background:"var(--surface-bg, #f9fafb)"},children:[o.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8},children:[o.jsx("input",{type:"text",value:u,onChange:W=>p(W.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:W=>W.key==="Enter"&&q()}),o.jsx("button",{onClick:q,disabled:!u.trim(),style:{background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",border:"none",borderRadius:6,padding:"5px 12px",fontSize:"0.78rem",cursor:"pointer",opacity:u.trim()?1:.5},children:"✓"})]}),o.jsxs("div",{style:{marginBottom:6},children:[o.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.color")}),o.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:Sa.map(W=>o.jsx("div",{onClick:()=>f(W),style:{width:20,height:20,borderRadius:"50%",background:W,cursor:"pointer",border:m===W?"3px solid var(--accent, #3b82f6)":"2px solid transparent",boxSizing:"border-box"}},W))})]}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"0.68rem",opacity:.6,marginBottom:4},children:l("playlistManager.icon")}),o.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap"},children:xn.map(W=>o.jsx("div",{onClick:()=>g(W),style:{width:26,height:26,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"0.85rem",background:y===W?"var(--accent-bg, #eff6ff)":"transparent",border:y===W?"1px solid var(--accent, #3b82f6)":"1px solid transparent"},children:W},W))})]})]}),V&&o.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")+": "+a.length}),e.length===0?o.jsx("div",{style:{textAlign:"center",padding:20,opacity:.3,fontSize:"0.82rem"},children:l("playlistManager.noTags")}):o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.map(W=>o.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderRadius:8,border:"1px solid var(--border-color, #e5e7eb)",background:c===W.id?"var(--surface-bg, #f9fafb)":"transparent"},children:c===W.id?o.jsxs(o.Fragment,{children:[o.jsx("select",{value:D,onChange:Q=>C(Q.target.value),style:{border:"none",background:"transparent",fontSize:"0.9rem",cursor:"pointer"},children:xn.map(Q=>o.jsx("option",{value:Q,children:Q},Q))}),o.jsx("input",{type:"color",value:j,onChange:Q=>T(Q.target.value),style:{width:24,height:24,border:"none",cursor:"pointer",padding:0}}),o.jsx("input",{type:"text",value:w,onChange:Q=>k(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"&&G()}),o.jsx("button",{onClick:G,style:Sn("var(--accent, #3b82f6)"),children:"✓"}),o.jsx("button",{onClick:()=>d(null),style:Sn("var(--text-secondary, #9ca3af)"),children:"✕"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 10px",borderRadius:20,background:`${W.color}18`,color:W.color,fontWeight:600,fontSize:"0.78rem"},children:[W.icon&&o.jsx("span",{children:W.icon}),W.name]}),V&&s&&i&&o.jsx("input",{type:"checkbox",checked:te(W.id),ref:Q=>{Q&&(Q.indeterminate=ee(W.id))},onChange:()=>{const Q=a.map(E=>E.id);te(W.id)?i(Q,W.id):s(Q,W.id)},style:{cursor:"pointer"}}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{onClick:()=>L(W),style:Sn("var(--text-secondary, #9ca3af)"),title:l("playlistManager.editTag"),children:"✏"}),o.jsx("button",{onClick:()=>A(W.id),style:Sn(b===W.id?"var(--error, #ef4444)":"var(--text-secondary, #9ca3af)"),title:b===W.id?l("playlistManager.confirmDelete"):l("playlistManager.deleteTag"),children:b===W.id?"⚠":"🗑"})]})},W.id))})]})]})},Sn=e=>({background:"none",border:"none",cursor:"pointer",fontSize:"0.82rem",color:e,padding:"2px 4px"});var Os=(e=>(e.Static="static",e.Dynamic="dynamic",e))(Os||{}),Ds=(e=>(e.List="list",e.Grid="grid",e.Compact="compact",e.DualPane="dual",e))(Ds||{}),Gs=(e=>(e.Left="left",e.Right="right",e))(Gs||{}),Ue=(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))(Ue||{}),qe=(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))(qe||{}),_s=(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))(_s||{}),It=(e=>(e.Asc="asc",e.Desc="desc",e))(It||{}),Bs=(e=>(e.Library="library",e.Spotify="spotify",e.Tidal="tidal",e.YouTube="youtube",e.MusicBrainz="musicbrainz",e.Import="import",e.Manual="manual",e))(Bs||{});const Td=[{value:Ue.Artist,label:"Artist"},{value:Ue.Title,label:"Title"},{value:Ue.Album,label:"Album"},{value:Ue.Genre,label:"Genre"},{value:Ue.Year,label:"Year"},{value:Ue.Duration,label:"Duration (s)"},{value:Ue.Rating,label:"Rating"},{value:Ue.PlayCount,label:"Play Count"},{value:Ue.Tag,label:"Tag"},{value:Ue.Source,label:"Source"},{value:Ue.AddedDate,label:"Added Date"}],Pd=[{value:qe.Equals,label:"="},{value:qe.NotEquals,label:"≠"},{value:qe.Contains,label:"contains"},{value:qe.NotContains,label:"not contains"},{value:qe.StartsWith,label:"starts with"},{value:qe.GreaterThan,label:">"},{value:qe.LessThan,label:"<"},{value:qe.Between,label:"between"},{value:qe.In,label:"in"},{value:qe.NotIn,label:"not in"}];function Ed(e){return"logic"in e&&"rules"in e}function vr(){return{id:crypto.randomUUID(),field:Ue.Artist,operator:qe.Contains,value:""}}function zs(){return{id:crypto.randomUUID(),logic:"and",rules:[vr()]}}const Ad=({rule:e,onChange:t,onRemove:n})=>o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[o.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.field,onChange:r=>t({...e,field:r.target.value}),children:Td.map(r=>o.jsx("option",{value:r.value,children:r.label},r.value))}),o.jsx("select",{className:"form-select form-select-sm",style:{width:130},value:e.operator,onChange:r=>t({...e,operator:r.target.value}),children:Pd.map(r=>o.jsx("option",{value:r.value,children:r.label},r.value))}),o.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:160},value:e.value,placeholder:"Value",onChange:r=>t({...e,value:r.target.value})}),e.operator===qe.Between&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-muted",children:"–"}),o.jsx("input",{type:"text",className:"form-control form-control-sm",style:{width:120},value:e.value2??"",placeholder:"Value 2",onChange:r=>t({...e,value2:r.target.value})})]}),o.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove rule",children:"✕"})]}),Ws=({group:e,onChange:t,onRemove:n,depth:r=0})=>{const{t:a}=Ce(),s=h.useCallback((p,m)=>{const f=[...e.rules];f[p]=m,t({...e,rules:f})},[e,t]),i=h.useCallback(p=>{const m=e.rules.filter((f,y)=>y!==p);t({...e,rules:m.length>0?m:[vr()]})},[e,t]),l=h.useCallback(()=>{t({...e,rules:[...e.rules,vr()]})},[e,t]),c=h.useCallback(()=>{t({...e,rules:[...e.rules,zs()]})},[e,t]),d=h.useCallback(()=>{t({...e,logic:e.logic==="and"?"or":"and"})},[e,t]),u=e.logic==="and"?"var(--bs-primary)":"var(--bs-warning)";return o.jsxs("div",{className:"p-2 mb-2 rounded",style:{borderLeft:`3px solid ${u}`,backgroundColor:r%2===0?"rgba(var(--bs-body-color-rgb), 0.03)":"transparent"},children:[o.jsxs("div",{className:"d-flex align-items-center gap-2 mb-2",children:[o.jsx("button",{className:`btn btn-sm ${e.logic==="and"?"btn-primary":"btn-warning"}`,onClick:d,title:a("playlistManager.toggleLogic","Toggle AND/OR"),children:e.logic.toUpperCase()}),o.jsx("span",{className:"text-muted small",children:a("playlistManager.matchAll","Match all / any of these rules")}),o.jsxs("div",{className:"ms-auto d-flex gap-1",children:[o.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:l,title:"Add rule",children:"+ Rule"}),r<3&&o.jsx("button",{className:"btn btn-outline-secondary btn-sm",onClick:c,title:"Add nested group",children:"+ Group"}),n&&o.jsx("button",{className:"btn btn-outline-danger btn-sm",onClick:n,title:"Remove group",children:"✕"})]})]}),e.rules.map((p,m)=>Ed(p)?o.jsx(Ws,{group:p,onChange:f=>s(m,f),onRemove:()=>i(m),depth:r+1},p.id):o.jsx(Ad,{rule:p,onChange:f=>s(m,f),onRemove:()=>i(m)},p.id))]})},Ld=({rules:e,onChange:t,limit:n,onLimitChange:r})=>{const{t:a}=Ce(),s=e??zs();return o.jsxs("div",{className:"border rounded p-3",children:[o.jsxs("h6",{className:"mb-3",children:["🔄 ",a("playlistManager.dynamicRules","Dynamic Playlist Rules")]}),o.jsx("p",{className:"text-muted small mb-3",children:a("playlistManager.dynamicRulesHint","Tracks matching these rules will automatically be included in the playlist.")}),o.jsx(Ws,{group:s,onChange:t}),r&&o.jsxs("div",{className:"d-flex align-items-center gap-2 mt-3 pt-2 border-top",children:[o.jsx("label",{className:"form-label mb-0 small",children:a("playlistManager.maxTracks","Max tracks:")}),o.jsx("input",{type:"number",className:"form-control form-control-sm",style:{width:100},min:0,value:n??"",placeholder:"∞",onChange:i=>{const l=parseInt(i.target.value,10);r(isNaN(l)||l<=0?void 0:l)}}),o.jsx("span",{className:"text-muted small",children:a("playlistManager.leaveEmptyForAll","(leave empty for unlimited)")})]})]})},wa=e=>{if(!e)return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`},Nd={library:"💿",spotify:"🟢",tidal:"⬛",youtube:"🔴",musicbrainz:"🎼",import:"📥",manual:"✏"},Id=({tracks:e,tags:t,selectedTrackIds:n,onSelectionChange:r,onPlay:a,onRemove:s,onReorder:i,onTagTracks:l,onRateTracks:c,sortField:d,sortDir:u,onSortChange:p,filterText:m,onFilterChange:f,compact:y=!1,draggable:g=!1,onDragStart:v,dropTarget:S=!1,onDrop:b})=>{const{t:x}=Ce(),[w,k]=h.useState(null),[j,T]=h.useState(null),D=h.useRef(null),C=h.useMemo(()=>{let M=e??[];if(m.trim()){const O=m.toLowerCase();M=M.filter(R=>{var _,I;return R.title.toLowerCase().includes(O)||R.artist.toLowerCase().includes(O)||((_=R.album)==null?void 0:_.toLowerCase().includes(O))||((I=R.genre)==null?void 0:I.toLowerCase().includes(O))})}return[...M].sort((O,R)=>{const _=u==="asc"?1:-1;switch(d){case"title":return _*O.title.localeCompare(R.title);case"artist":return _*O.artist.localeCompare(R.artist);case"album":return _*(O.album??"").localeCompare(R.album??"");case"duration":return _*((O.duration??0)-(R.duration??0));case"year":return _*((O.year??0)-(R.year??0));case"rating":return _*((O.rating??0)-(R.rating??0));case"addedDate":return _*(O.addedAt??"").localeCompare(R.addedAt??"");case"custom":return _*((O.customOrder??0)-(R.customOrder??0));default:return 0}})},[e,m,d,u]),L=h.useCallback((M,O)=>{const R=C[M];if(R){if(O.ctrlKey||O.metaKey){const _=new Set(n);_.has(R.id)?_.delete(R.id):_.add(R.id),r(_)}else if(O.shiftKey&&D.current!==null){const _=Math.min(D.current,M),I=Math.max(D.current,M),B=new Set(n);for(let Z=_;Z<=I;Z++)B.add(C[Z].id);r(B)}else r(new Set([R.id]));D.current=M}},[C,n,r]),G=h.useCallback(()=>{n.size===C.length?r(new Set):r(new Set(C.map(M=>M.id)))},[C,n,r]),q=({field:M,label:O,width:R})=>{const _=d===M;return o.jsxs("div",{style:{width:R,flex:R?void 0:1,cursor:"pointer",userSelect:"none",fontWeight:_?700:500,fontSize:"0.72rem",textTransform:"uppercase",letterSpacing:"0.04em",opacity:_?1:.6,display:"flex",alignItems:"center",gap:4},onClick:()=>{_?p(M,u===It.Asc?It.Desc:It.Asc):p(M,It.Asc)},children:[O,_&&o.jsx("span",{children:u==="asc"?"↑":"↓"})]})},A=h.useCallback((M,O)=>{const R=n.has(M.id)?Array.from(n):[M.id];O.dataTransfer.setData("trackIds",JSON.stringify(R)),O.dataTransfer.effectAllowed="move",v==null||v(R,O)},[n,v]),V=h.useCallback((M,O)=>{O.preventDefault(),O.dataTransfer.dropEffect="move",k(M)},[]),te=h.useCallback((M,O)=>{O.preventDefault(),k(null);try{const R=O.dataTransfer.getData("trackIds");if(R&&i){const _=JSON.parse(R),I=C.filter(z=>!_.includes(z.id)),B=C.filter(z=>_.includes(z.id)),Z=Math.min(M,I.length);I.splice(Z,0,...B),i(I.map(z=>z.id))}}catch{}},[C,i]),ee=h.useCallback(M=>{M.preventDefault(),k(null),b==null||b(M)},[b]),W=h.useMemo(()=>new Map(t.map(M=>[M.id,M])),[t]),Q=M=>M.replace(/[^a-z0-9_-]/gi,"-"),E=y?36:48,F={display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",color:"var(--text-secondary, #6b7280)"},N=(M,O)=>({display:"flex",alignItems:"center",gap:8,padding:y?"4px 12px":"6px 12px",height:E,cursor:"pointer",background:O?"var(--accent-light, #dbeafe)":M?"var(--selected-bg, #eff6ff)":"transparent",borderBottom:"1px solid var(--border-subtle, #f3f4f6)",transition:"background 0.1s"}),$=C.length>0&&n.size===C.length;return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},onDragOver:S?M=>{M.preventDefault(),M.dataTransfer.dropEffect="copy"}:void 0,onDrop:S?ee:void 0,children:[o.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)",display:"flex",gap:8,alignItems:"center"},children:[o.jsx("input",{type:"text",value:m,onChange:M=>f(M.target.value),placeholder:"🔍 "+x("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)"}}),o.jsxs("span",{style:{fontSize:"0.72rem",opacity:.5},children:[C.length,"/",(e??[]).length]}),n.size>0&&s&&o.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:()=>s(Array.from(n)),children:["🗑 ",n.size]})]}),o.jsxs("div",{style:F,children:[o.jsx("div",{style:{width:28},children:o.jsx("input",{type:"checkbox",checked:$,onChange:G,style:{cursor:"pointer"}})}),o.jsx("div",{style:{width:20},children:"#"}),!y&&o.jsx("div",{style:{width:44}}),o.jsx(q,{field:"title",label:x("playlistManager.colTitle")}),o.jsx(q,{field:"artist",label:x("playlistManager.colArtist")}),!y&&o.jsx(q,{field:"album",label:x("playlistManager.colAlbum")}),o.jsx(q,{field:"duration",label:x("playlistManager.colDuration"),width:60}),!y&&o.jsx(q,{field:"year",label:x("playlistManager.colYear"),width:50}),o.jsx("div",{style:{width:30}})," ",!y&&o.jsx("div",{style:{width:60}})," ",o.jsx("div",{style:{width:24}})," "]}),o.jsxs("div",{style:{flex:1,overflow:"auto"},children:[C.length===0&&o.jsx("div",{style:{padding:24,textAlign:"center",opacity:.4,fontSize:"0.85rem"},children:e.length===0?x("playlistManager.emptyPlaylist"):x("playlistManager.noMatchingTracks")}),C.map((M,O)=>{const R=n.has(M.id),_=w===O;return o.jsxs("div",{style:N(R,_),onClick:I=>L(O,I),onDoubleClick:()=>a==null?void 0:a(M),draggable:g,onDragStart:I=>A(M,I),onDragOver:I=>V(O,I),onDrop:I=>te(O,I),onDragLeave:()=>k(null),children:[o.jsx("div",{style:{width:28},children:o.jsx("input",{type:"checkbox",checked:R,onChange:()=>{const I=new Set(n);R?I.delete(M.id):I.add(M.id),r(I)},onClick:I=>I.stopPropagation(),style:{cursor:"pointer"}})}),o.jsx("div",{style:{width:20,fontSize:"0.7rem",opacity:.4},children:O+1}),!y&&o.jsx("div",{style:{width:44,height:36,flexShrink:0},children:M.coverUrl?o.jsx("img",{src:M.coverUrl,alt:M.title||x("common.coverArt","Cover art"),style:{width:36,height:36,borderRadius:4,objectFit:"cover"},loading:"lazy"}):o.jsx("div",{style:{width:36,height:36,borderRadius:4,background:"var(--surface-bg, #f3f4f6)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.9rem"},children:"🎵"})}),o.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",fontWeight:500},children:M.title}),o.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.82rem",opacity:.7},children:M.artist}),!y&&o.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",opacity:.5},children:M.album}),o.jsx("div",{style:{width:60,fontSize:"0.78rem",opacity:.5,textAlign:"right"},children:wa(M.duration)}),!y&&o.jsx("div",{style:{width:50,fontSize:"0.72rem",opacity:.4,textAlign:"center"},children:M.year||""}),o.jsx("div",{style:{width:30,textAlign:"center",fontSize:"0.75rem"},title:M.source,children:Nd[M.source]??"?"}),!y&&o.jsxs("div",{style:{width:60,display:"flex",gap:2,overflow:"hidden"},children:[M.tags.slice(0,2).map(I=>{const B=W.get(I);if(!B)return null;const Z=`--tag-${Q(I)}`;return o.jsx("span",{style:{fontSize:"0.6rem",padding:"1px 5px",borderRadius:8,background:`var(${Z}-bg, ${B.color}22)`,color:`var(${Z}, ${B.color})`,whiteSpace:"nowrap"},children:B.name},I)}),M.tags.length>2&&o.jsxs("span",{style:{fontSize:"0.6rem",opacity:.4},children:["+",M.tags.length-2]})]}),o.jsxs("div",{style:{width:24,display:"flex",alignItems:"center"},children:[o.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:2,opacity:.5,position:"relative"},onClick:I=>{I.stopPropagation(),T(j===M.id?null:M.id)},title:x("playlistManager.morActions"),children:"⋮"}),j===M.id&&t.length>0&&o.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 rgba(0,0,0,0.1)",minWidth:140},children:[o.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:x("playlistManager.assignTag")}),t.map(I=>{const B=M.tags.includes(I.id);return o.jsxs("div",{style:{padding:"4px 8px",borderRadius:4,cursor:"pointer",fontSize:"0.78rem",display:"flex",alignItems:"center",gap:6,background:B?`var(--tag-${Q(I.id)}-bg, ${I.color}22)`:"transparent"},onClick:Z=>{Z.stopPropagation();const z=n.size>0?Array.from(n):[M.id];B||l==null||l(z,[I.id]),T(null)},children:[o.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:`var(--tag-${Q(I.id)}, ${I.color})`,flexShrink:0}}),o.jsx("span",{children:I.name}),B&&o.jsx("span",{style:{marginLeft:"auto"},children:"✓"})]},I.id)})]})]})]},M.id)})]}),o.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid var(--border-color, #e5e7eb)",fontSize:"0.72rem",opacity:.5,display:"flex",gap:16},children:[o.jsxs("span",{children:[C.length," ",x("playlistManager.tracks")]}),o.jsx("span",{children:wa(C.reduce((M,O)=>M+(O.duration??0),0))}),n.size>0&&o.jsxs("span",{children:[n.size," ",x("playlistManager.selected")]})]})]})},Ca=e=>({playlistId:e,selectedTrackIds:new Set,sortField:"custom",sortDir:"asc",filterText:""}),Fd=({playlists:e,tags:t,onCopyTracks:n,onMoveTracks:r,onRemoveTracks:a,onReorderTracks:s,onPlay:i,onTagTracks:l,initialLeftId:c,initialRightId:d})=>{const{t:u}=Ce(),[p,m]=h.useState(()=>Ca(c??null)),[f,y]=h.useState(()=>Ca(d??null)),[g,v]=h.useState("left"),[S,b]=h.useState(null),[x,w]=h.useState(50),[k,j]=h.useState(!1),T=h.useMemo(()=>e.find($=>$.id===p.playlistId),[e,p.playlistId]),D=h.useMemo(()=>e.find($=>$.id===f.playlistId),[e,f.playlistId]),C=h.useCallback(($,M)=>{$==="left"?m(O=>({...O,...M})):y(O=>({...O,...M}))},[]),L=h.useCallback($=>$==="left"?p:f,[p,f]),G=$=>$==="left"?"right":"left",q=h.useCallback($=>{const M=L($),O=L(G($));!M.playlistId||!O.playlistId||M.selectedTrackIds.size===0||(n(M.playlistId,O.playlistId,Array.from(M.selectedTrackIds)),C($,{selectedTrackIds:new Set}))},[L,n,C]),A=h.useCallback($=>{const M=L($),O=L(G($));!M.playlistId||!O.playlistId||M.selectedTrackIds.size===0||(r(M.playlistId,O.playlistId,Array.from(M.selectedTrackIds)),C($,{selectedTrackIds:new Set}))},[L,r,C]),V=h.useCallback($=>{const M=L($);!M.playlistId||M.selectedTrackIds.size===0||b({operation:"copy",sourcePlaylistId:M.playlistId,trackIds:Array.from(M.selectedTrackIds)})},[L]),te=h.useCallback($=>{const M=L($);!M.playlistId||M.selectedTrackIds.size===0||b({operation:"cut",sourcePlaylistId:M.playlistId,trackIds:Array.from(M.selectedTrackIds)})},[L]),ee=h.useCallback($=>{const M=L($);!S||!M.playlistId||(S.operation==="copy"?n(S.sourcePlaylistId,M.playlistId,S.trackIds):r(S.sourcePlaylistId,M.playlistId,S.trackIds),b(null))},[S,L,n,r]),W=h.useCallback($=>{$.key==="Tab"&&!$.shiftKey&&($.preventDefault(),v(M=>G(M))),($.ctrlKey||$.metaKey)&&$.key==="c"&&V(g),($.ctrlKey||$.metaKey)&&$.key==="x"&&te(g),($.ctrlKey||$.metaKey)&&$.key==="v"&&ee(g)},[g,V,te,ee]),Q=h.useCallback(()=>j(!0),[]),E=h.useCallback($=>{if(!k)return;const M=$.currentTarget.getBoundingClientRect(),O=($.clientX-M.left)/M.width*100;w(Math.max(20,Math.min(80,O)))},[k]),F=h.useCallback(()=>j(!1),[]),N=$=>{const M=L($),O=$==="left"?T:D,R=g===$,I=!!L(G($)).playlistId;return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",border:R?"2px solid var(--accent, #3b82f6)":"2px solid transparent",borderRadius:8,overflow:"hidden",background:"var(--card-bg, #fff)"},onClick:()=>v($),children:[o.jsx("div",{style:{padding:"8px 12px",background:R?"var(--accent, #3b82f6)":"var(--surface-bg, #f3f4f6)",color:R?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",display:"flex",alignItems:"center",gap:8},children:o.jsxs("select",{value:M.playlistId??"",onChange:B=>C($,{playlistId:B.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:R?"var(--accent-overlay, #ffffff30)":"var(--input-bg, #fff)",color:R?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)"},children:[o.jsx("option",{value:"",children:u("playlistManager.selectPlaylist")}),e.map(B=>o.jsxs("option",{value:B.id,children:[B.name," (",B.trackCount,")"]},B.id))]})}),o.jsxs("div",{style:{display:"flex",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border-color, #e5e7eb)",flexWrap:"wrap"},children:[o.jsxs("button",{style:sr(!1),onClick:()=>q($),disabled:!M.playlistId||!I||M.selectedTrackIds.size===0,title:u("playlistManager.copyToOther"),children:[$==="left"?"📋→":"←📋"," ",u("playlistManager.copy")]}),o.jsxs("button",{style:sr(!1),onClick:()=>A($),disabled:!M.playlistId||!I||M.selectedTrackIds.size===0,title:u("playlistManager.moveToOther"),children:[$==="left"?"✂→":"←✂"," ",u("playlistManager.move")]}),o.jsx("div",{style:{flex:1}}),S&&o.jsxs("button",{style:sr(!0),onClick:()=>ee($),disabled:!M.playlistId,children:["📌 ",u("playlistManager.paste")," (",S.trackIds.length,")"]})]}),O?o.jsx(Id,{tracks:O.tracks,tags:t,selectedTrackIds:M.selectedTrackIds,onSelectionChange:B=>C($,{selectedTrackIds:B}),onPlay:i,onRemove:B=>a(O.id,B),onReorder:B=>s(O.id,B),onTagTracks:l,sortField:M.sortField,sortDir:M.sortDir,onSortChange:(B,Z)=>C($,{sortField:B,sortDir:Z}),filterText:M.filterText,onFilterChange:B=>C($,{filterText:B}),compact:!0,draggable:!0}):o.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",opacity:.3,fontSize:"0.85rem"},children:u("playlistManager.selectPlaylistPrompt")})]})};return o.jsxs("div",{style:{display:"flex",height:"100%",userSelect:k?"none":"auto"},onKeyDown:W,onMouseMove:E,onMouseUp:F,tabIndex:0,children:[o.jsx("div",{style:{width:`${x}%`,minWidth:200},children:N("left")}),o.jsx("div",{style:{width:6,cursor:"col-resize",background:k?"var(--accent, #3b82f6)":"var(--border-color, #e5e7eb)",transition:k?"none":"background 0.15s",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseDown:Q,children:o.jsx("div",{style:{width:2,height:40,borderRadius:1,background:k?"var(--btn-text, #fff)":"var(--text-secondary, #9ca3af)"}})}),o.jsx("div",{style:{flex:1,minWidth:200},children:N("right")})]})},sr=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"}),Us="av:local-playlists";function Od(){try{const e=localStorage.getItem(Us);return e?JSON.parse(e):[]}catch{return[]}}function Dd(e){const t=JSON.stringify(e);try{localStorage.setItem(Us,t)}catch{}}function qs(){const[e,t]=h.useState(()=>Od()),n=h.useRef(!1);return h.useEffect(()=>{n.current=!0},[]),h.useEffect(()=>{Dd(e)},[e]),h.useMemo(()=>({list:()=>e,get:a=>e.find(s=>s.id===a),create:a=>{const s=new Date().toISOString(),i={id:crypto.randomUUID(),name:a,items:[],updatedAt:s};return t(l=>[i,...l]),i},rename:(a,s)=>t(i=>i.map(l=>l.id===a?{...l,name:s,updatedAt:new Date().toISOString()}:l)),remove:a=>t(s=>s.filter(i=>i.id!==a)),replaceItems:(a,s)=>t(i=>i.map(l=>l.id===a?{...l,items:s,updatedAt:new Date().toISOString()}:l)),addItems:(a,s)=>t(i=>i.map(l=>l.id===a?{...l,items:[...l.items,...s],updatedAt:new Date().toISOString()}:l))}),[e])}const Gd="[PlaylistList]",_d={border:"1px solid #e5e7eb",borderRadius:8,background:"#fff"},Bd={..._d,padding:"8px 10px",cursor:"pointer"},Vs={border:"1px solid var(--border-light, #d1d5db)",borderRadius:8,padding:"6px 10px",background:"var(--bg, #fff)",cursor:"pointer"},zd={...Vs,background:"var(--primary, #4f46e5)",borderColor:"var(--primary, #4f46e5)",color:"var(--bg, #fff)"},Ks=({selectedId:e,onSelect:t,onCreateRemote:n})=>{const{t:r}=Ce(),a=qs(),[s,i]=h.useState(""),l=h.useMemo(()=>a.list(),[a]);return o.jsxs("div",{style:{display:"grid",gap:10},children:[o.jsxs("div",{style:{display:"flex",gap:8},children:[o.jsx("input",{placeholder:r("playlistList.playlistName","Playlist name..."),value:s,onChange:c=>i(c.target.value),style:{flex:1,border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px"},"aria-label":"Playlist name"}),o.jsxs("button",{type:"button",disabled:!s.trim(),style:s.trim()?zd:{...Vs,cursor:"not-allowed",color:"var(--muted, #9ca3af)",background:"var(--bg-muted, #f3f4f6)"},onClick:async()=>{const c=a.create(s.trim());if(i(""),n)try{await n({platform:"tidal",name:c.name,songs:c.items})}catch(d){console.error(Gd,"Remote playlist create failed:",d)}t==null||t(c)},children:["+ ",r("common.add","Add")]})]}),o.jsxs("div",{style:{display:"grid",gap:6},children:[l.map(c=>{const d=c.id===e;return o.jsxs("button",{onClick:()=>t==null?void 0:t(c),style:{...Bd,background:d?"var(--active-bg, #eef2ff)":"var(--bg, #fff)"},children:[o.jsx("div",{style:{fontWeight:600},children:c.name}),o.jsxs("div",{style:{color:"var(--text-dim, #64748b)",fontSize:12},children:[c.items.length+" "+r("playlistList.songs","songs")," \\u2022 ",new Date(c.updatedAt).toLocaleString()]})]},c.id)}),!l.length&&o.jsx("div",{style:{color:"var(--muted, #6b7280)"},children:r("playlistList.emptyState","No playlists. Add the first one ↑")})]})]})},Wd="PlaylistBrowser",Ma={display:"grid",gap:12},ka=e=>({artist:(e.artists??[]).join(", "),title:e.title}),Ud=({renderLibrarySearch:e,renderLibrarySearchResult:t,renderLibraryList:n})=>{var m;const{t:r}=Ce(),a=qs(),[s,i]=h.useState(null),[l,c]=h.useState(""),[,d]=h.useState([]),u=s==null?void 0:s.id,p=(f,y)=>{if("addItems"in a){a.addItems(f.id,y);const v=a.list().find(S=>S.id===f.id)||f;i(v);return}const g=a;if("update"in a&&typeof g.update=="function"){const v=Array.from([...f.items||[],...y]);g.update({...f,items:v});const S=a.list().find(b=>b.id===f.id)||{...f,items:v};i(S);return}console.warn(Wd,"useLocalPlaylists: missing addItems/update method � update hook implementation.")};return o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(min(200px, 100%), 320px) 1fr",gap:16},children:[o.jsxs("div",{style:Ma,children:[o.jsx("h3",{style:{margin:0},children:r("playlistBrowser.playlists")}),o.jsx(Ks,{selectedId:u,onSelect:i}),s&&o.jsxs("div",{style:{fontSize:12,color:"var(--text-dim, #64748b)"},children:[r("playlistBrowser.selected","Selected"),": ",o.jsx("strong",{children:s.name})," � ",((m=s.items)==null?void 0:m.length)??0," ",r("playlistBrowser.tracks","tracks")]})]}),o.jsxs("div",{style:Ma,children:[o.jsx("h3",{style:{margin:0},children:r("playlistBrowser.library")}),o.jsxs("div",{children:[e==null?void 0:e({placeholder:r("playlistBrowser.searchAndAdd","Search and add to playlist..."),onPick:f=>{s&&p(s,[ka(f)])}}),o.jsx("input",{placeholder:r("playlistBrowser.fullSearch","Full search (Enter does not add, full list below)"),value:l,onChange:f=>c(f.target.value),style:{width:"100%",border:"1px solid #d1d5db",borderRadius:8,padding:"6px 10px",marginTop:10}})]}),t==null?void 0:t({query:l,onPick:f=>{s&&p(s,[ka(f)])}}),n==null?void 0:n({onPlayNow:f=>d(f),onAddToQueue:f=>d(y=>[...y,...f]),onAddDescriptors:f=>s&&p(s,f)})]})]})};var bt=(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))(bt||{});const Hs=(e,t=null)=>e.filter(n=>n.parentId===t).sort((n,r)=>n.sortOrder-r.sortOrder).map(n=>({...n,children:Hs(e,n.id)})),qd={[bt.Spotify]:{icon:"🟢",label:"Spotify",color:"var(--source-spotify, #1DB954)",bg:"var(--source-spotify-bg, #1DB95418)"},[bt.Tidal]:{icon:"⬛",label:"Tidal",color:"var(--source-tidal, #000000)",bg:"var(--source-tidal-bg, #00000010)"},[bt.YouTube]:{icon:"🔴",label:"YouTube",color:"var(--source-youtube, #FF0000)",bg:"var(--source-youtube-bg, #FF000010)"}},Vd=({folders:e,playlists:t,tags:n,services:r,activeFolderId:a,activePlaylistId:s,onSelectFolder:i,onSelectPlaylist:l,onCreateFolder:c,onRenameFolder:d,onDeleteFolder:u,onCreatePlaylist:p,onConnectService:m,onDisconnectService:f,onDragPlaylistToFolder:y,collapsed:g=!1,onToggleCollapse:v})=>{const{t:S}=Ce(),[b,x]=h.useState(new Set),[w,k]=h.useState(!1),[j,T]=h.useState(""),[D,C]=h.useState(null),[L,G]=h.useState(!1),[q,A]=h.useState(""),[V,te]=h.useState("static"),[ee,W]=h.useState(null),[Q,E]=h.useState(""),[F,N]=h.useState(null),[$,M]=h.useState(!1),O=h.useMemo(()=>Hs(e),[e]),R=h.useCallback(U=>{x(fe=>{const me=new Set(fe);return me.has(U)?me.delete(U):me.add(U),me})},[]),_=h.useCallback(()=>{j.trim()&&(c(j.trim(),D),T(""),k(!1))},[j,D,c]),I=h.useCallback(()=>{q.trim()&&(p(q.trim(),V,a),A(""),G(!1))},[q,V,a,p]),B=h.useCallback(U=>{Q.trim()&&(d(U,Q.trim()),W(null),E(""))},[Q,d]),Z=h.useCallback((U,fe)=>{U.preventDefault(),U.dataTransfer.dropEffect="move",N(fe)},[]),z=h.useCallback((U,fe)=>{U.preventDefault();const me=U.dataTransfer.getData("playlistId");me&&y&&y(me,fe),N(null)},[y]),H=h.useCallback(()=>N(null),[]),ae=h.useCallback(U=>t.filter(fe=>(fe.folderId??null)===U),[t]),le={width:g?48:280,minWidth:g?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%"},ne={padding:"8px 12px",borderBottom:"1px solid var(--border-color, #e5e7eb)"},X=(U,fe=!1)=>({padding:"6px 12px",borderRadius:6,cursor:"pointer",display:"flex",alignItems:"center",gap:8,fontSize:"0.82rem",background:fe?"var(--accent-light, #dbeafe)":U?"var(--accent, #3b82f6)":"transparent",color:U?"var(--btn-text, #fff)":"var(--text-primary, #1f2937)",transition:"background 0.15s",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),K={background:"none",border:"none",cursor:"pointer",fontSize:"0.75rem",padding:"2px 6px",borderRadius:4,color:"var(--text-secondary, #6b7280)"},J={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=(U,fe)=>{var Me,Y;const me=b.has(U.id),xe=a===U.id,De=F===U.id,Te=ae(U.id);return o.jsxs("div",{children:[o.jsxs("div",{style:{...X(xe,De),paddingLeft:12+fe*16},onClick:()=>{i(U.id),U.children&&U.children.length>0&&R(U.id)},onDragOver:re=>Z(re,U.id),onDrop:re=>z(re,U.id),onDragLeave:H,children:[o.jsx("span",{style:{width:14,textAlign:"center",flexShrink:0,fontSize:"0.7rem"},children:(((Me=U.children)==null?void 0:Me.length)||0)>0||Te.length>0?me?"▼":"▶":"·"}),ee===U.id?o.jsx("input",{value:Q,onChange:re=>E(re.target.value),onKeyDown:re=>{re.key==="Enter"&&B(U.id),re.key==="Escape"&&W(null)},onBlur:()=>B(U.id),autoFocus:!0,style:{...J,flex:1},onClick:re=>re.stopPropagation()}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:U.icon??"📁"}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:U.name}),o.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:Te.length}),o.jsx("button",{style:K,onClick:re=>{re.stopPropagation(),W(U.id),E(U.name)},title:S("common.rename"),children:"✏"}),o.jsx("button",{style:{...K,color:"var(--error, #ef4444)"},onClick:re=>{re.stopPropagation(),u(U.id)},title:S("common.delete"),children:"✕"})]})]}),me&&o.jsxs(o.Fragment,{children:[Te.map(re=>ie(re,fe+1)),(Y=U.children)==null?void 0:Y.map(re=>oe(re,fe+1))]})]},U.id)},ie=(U,fe)=>{const me=s===U.id;return o.jsxs("div",{style:{...X(me),paddingLeft:12+fe*16+22},onClick:()=>l(U.id),draggable:!0,onDragStart:xe=>{xe.dataTransfer.setData("playlistId",U.id),xe.dataTransfer.effectAllowed="move"},children:[o.jsx("span",{style:{fontSize:"0.7rem"},children:U.type==="dynamic"?"⚡":"🎵"}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:U.name}),o.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:U.trackCount})]},U.id)};if(g)return o.jsx("div",{style:le,children:o.jsx("button",{style:{...K,padding:"12px 0",fontSize:"1.1rem",width:"100%"},onClick:v,title:S("playlistManager.expandSidebar"),children:"▶"})});const ue=ae(null);return o.jsxs("div",{style:le,children:[o.jsxs("div",{style:{...ne,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("span",{style:{fontWeight:700,fontSize:"0.85rem"},children:["🎶 ",S("playlistManager.title")]}),o.jsx("button",{style:K,onClick:v,title:S("playlistManager.collapseSidebar"),children:"◀"})]}),o.jsxs("div",{style:{...ne,display:"flex",gap:4,flexWrap:"wrap"},children:[o.jsxs("button",{style:{...K,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:6,padding:"4px 10px"},onClick:()=>G(!0),children:["+ ",S("playlistManager.newPlaylist")]}),o.jsxs("button",{style:{...K,border:"1px solid var(--border-color, #d1d5db)",borderRadius:6,padding:"4px 10px"},onClick:()=>{k(!0),C(a)},children:["📁 ",S("playlistManager.newFolder")]})]}),L&&o.jsxs("div",{style:{...ne,display:"flex",flexDirection:"column",gap:6},children:[o.jsx("input",{value:q,onChange:U=>A(U.target.value),placeholder:S("playlistManager.playlistName"),style:J,autoFocus:!0,onKeyDown:U=>{U.key==="Enter"&&I(),U.key==="Escape"&&G(!1)}}),o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[o.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[o.jsx("input",{type:"radio",checked:V==="static",onChange:()=>te("static")}),S("playlistManager.static")]}),o.jsxs("label",{style:{fontSize:"0.75rem",display:"flex",gap:4,alignItems:"center",cursor:"pointer"},children:[o.jsx("input",{type:"radio",checked:V==="dynamic",onChange:()=>te("dynamic")}),"⚡ ",S("playlistManager.dynamic")]}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{style:{...K,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:I,"aria-label":"Confirm create playlist",children:"✓"}),o.jsx("button",{style:K,onClick:()=>G(!1),"aria-label":"Cancel create playlist",children:"✕"})]})]}),w&&o.jsxs("div",{style:{...ne,display:"flex",gap:6},children:[o.jsx("input",{value:j,onChange:U=>T(U.target.value),placeholder:S("playlistManager.folderName"),style:{...J,flex:1},autoFocus:!0,onKeyDown:U=>{U.key==="Enter"&&_(),U.key==="Escape"&&k(!1)}}),o.jsx("button",{style:{...K,background:"var(--accent, #3b82f6)",color:"var(--btn-text, #fff)",borderRadius:4,padding:"3px 8px"},onClick:_,"aria-label":"Confirm create folder",children:"✓"}),o.jsx("button",{style:K,onClick:()=>k(!1),"aria-label":"Cancel create folder",children:"✕"})]}),o.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[o.jsxs("div",{style:X(a===null&&s===null,F==="__root__"),onClick:()=>i(null),onDragOver:U=>Z(U,null),onDrop:U=>z(U,null),onDragLeave:H,children:[o.jsx("span",{children:"🏠"}),o.jsx("span",{style:{flex:1},children:S("playlistManager.allPlaylists")}),o.jsx("span",{style:{fontSize:"0.65rem",opacity:.5},children:t.length})]}),ue.map(U=>ie(U,0)),O.map(U=>oe(U,0))]}),n.length>0&&o.jsxs("div",{style:ne,children:[o.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,marginBottom:4,opacity:.6},children:S("playlistManager.tags")}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:n.map(U=>o.jsxs("span",{style:{fontSize:"0.7rem",padding:"2px 8px",borderRadius:12,background:U.color+"22",color:U.color,border:`1px solid ${U.color}44`,cursor:"pointer"},children:[U.icon&&`${U.icon} `,U.name]},U.id))})]}),o.jsxs("div",{style:ne,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",fontSize:"0.7rem",fontWeight:600,opacity:.6},onClick:()=>M(!$),children:[o.jsxs("span",{children:["🔗 ",S("playlistManager.services")]}),o.jsx("span",{children:$?"▲":"▼"})]}),$&&o.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:4},children:[bt.Spotify,bt.Tidal,bt.YouTube].map(U=>{const fe=qd[U],me=r.find(xe=>xe.platform===U);return o.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:[o.jsx("span",{children:fe.icon}),o.jsx("span",{style:{flex:1},children:fe.label}),me!=null&&me.connected?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{fontSize:"0.65rem",opacity:.6},children:me.username??S("playlistManager.connected")}),o.jsx("button",{style:{...K,color:"#ef4444"},onClick:()=>f(U),children:"✕"})]}):o.jsx("button",{style:{...K,background:fe.color,color:"#fff",borderRadius:4,padding:"2px 8px"},onClick:()=>m(U),children:S("playlistManager.connect")})]},U)})})]})]})};function $a(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function Ys(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 a=parseInt(n.slice(1),16);return{r:a>>16&255,g:a>>8&255,b:a&255}}const r=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return r?{r:+r[1],g:+r[2],b:+r[3]}:null}function or(e,t){const n=Ys(e);return n?`rgba(${n.r},${n.g},${n.b},${t})`:`rgba(255,255,255,${t})`}function Kd(e){const t=Ys(e);return t?(.299*t.r+.587*t.g+.114*t.b)/255:1}function Zs(){const e=$a("--text-primary")||"rgba(255,255,255,0.95)",t=$a("--nav-active")||"goldenrod",n=document.documentElement.getAttribute("data-theme")==="dark",a=Kd(e)<.45;return{base:or(e,.92),staffLine:or(e,.22),outline:a?"rgba(255,255,255,0.75)":"rgba(0,0,0,0.55)",accents:[or(t,.95)],isDark:n,notesDark:a}}const Hd=[{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}],Yd="concert-harp",zr=Object.fromEntries(Hd.map(e=>[e.id,e])),Zd="nice2dev-note-sound-set";function Xs(){try{const e=localStorage.getItem(Zd);if(e&&zr[e])return e}catch{}return Yd}const Hn=typeof navigator<"u"&&/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent),Js=46,Qe=5,Pn=4,Xd=(Js-(Qe-1)*Pn)/2,Jd=6,Qd=18,eu=110,tu=50,Yn=Hn?tu:eu,nu=Hn?4:2,ru=Hn?2:4,Ra=Hn?1:0,au=180,ja=2.8,Ta=40,su=14,Pa=1.2,ou=16,ir=[64,67,71,74,77],At=64,cn=77;function iu(e){const t=Math.max(0,Math.min(Qe-1,e)),n=Math.floor(t),r=Math.min(n+1,Qe-1),a=t-n;return Math.round(ir[n]+(ir[r]-ir[n])*a)}function lu(e){return(Math.max(At-1*(cn-At)/(Qe-1),Math.min(cn+1*(cn-At)/(Qe-1),e))-At)/(cn-At)*(Qe-1)}const Ea=2.5,Aa=.72,cu=.55,dn=new Map;let En=null;async function du(e){const t=e??Xs(),n=zr[t];if(!n||!n.dir){dn.clear(),En=t;return}if(En===t&&dn.size>0)return;dn.clear(),En=t;const r=qt(),a=[];for(let s=At;s<=cn;s++)a.push(fetch(`/assets/soundfonts/notes/${n.dir}/note-${s}.mp3`).then(i=>i.arrayBuffer()).then(i=>r.decodeAudioData(i)).then(i=>{dn.set(s,i)}).catch(()=>{}));await Promise.all(a)}function La(e){const t=dn.get(e);if(!t)return;const n=qt(),r=n.createBufferSource();r.buffer=t;const a=n.createGain();a.gain.value=.7,r.connect(a).connect(n.destination),r.start()}const Na=["𝅘𝅥","𝅘𝅥𝅮","𝅘𝅥𝅯","𝅘𝅥𝅰","𝅘𝅥𝅱","♪","♫","♬"];function uu(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 hu(e){const t=uu(42),n=[];for(let r=0;r<e;r++){const s=t()<.15?0:-1;n.push({x:t(),lineIdx:t()*(Qe+1)-.5,char:Na[Math.floor(t()*Na.length)],rot:(t()-.5)*50,size:10+t()*4,colorIdx:s})}return n.sort((r,a)=>r.x-a.x),n}const He=hu(Yn),Xt=new Float32Array(Yn),wn=new Float32Array(Yn),un=new Float32Array(Yn);let xr=!1;const fu=(Qe-1)/2;function pu(){if(!xr){xr=!0;for(let e=0;e<He.length;e++)un[e]=He[e].lineIdx}}let Sr=[],Ia="";function mu(e){return`${e.base}|${e.outline}|${e.accents.join(",")}`}function gu(e){const t=mu(e);t===Ia&&Sr.length===He.length||(Ia=t,Sr=He.map(n=>{const r=Math.ceil(n.size*1.6),a=r*2,s=document.createElement("canvas");s.width=a,s.height=a;const i=s.getContext("2d");return i.translate(r,r),i.rotate(n.rot*Math.PI/180),i.font=`${n.size}px serif`,i.textAlign="center",i.textBaseline="middle",i.lineWidth=1.8,i.strokeStyle=e.outline,i.strokeText(n.char,0,0),i.fillStyle=n.colorIdx<0?e.base:e.accents[n.colorIdx%e.accents.length],i.fillText(n.char,0,0),{canvas:s,ox:r,oy:r}}))}function yu({pitchMidiRef:e}={}){const t=h.useRef(null),n=h.useRef(0),r=h.useRef(0),a=h.useRef(0),s=h.useRef(null),i=h.useRef(0),l=h.useRef(0),c=h.useRef(null),d=h.useRef(null),u=h.useRef(!1),p=h.useCallback((g,v,S)=>{const b=Xd+g*Pn,x=v/S*Math.PI*2;return b+Math.sin(x)*Jd},[]),m=h.useCallback(g=>{const v=t.current;if(!v)return;if(l.current++,Ra>0&&l.current%(Ra+1)!==0){a.current=g,n.current=requestAnimationFrame(m);return}const S=v.getContext("2d");if(!S)return;const b=Math.min(window.devicePixelRatio||1,ru),x=v.getBoundingClientRect(),w=x.width,k=x.height;(v.width!==Math.round(w*b)||v.height!==Math.round(k*b))&&(v.width=Math.round(w*b),v.height=Math.round(k*b),S.setTransform(b,0,0,b,0,0));const j=a.current?(g-a.current)/1e3:0;a.current=g,r.current=(r.current+Qd*j)%w,S.clearRect(0,0,w,k),i.current++,(!s.current||i.current%60===0)&&(s.current=Zs());const T=s.current;gu(T),S.strokeStyle=T.staffLine,S.lineWidth=.7;for(let G=0;G<Qe;G++){S.beginPath();for(let q=0;q<=w;q+=nu){const A=p(G,q,w);q===0?S.moveTo(q,A):S.lineTo(q,A)}S.stroke()}const D=r.current,C=(e==null?void 0:e.current)??null;if(C!==null){pu();const G=lu(C),q=Ea*j;for(let A=0;A<He.length;A++){const te=(He[A].lineIdx-fu)*cu,W=G*Aa+(G+te)*(1-Aa)-un[A];un[A]+=W>0?Math.min(q,W):Math.max(-q,W)}}else if(xr){const G=Ea*.4*j;for(let q=0;q<He.length;q++){const V=He[q].lineIdx-un[q];un[q]+=V>0?Math.min(G,V):Math.max(-G,V)}}const L=c.current;L&&(L.timer-=j,L.timer<=0&&(c.current=null));for(let G=0;G<He.length;G++){const q=He[G];if(wn[G]>0){wn[G]-=j;const te=Math.max(0,wn[G]/ja);Xt[G]+=au*te*j,Xt[G]>w&&(Xt[G]-=w)}const A=Sr[G];if(!A)continue;const V=q.lineIdx;for(let te=0;te<2;te++){let W=((q.x*w-D-Xt[G]+te*w)%w+w)%w;const Q=p(Math.max(0,Math.min(Qe-1,Math.round(V))),W,w),E=(V-Math.round(V))*Pn;let F=Q+E;if(L&&L.timer>0){const N=W-L.x,$=F-L.y,M=Math.sqrt(N*N+$*$);if(M<Ta&&M>.1){const O=L.timer/Pa,R=su*(1-M/Ta)*O;W+=N/M*R,F+=$/M*R}}S.drawImage(A.canvas,W-A.ox,F-A.oy)}}n.current=requestAnimationFrame(m)},[p]),f=h.useCallback(g=>{const v=t.current;if(!v)return;const S=v.getBoundingClientRect(),b=g.clientX-S.left,x=g.clientY-S.top,w=S.width,k=r.current;let j=1/0,T=-1;for(let D=0;D<He.length;D++){const C=He[D],G=((C.x*w-k-Xt[D])%w+w)%w,q=p(Math.max(0,Math.min(Qe-1,Math.round(C.lineIdx))),G,w),A=(C.lineIdx-Math.round(C.lineIdx))*Pn,V=q+A,te=G-b,ee=V-x,W=te*te+ee*ee;W<j&&(j=W,T=D)}if(T>=0&&Math.sqrt(j)<ou){wn[T]=ja;const D=He[T],C=iu(D.lineIdx);try{Vt();const L=Xs(),G=zr[L];G!=null&&G.dir&&(En!==L||!u.current?(u.current=!0,du(L).then(()=>La(C))):La(C))}catch{}}c.current={x:b,y:x,timer:Pa}},[p]),y=h.useCallback(g=>{const v=t.current;if(!v)return;const S=v.getBoundingClientRect(),b=g.clientX-S.left,x=g.clientY-S.top;d.current={x:b,y:x},c.current&&c.current.timer>0&&(c.current.x=b,c.current.y=x)},[]);return h.useEffect(()=>(n.current=requestAnimationFrame(m),()=>cancelAnimationFrame(n.current)),[m]),o.jsx("canvas",{ref:t,"aria-hidden":"true",role:"img","aria-label":"Note river animation canvas",onClick:f,onMouseMove:y,style:{display:"block",width:"100%",height:Js,marginBottom:5,cursor:"pointer",background:"transparent"}})}const bu=14,vu=.9,xu=320,Su=160,wu=6,Fa=8,Cu=14,Oa=["♪","♫","♬","𝅘𝅥𝅮","𝅘𝅥𝅯"];function Mu(){const e=h.useRef(null),t=h.useRef([]),n=h.useRef(0),r=h.useRef(0),a=h.useRef([]),s=h.useRef(null),i=h.useRef(0),l=h.useCallback((d,u)=>{for(let p=0;p<bu;p++){const m=Math.random()*Math.PI*2,f=Su*(.4+Math.random()*.6),y=vu*(.6+Math.random()*.4),g=Math.random()<.15?0:-1;t.current.push({x:d,y:u,vx:Math.cos(m)*f,vy:Math.sin(m)*f-60,rot:Math.random()*Math.PI*2,vr:(Math.random()-.5)*wu*2,size:Fa+Math.random()*(Cu-Fa),char:Oa[Math.floor(Math.random()*Oa.length)],life:y,maxLife:y,colorIdx:g})}},[]),c=h.useCallback(d=>{const u=e.current;if(!u){n.current=requestAnimationFrame(c);return}const p=u.getContext("2d");if(!p){n.current=requestAnimationFrame(c);return}const m=window.devicePixelRatio||1,f=window.innerWidth,y=window.innerHeight;(u.width!==Math.round(f*m)||u.height!==Math.round(y*m))&&(u.width=Math.round(f*m),u.height=Math.round(y*m),u.style.width=`${f}px`,u.style.height=`${y}px`,p.setTransform(m,0,0,m,0,0));const g=r.current?Math.min((d-r.current)/1e3,.05):0;r.current=d,p.clearRect(0,0,f,y),i.current++,(!s.current||i.current%60===0)&&(s.current=Zs());const v=s.current;if(navigator.getGamepads){const b=navigator.getGamepads();for(let x=0;x<b.length;x++){const w=b[x];if(w)for(let k=0;k<w.buttons.length;k++){const j=x*100+k,T=w.buttons[k].pressed;T&&!a.current[j]&&l(f/2,y/2),a.current[j]=T}}}const S=[];p.textAlign="center",p.textBaseline="middle";for(const b of t.current){if(b.life-=g,b.life<=0)continue;b.vy+=xu*g,b.x+=b.vx*g,b.y+=b.vy*g,b.rot+=b.vr*g;const x=Math.max(0,b.life/b.maxLife),w=.5+.5*x;p.save(),p.globalAlpha=x,p.translate(b.x,b.y),p.rotate(b.rot),p.font=`${b.size*w}px serif`,p.lineWidth=1.4,p.strokeStyle=v.notesDark?`rgba(255,255,255,${x*.8})`:`rgba(0,0,0,${x*.55})`,p.strokeText(b.char,0,0);const k=b.colorIdx<0?v.base:v.accents[b.colorIdx%v.accents.length];p.fillStyle=k.replace(/[\d.]+\)$/,`${x})`),p.fillText(b.char,0,0),p.restore(),S.push(b)}t.current=S,n.current=requestAnimationFrame(c)},[l]);return h.useEffect(()=>{const d=p=>{l(p.clientX,p.clientY)},u=p=>{if(p.key!=="Enter")return;const m=document.activeElement;if(m){const f=m.getBoundingClientRect();l(f.left+f.width/2,f.top+f.height/2)}else l(window.innerWidth/2,window.innerHeight/2)};return window.addEventListener("click",d,!0),window.addEventListener("keydown",u,!0),n.current=requestAnimationFrame(c),()=>{window.removeEventListener("click",d,!0),window.removeEventListener("keydown",u,!0),cancelAnimationFrame(n.current)}},[c,l]),o.jsx("canvas",{ref:e,"aria-hidden":"true",role:"img","aria-label":"Note particles animation canvas",style:{position:"fixed",inset:0,zIndex:99999,pointerEvents:"none"}})}class Qs{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,r){}midiToFreq(t){return 440*Math.pow(2,(t-69)/12)}playNote(t,n=100,r=1,a="sine"){const s=this.midiToFreq(t),i=this.audioContext.createOscillator(),l=this.audioContext.createGain();i.type=a,i.frequency.value=s;const c=n/127*.8;l.gain.value=c,i.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+r-.05),l.gain.exponentialRampToValueAtTime(.001,d+r),i.start(d),i.stop(d+r),i.onended=()=>{l.disconnect(),i.disconnect()},{osc:i,gain:l}}scheduleNote(t,n,r,a=100,s="sine"){const i=this.midiToFreq(t),l=this.audioContext.createOscillator(),c=this.audioContext.createGain();l.type=s,l.frequency.value=i;const d=a/127*.8;l.connect(c),c.connect(this.masterGain);const u=n;return c.gain.setValueAtTime(0,u),c.gain.linearRampToValueAtTime(d,u+.01),c.gain.exponentialRampToValueAtTime(d*.7,u+.1),c.gain.setValueAtTime(d*.7,u+r-.05),c.gain.exponentialRampToValueAtTime(.001,u+r),l.start(u),l.stop(u+r),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 Da="AudioPlaybackEngine";class ku{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 r=this.midiTracks.get(t);r&&(r.ccEvents=n)}getMidiCCEvents(t){const n=this.midiTracks.get(t);return(n==null?void 0:n.ccEvents)||[]}addMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&(r.ccEvents||(r.ccEvents=[]),r.ccEvents.push(n))}removeMidiCCEvent(t,n){const r=this.midiTracks.get(t);r&&r.ccEvents&&(r.ccEvents=r.ccEvents.filter(a=>a.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){console.error(Da,"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(),r=this.audioContext.createBiquadFilter(),a=this.audioContext.createBiquadFilter();return n.type="lowshelf",n.frequency.value=t.params.lowFreq||250,n.gain.value=t.params.lowGain||0,r.type="peaking",r.frequency.value=1e3,r.Q.value=1,r.gain.value=t.params.midGain||0,a.type="highshelf",a.frequency.value=t.params.highFreq||4e3,a.gain.value=t.params.highGain||0,n.connect(r),r.connect(a),{input:n,output:a}}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 r=this.audioContext.createGain();r.gain.value=t.params.feedback||.3;const a=this.audioContext.createGain();a.gain.value=t.params.mix||.3;const s=this.audioContext.createGain();return s.gain.value=1-(t.params.mix||.3),n.connect(r),r.connect(n),n.connect(a),{input:n,output:a,dry:s,connect:function(i){a.connect(i),s.connect(i)}}}case"reverb":{const n=this.audioContext.createConvolver(),r=this.audioContext.sampleRate*(t.params.decay||2),a=this.audioContext.createBuffer(2,r,this.audioContext.sampleRate);for(let l=0;l<2;l++){const c=a.getChannelData(l);for(let d=0;d<r;d++)c[d]=(Math.random()*2-1)*Math.pow(1-d/r,2)}n.buffer=a;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(s),{input:n,output:s,dry:i,connect:function(l){s.connect(l),i.connect(l)}}}case"distortion":{const n=this.audioContext.createWaveShaper(),r=t.params.amount||20,a=44100,s=new Float32Array(a),i=Math.PI/180;for(let d=0;d<a;d++){const u=d*2/a-1;s[d]=(3+r)*u*20*i/(Math.PI+r*Math.abs(u))}n.curve=s,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(d){l.connect(d),c.connect(d)}}}default:return null}}catch(n){return console.error(Da,"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 r=this.clips.get(t);r&&(Object.assign(r,n),this.updateDuration())}getClipsByLayer(t){return Array.from(this.clips.values()).filter(n=>n.layerId===t)}setMidiTrack(t,n,r="sine",a=.5){if(this.midiTracks.set(t,{layerId:t,notes:n,instrument:r,volume:a}),!this.synths.has(t)&&this.audioContext&&this.masterGain){const s=new Qs(this.audioContext,this.masterGain);s.setVolume(a),this.synths.set(t,s)}}removeMidiTrack(t){this.midiTracks.delete(t);const n=this.synths.get(t);n&&(n.dispose(),this.synths.delete(t))}updateMidiTrackVolume(t,n){const r=this.midiTracks.get(t);r&&(r.volume=n);const a=this.synths.get(t);a&&a.setVolume(n)}updateDuration(){let t=0;this.clips.forEach(n=>{const r=n.startTime+n.duration;r>t&&(t=r)}),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 r=this.audioContext.createBufferSource();r.buffer=t.buffer,t.stretchFactor&&t.stretchFactor!==1&&(r.playbackRate.value=1/t.stretchFactor);const a=this.audioContext.createGain();a.gain.value=t.volume;const s=this.audioContext.createStereoPanner();s.pan.value=t.pan,r.connect(a);let i=a;if(t.effectChain&&t.effectChain.length>0)for(const u of t.effectChain){const p=this.createEffectNode(u);if(p)if("input"in p&&"output"in p){const m=p;i.connect(m.input),i=m.output,"dry"in p&&a.connect(m.dry)}else i.connect(p),i=p}i.connect(s),s.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&&(r.start(d,t.offset+c,t.duration-c),this.scheduledSources.set(t.id,r),r.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(r=>{if(r.start+r.duration<=this.currentTime)return;const s=Math.max(0,this.currentTime-r.start),i=this.audioContext.currentTime+(r.start-this.currentTime);i>=this.audioContext.currentTime&&n.scheduleNote(r.pitch,i,r.duration-s,r.velocity,t.instrument)}),t.ccEvents&&Array.isArray(t.ccEvents)&&t.ccEvents.length>0)){const r=[...t.ccEvents].sort((i,l)=>i.time-l.time);let s=r[0];for(let i=1;i<r.length;++i){const l=r[i],c=s.time,d=l.time,u=s.value,p=l.value,m=s.handleType||"linear",f=Math.max(2,Math.ceil((d-c)*20));for(let y=0;y<=f;++y){const g=y/f;let v=u;if(m==="linear")v=u+(p-u)*g;else if(m==="step")v=g<1?u:p;else if(m==="exp"){const w=Math.max(u/127,.001),k=Math.max(p/127,.001);v=w*Math.pow(k/w,g)*127}const S=c+(d-c)*g,b=this.audioContext.currentTime+(S-this.currentTime);b>=this.audioContext.currentTime&&typeof n.applyCC=="function"&&n.applyCC(l.cc,v,b)}s=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,r){this.loopRegion={start:t,end:n,enabled:r}}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 $u=[{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 Zn(e={}){const{channelFilter:t,sysex:n=!1,onEvent:r,inputNameIncludes:a,onInputsChanged:s}=e,[i,l]=h.useState(null),[c,d]=h.useState(!1),[u,p]=h.useState([]),m=h.useRef(null),f=h.useCallback((y,g)=>{const v=y.data??new Uint8Array(0),S=v[0]??0,b=v[1]??0,x=v[2]??0,w=y.timeStamp,k=S&240,j=S&15,T=g.id,D=g.name??"MIDI Input",C=t===void 0||t===j;if((k===144||k===128)&&C){const L=k===144&&x>0;return{type:L?"noteon":"noteoff",note:b,velocity:L?x:0,channel:j,ts:w,deviceId:T,deviceName:D}}return k===176&&C?{type:"cc",controller:b,value:x,channel:j,ts:w,deviceId:T,deviceName:D}:k===208&&C?{type:"aftertouch",pressure:b,channel:j,ts:w,deviceId:T,deviceName:D}:k===224&&C?{type:"pitchbend",value:(b|x<<7)-8192,channel:j,ts:w,deviceId:T,deviceName:D}:k===192&&C?{type:"program",program:b,channel:j,ts:w,deviceId:T,deviceName:D}:{type:"unknown",status:S,data1:b,data2:x,channel:j,ts:w,deviceId:T,deviceName:D}},[t]);return h.useEffect(()=>{if(!("requestMIDIAccess"in navigator)){l(!1);return}l(!0);let y=!1;return navigator.requestMIDIAccess({sysex:n}).then(g=>{if(y)return;m.current=g,d(!0);const v=()=>{const S=Array.from(g.inputs.values()),b=a?S.filter(x=>(x.name||"").toUpperCase().includes(a.toUpperCase())):S;p(b),s==null||s(b),S.forEach(x=>x.onmidimessage=null),b.forEach(x=>{x.onmidimessage=w=>r==null?void 0:r(f(w,x))})};v(),g.onstatechange=()=>v()}),()=>{y=!0;const g=m.current;g&&(g.inputs.forEach(v=>v.onmidimessage=null),g.onstatechange=null)}},[a,r,s,f,n]),{supported:i,granted:c,inputs:u}}const Wr="nice2dev.midiLearn";function Ru(){try{const e=localStorage.getItem(Wr);return e?JSON.parse(e):{}}catch{return{}}}function Ga(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(Wr,JSON.stringify(t))}function ju(e){const{parameters:t,onParameterChange:n}=e,[r,a]=h.useState(()=>{const x=Ru();return t.map(w=>{const k=x[w.id];return{id:w.id,paramName:w.name,type:(k==null?void 0:k.type)??"cc",number:k==null?void 0:k.number,channel:k==null?void 0:k.channel,min:(k==null?void 0:k.min)??w.min??0,max:(k==null?void 0:k.max)??w.max??127,value:0}})}),[s,i]=h.useState({learning:!1,targetId:null}),[l,c]=h.useState(null),d=h.useRef(r);d.current=r;const u=h.useRef(n);u.current=n;const p=h.useRef(s);p.current=s;const m=h.useCallback(x=>{var k;c(x);const w=p.current;if(w.learning&&w.targetId){if(!d.current.find(D=>D.id===w.targetId))return;let T={};switch(x.type){case"cc":T={type:"cc",number:x.controller,channel:x.channel};break;case"noteon":T={type:"note",number:x.note,channel:x.channel};break;case"pitchbend":T={type:"pitchbend",channel:x.channel};break;case"aftertouch":T={type:"aftertouch",channel:x.channel};break;default:return}a(D=>{const C=D.map(L=>L.id===w.targetId?{...L,...T}:L);return Ga(C),C}),i({learning:!1,targetId:null});return}for(const j of d.current){if(j.number===void 0&&j.type!=="pitchbend"&&j.type!=="aftertouch"||j.channel!==void 0&&x.channel!==j.channel)continue;let T=null,D=127;if(j.type==="cc"&&x.type==="cc"&&x.controller===j.number?T=x.value:j.type==="note"&&x.type==="noteon"&&x.note===j.number?T=x.velocity:j.type==="pitchbend"&&x.type==="pitchbend"?(T=x.value+8192,D=16383):j.type==="aftertouch"&&x.type==="aftertouch"&&(T=x.pressure),T!==null){const C=T/D,L=j.min+C*(j.max-j.min);a(G=>G.map(q=>q.id===j.id?{...q,value:C}:q)),(k=u.current)==null||k.call(u,j.id,L,C)}}},[]),{supported:f,granted:y}=Zn({onEvent:m}),g=h.useCallback(x=>{i({learning:!0,targetId:x})},[]),v=h.useCallback(()=>{i({learning:!1,targetId:null})},[]),S=h.useCallback(x=>{a(w=>{const k=w.map(j=>j.id===x?{...j,type:"cc",number:void 0,channel:void 0}:j);return Ga(k),k})},[]),b=h.useCallback(()=>{a(x=>{const w=x.map(k=>({...k,type:"cc",number:void 0,channel:void 0,value:0}));return localStorage.removeItem(Wr),w})},[]);return{bindings:r,startLearn:g,cancelLearn:v,removeBinding:S,clearAll:b,learnState:s,midiSupported:f,midiGranted:y,lastEvent:l}}const Tu={masterChannel:0,memberChannels:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],pitchBendRange:48};function Pu(e={}){const{lowerZone:t=Tu,onNoteExpression:n,onNoteOn:r,onNoteOff:a}=e,[s,i]=h.useState([]),l=h.useRef(new Map),c=h.useRef(n);c.current=n;const d=h.useRef(r);d.current=r;const u=h.useRef(a);u.current=a;const p=h.useRef(new Set(t.memberChannels));h.useEffect(()=>{p.current=new Set(t.memberChannels)},[t.memberChannels]);const m=h.useCallback(g=>{var S,b,x,w,k;if(!p.current.has(g.channel??-1))return;const v=`${g.channel}`;switch(g.type){case"noteon":{const j={note:g.note,channel:g.channel,velocity:g.velocity,pitchBend:0,pressure:0,slide:0,lastUpdate:g.ts};l.current.set(v,j),i(Array.from(l.current.values())),(S=d.current)==null||S.call(d,j);break}case"noteoff":{l.current.delete(v),i(Array.from(l.current.values())),(b=u.current)==null||b.call(u,g.channel,g.note);break}case"pitchbend":{const j=l.current.get(v);j&&(j.pitchBend=g.value,j.lastUpdate=g.ts,(x=c.current)==null||x.call(c,j),i(Array.from(l.current.values())));break}case"aftertouch":{const j=l.current.get(v);j&&(j.pressure=g.pressure,j.lastUpdate=g.ts,(w=c.current)==null||w.call(c,j),i(Array.from(l.current.values())));break}case"cc":{if(g.controller===74){const j=l.current.get(v);j&&(j.slide=g.value,j.lastUpdate=g.ts,(k=c.current)==null||k.call(c,j),i(Array.from(l.current.values())))}break}}},[]),{supported:f,granted:y}=Zn({onEvent:m,sysex:!1});return{activeNotes:s,midiSupported:f,midiGranted:y}}const Eu={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 Au(e={},t=Eu){const[n,r]=h.useState(()=>{const f=localStorage.getItem("oxygen25.layout");return f?JSON.parse(f):t}),[a,s]=h.useState([]),i=h.useRef({mode:"idle"}),l=h.useCallback(f=>{r(y=>{const g={...y,...f};return localStorage.setItem("oxygen25.layout",JSON.stringify(g)),g})},[]),c=h.useCallback(f=>{var v,S,b,x,w,k,j,T,D;const y=f.deviceName||"MIDI";s(C=>C.includes(y)?C:[...C,y]);const g=i.current;if(g.mode!=="idle"){if(g.mode==="knob"&&f.type==="cc"){const C=g.index;l({knobs:n.knobs.map(L=>L.index===C?{...L,cc:f.controller}:L)}),i.current={mode:"idle"};return}if(g.mode==="fader"&&f.type==="cc"){l({fader:{cc:f.controller,label:"Fader"}}),i.current={mode:"idle"};return}if(g.mode==="pad"&&f.type==="noteon"){const C=n.pads.slice();C[g.padIdx]={...C[g.padIdx],note:f.note},l({pads:C}),i.current={mode:"idle"};return}if(g.mode==="transport"&&f.type==="cc"){const C={...n.transport};C[g.action]=f.controller,l({transport:C}),i.current={mode:"idle"};return}}switch(f.type){case"noteon":{n.pads.findIndex(L=>L.note===f.note)>=0?(v=e.onPad)==null||v.call(e,{note:f.note,velocity:f.velocity,ts:f.ts,device:y}):(S=e.onKey)==null||S.call(e,{note:f.note,velocity:f.velocity,ts:f.ts,device:y});break}case"cc":{if(n.fader&&f.controller===n.fader.cc){(b=e.onFader)==null||b.call(e,{cc:f.controller,value:f.value,ts:f.ts,device:y});break}const C=n.knobs.find(G=>G.cc===f.controller);if(C){(x=e.onKnob)==null||x.call(e,{index:C.index,cc:f.controller,value:f.value,ts:f.ts,device:y});break}const L=Object.keys(n.transport).find(G=>n.transport[G]===f.controller);if(L){(w=e.onTransport)==null||w.call(e,{action:L,value:f.value,ts:f.ts,device:y});break}(k=e.onUnknown)==null||k.call(e,f);break}case"pitchbend":(j=e.onPitchBend)==null||j.call(e,{value:f.value,ts:f.ts,device:y});break;case"aftertouch":(T=e.onAftertouch)==null||T.call(e,{pressure:f.pressure,ts:f.ts,device:y});break;default:(D=e.onUnknown)==null||D.call(e,f)}},[l,e,n]),{supported:d,granted:u,inputs:p}=Zn({inputNameIncludes:void 0,onEvent:c,sysex:!1,channelFilter:void 0,onInputsChanged:f=>s(f.map(y=>y.name||"MIDI"))}),m=h.useMemo(()=>({knob:f=>i.current={mode:"knob",index:f},fader:()=>i.current={mode:"fader"},pad:f=>i.current={mode:"pad",padIdx:f},transport:f=>i.current={mode:"transport",action:f},cancel:()=>i.current={mode:"idle"},state:()=>i.current}),[]);return{supported:d,granted:u,inputs:p,layout:n,setLayout:l,learn:m,inputsInfo:a}}const wr={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]},Lu=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],Cr={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]]},Tt=36,Jt=38,nt=42,Pt=51,Nu=49,Mr={basic:[{step:0,pitch:Tt,vel:110},{step:0,pitch:nt,vel:80},{step:2,pitch:nt,vel:70},{step:4,pitch:Jt,vel:100},{step:4,pitch:nt,vel:80},{step:6,pitch:nt,vel:70},{step:8,pitch:Tt,vel:100},{step:10,pitch:nt,vel:70},{step:12,pitch:Jt,vel:100},{step:12,pitch:nt,vel:80},{step:14,pitch:nt,vel:70}],rock:[{step:0,pitch:Tt,vel:120},{step:0,pitch:Nu,vel:90},{step:4,pitch:Jt,vel:110},{step:4,pitch:nt,vel:80},{step:8,pitch:Tt,vel:110},{step:8,pitch:nt,vel:80},{step:10,pitch:Tt,vel:90},{step:12,pitch:Jt,vel:110},{step:12,pitch:nt,vel:80}],swing:[{step:0,pitch:Pt,vel:90},{step:3,pitch:Pt,vel:70},{step:4,pitch:Pt,vel:80},{step:8,pitch:Pt,vel:90},{step:11,pitch:Pt,vel:70},{step:12,pitch:Pt,vel:80},{step:4,pitch:Tt,vel:80},{step:12,pitch:Jt,vel:70}]},eo={root:0,scale:"pentatonic",tempo:120,bars:8,progression:"pop",drumPattern:"basic",density:.5,octave:4,seed:0};function Iu(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 to=1;const Cn=()=>to++,no=e=>60/e,Fu=e=>no(e)/4;function lr(e,t,n,r){const a=t.length,s=Math.floor(n/a),i=(n%a+a)%a;return e+t[i]+(r+s)*12}function Ou(e=eo){to=1;const t=e.seed>0?Iu(e.seed):Math.random,n=wr[e.scale]??wr.pentatonic,r=Cr[e.progression]??Cr.pop,a=Mr[e.drumPattern]??Mr.basic,s=no(e.tempo),i=Fu(e.tempo),l=Math.max(1,e.bars),c=16,d=[],u=[],p=[],m=[];let f=0;for(let y=0;y<l;y++){const g=y*4*s,v=y%r.length,S=r[v];for(const x of S)p.push({id:Cn(),pitch:lr(e.root,n,x,e.octave-1),start:g,duration:4*s-.01,velocity:70+Math.floor(t()*20)});const b=S[0];for(let x=0;x<4;x++){const w=x===2?b+(t()>.5?2:0):b;u.push({id:Cn(),pitch:lr(e.root,n,w,e.octave-2),start:g+x*s,duration:s*.9,velocity:80+Math.floor(t()*30)})}for(let x=0;x<c;x++){if(t()>e.density)continue;const w=g+x*i,k=t()>.8?t()>.5?2:-2:t()>.5?1:-1;f=Math.max(-3,Math.min(n.length+3,f+k));const j=1+Math.floor(t()*3);d.push({id:Cn(),pitch:lr(e.root,n,f,e.octave),start:w,duration:j*i*.95,velocity:85+Math.floor(t()*30)})}for(const x of a)m.push({id:Cn(),pitch:x.pitch,start:g+x.step*i,duration:i*.8,velocity:x.vel+Math.floor(t()*10-5)})}return{melody:d,bass:u,chords:p,drums:m,config:e}}const Du=Object.keys(wr),Gu=Object.keys(Cr),_u=Object.keys(Mr);function ro(e){return{past:[],present:e,future:[]}}function ao(e,t){return{past:[...e.past.slice(-99),e.present],present:t,future:[]}}function so(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 oo(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 io(e){return e.past.length>0}function lo(e){return e.future.length>0}function kr(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>({...n}))}function co(e,t,n){if(t.length===0)return e;const r=Math.min(...t.map(i=>i.time)),a=n-r,s=t.map(i=>({...i,id:Date.now()+Math.floor(Math.random()*1e4)+i.id,time:i.time+a}));return[...e,...s]}function uo(e,t){const n=[],r=[];for(const a of e)a.time>=t.start&&a.time<=t.end?n.push({...a}):r.push(a);return{remaining:r,cut:n}}function ho(e,t){return e.filter(n=>n.time<t.start||n.time>t.end)}function Bu(e,t){return e.filter(n=>n.time>=t.start&&n.time<=t.end).map(n=>n.id)}function fo(e,t,n,r){const a={id:Date.now()+Math.floor(Math.random()*1e4),cc:t,value:n,time:r};return[...e,a]}function po(e,t=3){if(e.length<=2)return e;const n=[...e].sort((a,s)=>a.time-s.time),r=[n[0]];for(let a=1;a<n.length-1;a++)a%t===0&&r.push(n[a]);return r.push(n[n.length-1]),r}function mo(e){return JSON.stringify(e,null,2)}function go(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 Ze(e,t){var n;return((n=e.find(r=>r.layerId===t))==null?void 0:n.events)??[]}function rt(e,t,n){return e.find(a=>a.layerId===t)?e.map(a=>a.layerId===t?{...a,events:n}:a):[...e,{layerId:t,events:n}]}function zu(e,t){switch(t.type){case"UNDO":return so(e);case"REDO":return oo(e);default:{let n=e.present;switch(t.type){case"ADD_EVENT":{const r=[...Ze(n,t.layerId),t.event];n=rt(n,t.layerId,r);break}case"UPDATE_EVENT":{const r=Ze(n,t.layerId).map(a=>a.id===t.id?{...a,value:t.value,time:t.time,handleType:t.handleType??a.handleType}:a);n=rt(n,t.layerId,r);break}case"REMOVE_EVENT":{const r=Ze(n,t.layerId).filter(a=>a.id!==t.id);n=rt(n,t.layerId,r);break}case"SET_EVENTS":n=rt(n,t.layerId,t.events);break;case"PASTE":{const r=Ze(n,t.layerId),a=co(r,t.clipboard,t.targetTime);n=rt(n,t.layerId,a);break}case"CUT":{const r=Ze(n,t.layerId),{remaining:a}=uo(r,t.range);n=rt(n,t.layerId,a);break}case"DELETE_RANGE":{const r=Ze(n,t.layerId),a=ho(r,t.range);n=rt(n,t.layerId,a);break}case"RECORD":{const r=Ze(n,t.layerId),a=fo(r,t.cc,t.value,t.time);n=rt(n,t.layerId,a);break}case"THIN":{const r=Ze(n,t.layerId),a=po(r,t.keepEveryN);n=rt(n,t.layerId,a);break}case"IMPORT":{const r=go(t.json);r.length>0&&(n=rt(n,t.layerId,r));break}}return ao(e,n)}}}function Wu(e=[]){const[t,n]=h.useReducer(zu,ro(e)),r=h.useRef([]),a=h.useCallback(x=>Ze(t.present,x),[t.present]),s=h.useCallback((x,w)=>n({type:"ADD_EVENT",layerId:x,event:w}),[]),i=h.useCallback((x,w,k,j,T)=>n({type:"UPDATE_EVENT",layerId:x,id:w,value:k,time:j,handleType:T}),[]),l=h.useCallback((x,w)=>n({type:"REMOVE_EVENT",layerId:x,id:w}),[]),c=h.useCallback((x,w)=>n({type:"SET_EVENTS",layerId:x,events:w}),[]),d=h.useCallback(()=>n({type:"UNDO"}),[]),u=h.useCallback(()=>n({type:"REDO"}),[]),p=h.useCallback((x,w)=>{r.current=kr(Ze(t.present,x),w)},[t.present]),m=h.useCallback((x,w)=>{r.current=kr(Ze(t.present,x),w),n({type:"CUT",layerId:x,range:w})},[t.present]),f=h.useCallback((x,w)=>{r.current.length>0&&n({type:"PASTE",layerId:x,clipboard:r.current,targetTime:w})},[]),y=h.useCallback((x,w)=>n({type:"DELETE_RANGE",layerId:x,range:w}),[]),g=h.useCallback((x,w,k,j)=>n({type:"RECORD",layerId:x,cc:w,value:k,time:j}),[]),v=h.useCallback((x,w)=>n({type:"THIN",layerId:x,keepEveryN:w}),[]),S=h.useCallback(x=>mo(Ze(t.present,x)),[t.present]),b=h.useCallback((x,w)=>n({type:"IMPORT",layerId:x,json:w}),[]);return{snapshots:t.present,getEvents:a,addEvent:s,updateEvent:i,removeEvent:l,setEvents:c,undo:d,redo:u,canUndo:io(t),canRedo:lo(t),copy:p,cut:m,paste:f,clipboard:r.current,deleteRange:y,record:g,thin:v,exportLane:S,importLane:b}}function Ur(e=60){return{active:!1,note:e,velocity:100,gate:.8,probability:1,slide:!1}}function St(e="New Pattern",t=16,n=120){return{name:e,length:t,steps:Array.from({length:t},()=>Ur()),bpm:n,swing:0,rootNote:60}}function yo(e,t){const n=e.steps.map((r,a)=>a===t?{...r,active:!r.active}:r);return{...e,steps:n}}function bo(e,t,n){const r=e.steps.map((a,s)=>s===t?{...a,note:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function vo(e,t,n){const r=e.steps.map((a,s)=>s===t?{...a,velocity:Math.max(0,Math.min(127,n))}:a);return{...e,steps:r}}function xo(e,t,n){const r=e.steps.map((a,s)=>s===t?{...a,gate:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function So(e,t,n){const r=e.steps.map((a,s)=>s===t?{...a,probability:Math.max(0,Math.min(1,n))}:a);return{...e,steps:r}}function wo(e,t){const n=e.steps.map((r,a)=>a===t?{...r,slide:!r.slide}:r);return{...e,steps:n}}function Co(e,t){const n=e.steps.map(r=>r.active?{...r,note:Math.max(0,Math.min(127,r.note+t))}:r);return{...e,steps:n,rootNote:Math.max(0,Math.min(127,e.rootNote+t))}}function Mo(e){return{...e,steps:[...e.steps].reverse()}}function ko(e,t){const n=e.steps.length,r=(t%n+n)%n,a=[...e.steps.slice(r),...e.steps.slice(0,r)];return{...e,steps:a}}function $o(e,t=60,n=127){const r=e.steps.map(a=>a.active?{...a,velocity:Math.floor(t+Math.random()*(n-t+1))}:a);return{...e,steps:r}}function Ro(e){return{...e,steps:e.steps.map(()=>Ur(e.rootNote))}}function qr(e,t=4){return 60/e/t}function jo(e,t,n=0,r=4){const a=qr(t,r),s=e*a;return e%2===1&&n>0?s+a*n*.5:s}function To(e){return e.active&&Math.random()<e.probability}function Uu(){const e=St("Kick",16);return[0,4,8,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:36,velocity:110}}),e}function qu(){const e=St("Snare",16);return[4,12].forEach(t=>{e.steps[t]={...e.steps[t],active:!0,note:38,velocity:100}}),e}function Vu(){const e=St("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 Ku(e=60){const t=St("Arp",16,120);return[0,4,7,12,7,4,0,-5,0,3,7,12,7,3,0,-5].forEach((r,a)=>{t.steps[a]={...t.steps[a],active:!0,note:e+r,velocity:90,gate:.5}}),{...t,rootNote:e}}function Hu(e=36){const t=St("Bassline",16,120),n=[0,0,7,0,5,5,3,0,0,0,7,12,5,5,3,0],r=[1,0,1,0,1,0,1,1,1,0,1,1,1,0,1,0];return n.forEach((a,s)=>{t.steps[s]={...t.steps[s],active:!!r[s],note:e+a,velocity:100,gate:.7}}),{...t,rootNote:e}}function Yu(e){return JSON.stringify(e,null,2)}function Zu(e){try{const t=JSON.parse(e);return!t||!Array.isArray(t.steps)?null:t}catch{return null}}function Xu(e={}){const{onTrigger:t,onLFOOutput:n,initialPattern:r}=e,[a,s]=h.useState(()=>r??St()),[i,l]=h.useState(-1),[c,d]=h.useState(!1),[u,p]=h.useState([]),m=h.useRef(a);m.current=a;const f=h.useRef(u);f.current=u;const y=h.useRef(c);y.current=c;const g=h.useRef(t);g.current=t;const v=h.useRef(n);v.current=n;const S=h.useRef(null),b=h.useRef(0),x=h.useRef(0),w=h.useCallback(()=>{var H,ae;if(!y.current)return;const R=m.current,_=b.current%R.length,I=R.steps[_];if(To(I)){const le=jo(b.current,R.bpm,R.swing);(H=g.current)==null||H.call(g,I,_,le)}const B=(Date.now()-x.current)/1e3;for(let le=0;le<f.current.length;le++){const ne=f.current[le];if(ne.enabled&&ne.targetCC!==void 0){const X=jr(ne,B,R.bpm);(ae=v.current)==null||ae.call(v,le,ne.targetCC,X)}}l(_),b.current++;const Z=qr(R.bpm)*1e3,z=_%2===0?0:Z*R.swing*.5;S.current=setTimeout(w,Z+z)},[]),k=h.useCallback(()=>{y.current||(b.current=0,x.current=Date.now(),d(!0),y.current=!0,w())},[w]),j=h.useCallback(()=>{d(!1),y.current=!1,l(-1),S.current&&(clearTimeout(S.current),S.current=null)},[]),T=h.useCallback(()=>{y.current?j():k()},[k,j]);h.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const D=h.useCallback(R=>s(_=>yo(_,R)),[]),C=h.useCallback((R,_)=>s(I=>bo(I,R,_)),[]),L=h.useCallback((R,_)=>s(I=>vo(I,R,_)),[]),G=h.useCallback((R,_)=>s(I=>xo(I,R,_)),[]),q=h.useCallback((R,_)=>s(I=>So(I,R,_)),[]),A=h.useCallback(R=>s(_=>wo(_,R)),[]),V=h.useCallback(R=>s(_=>Co(_,R)),[]),te=h.useCallback(()=>s(R=>Mo(R)),[]),ee=h.useCallback(R=>s(_=>ko(_,R)),[]),W=h.useCallback((R,_)=>s(I=>$o(I,R,_)),[]),Q=h.useCallback(()=>s(R=>Ro(R)),[]),E=h.useCallback(R=>s(_=>({..._,bpm:Math.max(20,Math.min(300,R))})),[]),F=h.useCallback(R=>s(_=>({..._,swing:Math.max(0,Math.min(1,R))})),[]),N=h.useCallback(R=>{s(_=>{if(_.length===R)return _;const I=Array.from({length:R},(B,Z)=>Z<_.steps.length?_.steps[Z]:{active:!1,note:_.rootNote,velocity:100,gate:.8,probability:1,slide:!1});return{..._,length:R,steps:I}})},[]),$=h.useCallback(R=>{p(_=>[..._,R??Wn()])},[]),M=h.useCallback(R=>{p(_=>_.filter((I,B)=>B!==R))},[]),O=h.useCallback((R,_)=>{p(I=>I.map((B,Z)=>Z===R?{...B,..._}:B))},[]);return{pattern:a,currentStep:i,playing:c,lfos:u,play:k,stop:j,togglePlayback:T,toggle:D,setNote:C,setVelocity:L,setGate:G,setProbability:q,toggleSlide:A,transpose:V,reverse:te,shift:ee,randomizeVel:W,clear:Q,setPattern:s,setBpm:E,setSwing:F,setLength:N,addLFO:$,removeLFO:M,updateLFO:O}}function Vr(e){const t=h.useRef(null),n=h.useRef(new Map),r=h.useRef(1),a=h.useCallback(()=>{if(!t.current){const i=e();i.onmessage=l=>{const{id:c}=l.data,d=n.current.get(c);d&&(n.current.delete(c),d(l.data))},t.current=i}return t.current},[e]);return h.useEffect(()=>()=>{var i;(i=t.current)==null||i.terminate(),t.current=null,n.current.clear()},[]),h.useCallback((i,l)=>{const c=r.current++,d=a();return new Promise(u=>{n.current.set(c,u),d.postMessage({...i,id:c},l??[])})},[a])}function Ju(){const e=Vr(h.useCallback(()=>new Worker(new URL("/assets/pitchWorker-BgAp5Z97.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:lt&&lt.tagName.toUpperCase()==="SCRIPT"&&lt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return h.useCallback(async(n,r,a=.01)=>(await e({buffer:n,sampleRate:r,rmsThreshold:a})).hz,[e])}function Qu(){const e=Vr(h.useCallback(()=>new Worker(new URL("/assets/scoringWorker-B1PkYu_m.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:lt&&lt.tagName.toUpperCase()==="SCRIPT"&&lt.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),[]));return h.useCallback(async(n,r,a)=>(await e({notes:n,points:r,params:a})).result,[e])}function Po(e){return e>=.95?"Perfect":e>=.8?"Great":e>=.6?"Good":e>=.4?"OK":e>=.2?"Bad":"Awful"}function Eo(e){return e>=50?3:e>=30?2.5:e>=20?2:e>=10?1.5:1}function eh(e,t,n){const{semitoneTolerance:r,preWindow:a,postExtra:s}=n,i=n.segMs??.25,l=typeof n.completionBonusFactor=="number"?n.completionBonusFactor:.15,c=typeof n.goldFullBonusFactor=="number"?n.goldFullBonusFactor:.3,d=typeof n.difficultyMult=="number"?n.difficultyMult:1,u=!!n.disableGoldNotes;let p=0,m=0,f=0;const y=[];let g=0,v=0,S=0;const b=new Map;e.forEach((C,L)=>{const G=C.startTime,q=C.startTime+C.duration,A=G-a,V=q+s,te=t.filter(M=>M.t>=A&&M.t<=V&&M.hz>0);if(!te||te.length===0)return;const ee=Math.max(1,Math.ceil((C.duration||.25)/i)),W=Math.max(10,Math.round(100*(C.duration||1))),Q=Math.max(1,Math.round(W/ee));let E=0;const F=[];for(let M=0;M<ee;M++){const O=G+M*(C.duration/ee),R=G+(M+1)*(C.duration/ee),_=Math.min(.06,C.duration/ee*.2),I=O-_,B=R+_,Z=t.filter(X=>X.t>=I&&X.t<=B&&X.hz>0);if(!Z||Z.length===0)continue;let z=0;Z.forEach(X=>{let J=((12*Math.log2(X.hz/440)+69)%12+12)%12;for(;J-C.pitch>6;)J-=12;for(;J-C.pitch<-6;)J+=12;const oe=Math.abs(J-C.pitch);z+=oe});const H=z/Z.length;let ae=0;if(r<=0)ae=H===0?1:0;else{const X=r*2;ae=Math.max(0,1-Math.min(H/X,1))}if(ae<=0)continue;const le=!u&&C.isGold?2:1,ne=Math.round(Q*le*ae);ne>0&&(p+=ne,E+=ne,F.push({segIndex:M,frac:ae,add:ne,segStart:I,segEnd:B,visualStart:O,visualEnd:R}))}const N=C.line??0;b.has(N)||b.set(N,{total:0,hit:0,comboBonus:0});const $=b.get(N);if($.total++,E>0){g++,g>v&&(v=g),$.hit++;const M=Eo(g),O=M>1?Math.round(E*(M-1)):0;S+=O,$.comboBonus+=O;const R=Math.max(1,Math.ceil((C.duration||.25)/i)),I=F.length>=R,B=I?Math.round(Math.max(10,Math.round(100*(C.duration||1)))*l*(!u&&C.isGold?1.5:1)*d):0,Z=I&&!u&&C.isGold?Math.round(Math.max(10,Math.round(100*(C.duration||1)))*c*d):0;m+=B,f+=Z,y.push({noteKey:`${C.line??0}-${C.idx??0}`,segments:F,totalAdded:E,completed:I,completionBonus:B,goldFullBonus:Z})}else g=0});const x=[];for(const[C,L]of b.entries()){const G=L.total>0?L.hit/L.total:0;x.push({verseIndex:C,hitFraction:G,label:Po(G),comboBonus:L.comboBonus})}const w={maxCombo:v,currentCombo:0,totalComboBonus:S},k=S+m+f,j=y.length,T=y.filter(C=>C.completed).length,D={hits:j,misses:e.length-j,good:j-T,perfect:T,maxCombo:v};return{classicScore:p,bonusScore:k,totalScore:p+k,total:p,perNote:y,combo:w,verseRatings:x,noteStats:D}}function Ao(e,t){let n=0;for(const r of e){const a=Math.max(10,Math.round(100*(r.duration||1))),s=!t&&r.isGold?2:1;n+=a*s}return n}function Lo(e,t){return t<=0?0:Math.min(1e4,Math.round(e/t*1e4))}function th(e,t,n){const r=Ao(t,n);if(r<=0)return{...e,classicScore:0,bonusScore:0,totalScore:0,total:0};const a=Lo(e.classicScore,r),s=Math.round(e.bonusScore/r*1e4);return{...e,classicScore:a,bonusScore:s,totalScore:a+s,total:a}}function No(e){const t={};if(!e)return t;const n=e.split(",");for(const r of n){const a=r.trim();a.startsWith("v=")?t.youtubeId=a.substring(2):a.startsWith("co=")?t.coverImage=a.substring(3):a.startsWith("bg=")&&(t.backgroundImage=a.substring(3))}return t}function nh(e,t="/api/karaoke/cover"){var r,a;const n=((r=e.coverImage)==null?void 0:r.startsWith("http://"))||((a=e.coverImage)==null?void 0:a.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 rh(e,t="/backgrounds"){return e.backgroundImage?`${t}/${e.backgroundImage}`:""}function ah(e,t,n=.01){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*e[i];if(r=Math.sqrt(r/e.length),r<n)return 0;let a=-1,s=0;for(let i=20;i<e.length/2;i++){let l=0;for(let c=0;c<e.length/2;c++)l+=e[c]*e[c+i];l/=e.length/2,l>s&&(s=l,a=i)}return a>0?t/a:0}function sh(e,t){const n=[];return e.forEach((r,a)=>{r.forEach((s,i)=>{n.push({startTime:s.startTime+t,duration:s.duration,pitch:s.pitch,isGold:s.isGold,line:a,idx:i})})}),n}function oh(e,t,n){const r=[];return e.forEach(a=>{var c;const[s,i]=a.noteKey.split("-").map(Number),l=(c=t[s])==null?void 0:c[i];l&&a.segments.forEach(d=>{r.push({start:d.visualStart-n,end:d.visualEnd-n,pitch:l.pitch,frac:d.frac,isGold:l.isGold,noteStart:l.startTime,noteEnd:l.startTime+l.duration})})}),r}function ih(e,t=120){let n=e;if(e.length>t){const r=e.length/t,a=[];for(let s=0;s<t;s++)a.push(e[Math.floor(s*r)]);n=a}return n.map(r=>({t:Math.round(r.t*1e3)/1e3,hz:Math.round(r.hz)}))}function lh(e,t,n){const a=Date.parse(e)-n;return Math.max(0,Math.round(t-a))}const Io={crepe:"#a78bfa",librosa:"#34d399",pitchy:"#60a5fa",autocorr:"#555555"};function ch(e){return e==="autocorr"?"Ultrastar":e.charAt(0).toUpperCase()+e.slice(1)}function dh(e){return Io[e]??"#555555"}function uh(e){const t=Io[e]??"#555555";return`var(--algo-${e}, ${t})`}function hh(e,t){const n=!(t!=null&&t.includes("no-music")),r=t==null?void 0:t.includes("instrumental"),a=[];if(n){if(e.videoPath){let s=e.videoPath;if(s.startsWith("v=")){const i=No(s);i.youtubeId&&(s=`https://www.youtube.com/watch?v=${i.youtubeId}`)}/youtu(\.be|be\.com)/i.test(s)?a.push({kind:"youtube",url:s}):/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(e.videoPath)&&a.push({kind:"audio",url:e.videoPath})}if(a.length===0){const s=r?e.instrumentalPath:e.audioPath;s&&/^(https?:\/\/|blob:|data:\/\/|\/)/i.test(s)&&a.push({kind:"audio",url:s})}a.length===0&&e.youtubeId&&a.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:a}}function fh(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}}function ph(e,t,n){const s={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(i=>{var l;return{...i,[t]:{...i[t],effectChain:[...((l=i[t])==null?void 0:l.effectChain)||[],s]}}})}function mh(e,t,n){e(r=>{var a,s;return{...r,[t]:{...r[t],effectChain:((s=(a=r[t])==null?void 0:a.effectChain)==null?void 0:s.filter(i=>i.id!==n))||[]}}})}function gh(e,t,n){e(r=>{var a,s;return{...r,[t]:{...r[t],effectChain:((s=(a=r[t])==null?void 0:a.effectChain)==null?void 0:s.map(i=>i.id===n?{...i,bypass:!i.bypass}:i))||[]}}})}function yh(e,t,n,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(l=>l.id===n?{...l,params:{...l.params,...r}}:l))||[]}}})}function bh(e,t,n,r,a,s,i=.5,l=100){const c={id:Date.now()+Math.floor(Math.random()*1e3),pitch:a,start:s,duration:i,velocity:l};t(d=>({...d,[r]:[...d[r]||[],c]})),n({layerId:r,noteId:c.id})}function vh(e,t,n,r){e(a=>({...a,[n]:(a[n]||[]).filter(s=>s.id!==r)})),t(null)}function xh(e,t,n){e(r=>({...r,[n]:[]})),t(null)}function Sh(e,t,n){e(r=>({...r,[t]:n}))}function wh(e,t,n,r,a){const s={id:Date.now()+Math.floor(Math.random()*1e3),cc:n,value:r,time:a};e(i=>({...i,[t]:[...i[t]||[],s]}))}function Ch(e,t,n,r,a,s){e(i=>({...i,[t]:(i[t]||[]).map(l=>l.id===n?{...l,value:r,time:a,handleType:s??l.handleType}:l)}))}function Mh(e,t,n){e(r=>({...r,[t]:(r[t]||[]).filter(a=>a.id!==n)}))}function Mn(e){if(!e||e<=0)return null;const t=12*Math.log2(e/440)+69;return Math.round(t-12)}function kh(e){if(e.length===0)return[];const t=[];let n=e[0];for(let r=1;r<e.length;r++){const a=e[r];a.pitch===n.pitch&&Math.abs(a.freq-n.freq)<1?n.duration+=a.duration:(t.push(n),n=a)}return t.push(n),t}function $h(e,t,n=.01){const r=Math.floor(t/50);let a=-1,s=0,i=0;for(let c=0;c<e.length;c++)i+=e[c]*e[c];if(i=Math.sqrt(i/e.length),i<n)return 0;let l=1;for(let c=50;c<r;c++){let d=0;for(let u=0;u<r;u++)d+=Math.abs(e[u]-e[u+c]);d=1-d/r,d>s&&d>.9&&d>l&&(s=d,a=c),l=d}return a===-1?0:t/a}async function Rh(e,t,n){const{signal:r,onProgress:a,rmsThreshold:s,useHanning:i,postPitch:l,postLibrosaPitchTrack:c}=n||{},d=await e.arrayBuffer();if(r!=null&&r.aborted)throw new Error("aborted");const p=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(d),m=p.getChannelData(0),f=p.sampleRate,y=Math.floor(f*.1),g=y,v=[];if(t==="pitchy"){const S=ur.PitchDetector.forFloat32Array(y),b=Math.max(1,Math.floor((m.length-y)/g));let x=0;for(let w=0;w<m.length-y;w+=g){if(r!=null&&r.aborted)throw new Error("aborted");const k=m.slice(w,w+y);if(i)for(let G=0;G<k.length;G++)k[G]*=.5*(1-Math.cos(2*Math.PI*G/(k.length-1)));const[j,T]=S.findPitch(k,f),D=Mn(j);let C=0;for(let G=0;G<k.length;G++)C+=k[G]*k[G];C=Math.sqrt(C/k.length);const L=typeof s=="number"?s:.01;D&&j>50&&j<2e3&&T>.7&&C>L&&v.push({start:w/f,duration:y/f,pitch:D,freq:j}),x++,a&&a(x/b)}}else if(t==="crepe"){if(a&&a(.05),!l)throw new Error("CREPE backend callback (postPitch) is required for crepe algorithm");const S=await l(e);if(r!=null&&r.aborted)throw new Error("aborted");const b=Array.isArray(S.track)?S.track:[];b.length>0&&b.forEach((x,w)=>{var j;const k=Mn(x.hz);if(k&&x.hz>50&&x.hz<2e3){const T=((j=b[w+1])==null?void 0:j.t)??x.t+.1;v.push({start:x.t,duration:w<b.length-1?T-x.t:.1,pitch:k,freq:x.hz})}}),a&&a(1)}else if(t==="ultrastar-wp"){const S=Math.max(1,Math.floor((m.length-y)/g));let b=0;for(let x=0;x<m.length-y;x+=g){if(r!=null&&r.aborted)throw new Error("aborted");const w=m.slice(x,x+y);if(i)for(let D=0;D<w.length;D++)w[D]*=.5*(1-Math.cos(2*Math.PI*D/(w.length-1)));const j=$h(w,f,typeof s=="number"?s:.01),T=Mn(j);T&&j>50&&j<2e3&&v.push({start:x/f,duration:y/f,pitch:T,freq:j}),b++,a&&a(b/S)}}if(t==="librosa"){if(a&&a(.05),!c)throw new Error("Librosa backend callback (postLibrosaPitchTrack) is required for librosa algorithm");const S=await c(e);if(r!=null&&r.aborted)throw new Error("aborted");const b=Array.isArray(S.track)?S.track:[];b.length>0&&b.forEach((x,w)=>{var j;const k=Mn(x.hz);if(k&&x.hz>50&&x.hz<2e3){const T=((j=b[w+1])==null?void 0:j.t)??x.t+.1;v.push({start:x.t,duration:w<b.length-1?T-x.t:.1,pitch:k,freq:x.hz})}}),a&&a(1)}return kh(v)}function jh(e){switch(e){case"pitchy":return`#TITLE:Analyzed Song
51
+ #ARTIST:AI
52
+ #ALGO:Pitchy
53
+ : 0 4 40 Pitchy
54
+ : 5 3 41 Example
55
+ E`;case"crepe":return`#TITLE:Analyzed Song
56
+ #ARTIST:AI
57
+ #ALGO:Crepe
58
+ : 0 2 42 Cre
59
+ : 2 2 43 pe
60
+ E`;case"librosa":return`#TITLE:Analyzed Song
61
+ #ARTIST:AI
62
+ #ALGO:Librosa
63
+ : 0 2 44 Li
64
+ : 2 2 45 bro
65
+ E`;case"ultrastarws":return`#TITLE:Analyzed Song
66
+ #ARTIST:AI
67
+ #ALGO:UltrastarWS
68
+ : 0 2 46 Ultra
69
+ : 2 2 47 starWS
70
+ E`;default:return`#TITLE:Analyzed Song
71
+ #ARTIST:AI
72
+ : 0 2 40 Test
73
+ E`}}function Th(e,t){return`${e}:${t}`}function Ph(e,t,n,r=1){if(t==="off")return e;const a=60/n;if(t==="beat")return Math.round(e/(a/r))*(a/r);if(t==="bar"){const s=a*4;return Math.round(e/s)*s}return e}function Eh(e){return e.length===0?[]:e.flat()}function Ah(e,t=44100){return new Array(Math.floor(e*t)).fill(0)}const Kr=[{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 Lh(e){let t=e;return()=>(t=t*1664525+1013904223&4294967295,(t>>>0)/4294967295)}function Fo(e,t){return t.amount===0?e:e.map(n=>{const r=n.time/t.grid;if(Math.round(r)%2===1){const i=t.grid*t.amount*.5;return{...n,time:n.time+i}}return{...n}})}function Oo(e,t){const n=t.seed!=null?Lh(t.seed):Math.random;return e.map(r=>{const a=(n()-.5)*2*t.timingAmount,s=Math.round((n()-.5)*2*t.velocityAmount),i=(n()-.5)*2*t.durationAmount;return{...r,time:Math.max(0,r.time+a),velocity:Math.max(1,Math.min(127,r.velocity+s)),duration:Math.max(.01,r.duration+i)}})}function Do(e,t,n=1){const r=4/t.stepsPerBar;return e.map(a=>{const s=a.time/r,i=Math.round(s)%t.stepsPerBar,l=t.timingOffsets[i]*r*n,c=1+(t.velocityScales[i]-1)*n,d=1+(t.durationScales[i]-1)*n;return{...a,time:Math.max(0,a.time+l),velocity:Math.max(1,Math.min(127,Math.round(a.velocity*c))),duration:Math.max(.01,a.duration*d)}})}function Nh(e,t){let n=[...e.map(r=>({...r}))];return t.template&&t.grooveStrength>0&&(n=Do(n,t.template,t.grooveStrength)),t.swing&&t.swing.amount>0&&(n=Fo(n,t.swing)),t.humanize&&(n=Oo(n,t.humanize)),n}function Ih(e){return Kr.find(t=>t.id===e)}function Fh(){return Kr.map(({id:e,name:t})=>({id:e,name:t}))}const Oh=[{type:"chipmunk",enabled:!1,intensity:60,label:"Chipmunk",icon:"🐿️"},{type:"helium",enabled:!1,intensity:80,label:"Helium",icon:"🎈"},{type:"deep",enabled:!1,intensity:50,label:"Deep Voice",icon:"🎸"},{type:"demon",enabled:!1,intensity:70,label:"Demon",icon:"😈"},{type:"robot",enabled:!1,intensity:50,label:"Robot",icon:"🤖"},{type:"alien",enabled:!1,intensity:60,label:"Alien",icon:"👽"},{type:"echo",enabled:!1,intensity:50,label:"Echo",icon:"🏔️"},{type:"cave",enabled:!1,intensity:60,label:"Cave",icon:"🕳️"},{type:"reverb",enabled:!1,intensity:50,label:"Reverb",icon:"⛪"},{type:"chorus",enabled:!1,intensity:50,label:"Chorus",icon:"🎵"},{type:"flanger",enabled:!1,intensity:50,label:"Flanger",icon:"🌊"},{type:"distortion",enabled:!1,intensity:40,label:"Distortion",icon:"🔥"},{type:"telephone",enabled:!1,intensity:80,label:"Telephone",icon:"📞"},{type:"megaphone",enabled:!1,intensity:60,label:"Megaphone",icon:"📢"},{type:"radio",enabled:!1,intensity:70,label:"AM Radio",icon:"📻"},{type:"underwater",enabled:!1,intensity:50,label:"Underwater",icon:"🌊"},{type:"whisper",enabled:!1,intensity:60,label:"Whisper",icon:"🤫"},{type:"tremolo",enabled:!1,intensity:50,label:"Tremolo",icon:"〰️"},{type:"autotune",enabled:!1,intensity:60,label:"Auto-Tune",icon:"🎤"},{type:"vocoder",enabled:!1,intensity:50,label:"Vocoder",icon:"🔊"}];function _a(e,t,n){const r=e.sampleRate,a=Math.round(r*t),s=e.createBuffer(2,a,r);for(let i=0;i<2;i++){const l=s.getChannelData(i);for(let c=0;c<a;c++)l[c]=(Math.random()*2-1)*Math.pow(1-c/a,n)}return s}function kn(e){const t=Math.max(1,e),n=44100,r=new Float32Array(n),a=Math.PI/180;for(let s=0;s<n;s++){const i=s*2/n-1;r[s]=(3+t)*i*20*a/(Math.PI+t*Math.abs(i))}return r}class Dh{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,r,a,s,i;this.clearAllEffects();try{(t=this.analyser)==null||t.disconnect()}catch{}try{(n=this.outputGain)==null||n.disconnect()}catch{}try{(r=this.inputGain)==null||r.disconnect()}catch{}try{(a=this.sourceNode)==null||a.disconnect()}catch{}try{(s=this.audioCtx)==null||s.close()}catch{}if(!this.externalStream)try{(i=this.mediaStream)==null||i.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 r=0;r<t.length;r++){const a=(t[r]-128)/128;n+=a*a}return Math.sqrt(n/t.length)}addEffect(t,n=50){if(!this.audioCtx||!this.inputGain||!this.outputGain||this.activeEffects.has(t))return;const r=this.buildEffectChain(t,n);r&&(this.activeEffects.set(t,r),this.effectOrder.push(t),this.reconnectChain())}removeEffect(t){const n=this.activeEffects.get(t);if(n){for(const r of n.nodes)try{r.disconnect()}catch{}this.activeEffects.delete(t),this.effectOrder=this.effectOrder.filter(r=>r!==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 r of n.nodes)try{r.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 r=this.activeEffects.get(n);r&&(t.connect(r.input),t=r.output)}t.connect(this.outputGain)}buildEffectChain(t,n){const r=this.audioCtx,a=n/100;switch(t){case"chipmunk":return this.buildPitchShift(r,1+a*.8,a);case"helium":return this.buildPitchShift(r,1.5+a*1,a);case"deep":return this.buildPitchShift(r,1/(1+a*.5),a);case"demon":return this.buildDemon(r,a);case"robot":return this.buildRobot(r,a);case"alien":return this.buildAlien(r,a);case"echo":return this.buildDelay(r,.15+a*.35,.3+a*.4,a);case"cave":return this.buildCave(r,a);case"reverb":return this.buildReverb(r,1.5+a*3,2+a*4,a);case"chorus":return this.buildChorus(r,a);case"flanger":return this.buildFlanger(r,a);case"distortion":return this.buildDistortion(r,20+a*100,a);case"telephone":return this.buildBandpass(r,400,3500,a);case"megaphone":return this.buildMegaphone(r,a);case"radio":return this.buildRadio(r,a);case"underwater":return this.buildUnderwater(r,a);case"whisper":return this.buildWhisper(r,a);case"tremolo":return this.buildTremolo(r,a);case"autotune":return this.buildAutotune(r,a);case"vocoder":return this.buildVocoder(r,a);default:return null}}buildPitchShift(t,n,r){const a=t.createGain();a.gain.value=1;const s=t.createGain();s.gain.value=1;const i=t.createGain();i.gain.value=.7+r*.3;const l=t.createGain();l.gain.value=1-r*.5;const c=t.createDelay(1),d=t.createDelay(1),u=t.createOscillator(),p=t.createOscillator(),m=t.createGain(),f=t.createGain(),y=n-1,g=Math.abs(y)*5+2,v=Math.abs(y)*.015;u.type="sawtooth",u.frequency.value=g,m.gain.value=v,u.connect(m),m.connect(c.delayTime),c.delayTime.value=.02,p.type="sawtooth",p.frequency.value=g,f.gain.value=v,p.connect(f),f.connect(d.delayTime),d.delayTime.value=.02+v;const S=t.createGain();S.gain.value=.5;const b=t.createGain();return b.gain.value=.5,a.connect(c),a.connect(d),c.connect(S),d.connect(b),S.connect(i),b.connect(i),a.connect(l),i.connect(s),l.connect(s),u.start(),p.start(),{type:"chipmunk",nodes:[a,c,d,u,p,m,f,S,b,i,l,s],input:a,output:s}}buildRobot(t,n){const r=t.createGain(),a=t.createGain(),s=t.createGain();s.gain.value=.6+n*.4;const i=t.createGain();i.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),r.connect(c),c.connect(s),r.connect(i),s.connect(a),i.connect(a),l.start(),{type:"robot",nodes:[r,l,c,s,i,a],input:r,output:a}}buildAlien(t,n){const r=t.createGain(),a=t.createGain(),s=t.createOscillator();s.type="sine",s.frequency.value=300+n*700;const i=t.createGain();i.gain.value=0,s.connect(i.gain),r.connect(i);const l=t.createDelay(.1);l.delayTime.value=.005;const c=t.createOscillator();c.type="sine",c.frequency.value=3+n*10;const d=t.createGain();d.gain.value=.004,c.connect(d),d.connect(l.delayTime),i.connect(l),l.connect(a);const u=t.createGain();return u.gain.value=.3,r.connect(u),u.connect(a),s.start(),c.start(),{type:"alien",nodes:[r,s,i,l,c,d,u,a],input:r,output:a}}buildDelay(t,n,r,a){const s=t.createGain(),i=t.createGain(),l=t.createDelay(2);l.delayTime.value=n;const c=t.createGain();c.gain.value=Math.min(.85,r);const d=t.createGain();d.gain.value=.5+a*.5;const u=t.createGain();return u.gain.value=1,s.connect(l),l.connect(c),c.connect(l),l.connect(d),s.connect(u),d.connect(i),u.connect(i),{type:"echo",nodes:[s,l,c,d,u,i],input:s,output:i}}buildCave(t,n){const r=t.createGain(),a=t.createGain(),s=t.createDelay(2);s.delayTime.value=.2+n*.3;const i=t.createDelay(2);i.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 d=t.createGain();d.gain.value=.35;const u=t.createGain();u.gain.value=.25;const p=t.createConvolver();p.buffer=_a(t,2+n*3,3);const m=t.createGain();m.gain.value=.3+n*.3,r.connect(s),s.connect(c),c.connect(s),r.connect(i),i.connect(d),d.connect(i),r.connect(l),l.connect(u),u.connect(l),s.connect(m),i.connect(m),l.connect(m),r.connect(p),p.connect(m);const f=t.createGain();return f.gain.value=.7,r.connect(f),f.connect(a),m.connect(a),{type:"cave",nodes:[r,s,i,l,c,d,u,p,m,f,a],input:r,output:a}}buildReverb(t,n,r,a){const s=t.createGain(),i=t.createGain(),l=t.createConvolver();l.buffer=_a(t,n,r);const c=t.createGain();c.gain.value=.4+a*.5;const d=t.createGain();return d.gain.value=1,s.connect(l),l.connect(c),s.connect(d),c.connect(i),d.connect(i),{type:"reverb",nodes:[s,l,c,d,i],input:s,output:i}}buildChorus(t,n){const r=t.createGain(),a=t.createGain(),s=[{delayMs:20,lfoFreq:.5,depth:.003},{delayMs:25,lfoFreq:.7,depth:.004},{delayMs:30,lfoFreq:1.1,depth:.005}],i=[r,a],l=t.createGain();l.gain.value=.7,r.connect(l),l.connect(a),i.push(l);for(const c of s){const d=t.createDelay(.1);d.delayTime.value=c.delayMs/1e3;const u=t.createOscillator();u.type="sine",u.frequency.value=c.lfoFreq;const p=t.createGain();p.gain.value=c.depth*(.5+n),u.connect(p),p.connect(d.delayTime);const m=t.createGain();m.gain.value=.3+n*.2,r.connect(d),d.connect(m),m.connect(a),u.start(),i.push(d,u,p,m)}return{type:"chorus",nodes:i,input:r,output:a}}buildFlanger(t,n){const r=t.createGain(),a=t.createGain(),s=t.createDelay(.02);s.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=.2+n*2;const l=t.createGain();l.gain.value=.003+n*.002,i.connect(l),l.connect(s.delayTime);const c=t.createGain();c.gain.value=.5+n*.35;const d=t.createGain();d.gain.value=.5+n*.3;const u=t.createGain();return u.gain.value=1,r.connect(s),s.connect(c),c.connect(s),s.connect(d),r.connect(u),d.connect(a),u.connect(a),i.start(),{type:"flanger",nodes:[r,s,i,l,c,d,u,a],input:r,output:a}}buildDistortion(t,n,r){const a=t.createGain(),s=t.createGain(),i=t.createWaveShaper();i.curve=kn(n),i.oversample="4x";const l=t.createGain();l.gain.value=.6+r*.4;const c=t.createGain();return c.gain.value=1-r*.4,a.connect(i),i.connect(l),a.connect(c),l.connect(s),c.connect(s),{type:"distortion",nodes:[a,i,l,c,s],input:a,output:s}}buildBandpass(t,n,r,a){const s=t.createGain(),i=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=r,c.Q.value=.7,s.connect(l),l.connect(c),c.connect(i),{type:"telephone",nodes:[s,l,c,i],input:s,output:i}}buildMegaphone(t,n){const r=t.createGain(),a=t.createGain(),s=t.createBiquadFilter();s.type="highpass",s.frequency.value=500;const i=t.createBiquadFilter();i.type="lowpass",i.frequency.value=4e3;const l=t.createWaveShaper();l.curve=kn(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,r.connect(s),s.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"megaphone",nodes:[r,s,i,l,c,a],input:r,output:a}}buildRadio(t,n){const r=t.createGain(),a=t.createGain(),s=t.createBiquadFilter();s.type="highpass",s.frequency.value=300+n*200;const i=t.createBiquadFilter();i.type="lowpass",i.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=kn(10),r.connect(s),s.connect(i),i.connect(l),l.connect(c),c.connect(a),{type:"radio",nodes:[r,s,i,l,c,a],input:r,output:a}}buildUnderwater(t,n){const r=t.createGain(),a=t.createGain(),s=t.createBiquadFilter();s.type="lowpass",s.frequency.value=300+(1-n)*400,s.Q.value=5+n*10;const i=t.createOscillator();i.type="sine",i.frequency.value=.5+n*2;const l=t.createGain();l.gain.value=100+n*200,i.connect(l),l.connect(s.frequency);const c=t.createGain();c.gain.value=.7+n*.3;const d=t.createGain();return d.gain.value=.3-n*.2,r.connect(s),s.connect(c),r.connect(d),c.connect(a),d.connect(a),i.start(),{type:"underwater",nodes:[r,s,i,l,c,d,a],input:r,output:a}}buildWhisper(t,n){const r=t.createGain(),a=t.createGain(),s=t.createBiquadFilter();s.type="highpass",s.frequency.value=500+n*500,s.Q.value=.5;const i=t.createWaveShaper(),l=new Float32Array(256);for(let d=0;d<256;d++){const u=d/255*2-1;l[d]=Math.sign(u)*Math.pow(Math.abs(u),.3+n*.5)}i.curve=l;const c=t.createBiquadFilter();return c.type="highshelf",c.frequency.value=3e3,c.gain.value=6+n*6,r.connect(s),s.connect(i),i.connect(c),c.connect(a),{type:"whisper",nodes:[r,s,i,c,a],input:r,output:a}}buildDemon(t,n){const r=t.createGain(),a=t.createGain(),s=t.createDelay(.1);s.delayTime.value=.03;const i=t.createOscillator();i.type="sawtooth",i.frequency.value=2+n*3;const l=t.createGain();l.gain.value=.02+n*.015,i.connect(l),l.connect(s.delayTime);const c=t.createWaveShaper();c.curve=kn(20+n*50),c.oversample="2x";const d=t.createBiquadFilter();d.type="lowshelf",d.frequency.value=200,d.gain.value=8+n*8;const u=t.createGain();u.gain.value=.7+n*.3;const p=t.createGain();return p.gain.value=.3,r.connect(s),s.connect(c),c.connect(d),d.connect(u),r.connect(p),u.connect(a),p.connect(a),i.start(),{type:"demon",nodes:[r,s,i,l,c,d,u,p,a],input:r,output:a}}buildTremolo(t,n){const r=t.createGain(),a=t.createGain(),s=t.createGain();s.gain.value=1;const i=t.createOscillator();i.type="sine",i.frequency.value=3+n*12;const l=t.createGain();return l.gain.value=.3+n*.5,i.connect(l),l.connect(s.gain),r.connect(s),s.connect(a),i.start(),{type:"tremolo",nodes:[r,s,i,l,a],input:r,output:a}}buildAutotune(t,n){const r=t.createGain(),a=t.createGain(),s=t.createDelay(.05);s.delayTime.value=.005;const i=t.createOscillator();i.type="sine",i.frequency.value=6+n*8;const l=t.createGain();l.gain.value=.002+n*.002,i.connect(l),l.connect(s.delayTime);const c=[],d=[261.6,293.7,329.6,349.2,392,440,493.9,523.3],u=t.createGain();u.gain.value=.15;for(const f of d){const y=t.createBiquadFilter();y.type="peaking",y.frequency.value=f,y.Q.value=8+n*15,y.gain.value=4+n*8,r.connect(y),y.connect(u),c.push(y)}const p=t.createGain();p.gain.value=.7;const m=t.createGain();return m.gain.value=.5+n*.3,r.connect(s),s.connect(m),u.connect(m),r.connect(p),m.connect(a),p.connect(a),i.start(),{type:"autotune",nodes:[r,s,i,l,...c,u,m,p,a],input:r,output:a}}buildVocoder(t,n){const r=t.createGain(),a=t.createGain(),s=t.createOscillator();s.type="sawtooth",s.frequency.value=110+n*110;const i=t.createGain();i.gain.value=0;const l=8,c=[r,a,s,i],d=t.createGain();d.gain.value=.5+n*.5,c.push(d);for(let p=0;p<l;p++){const m=200*Math.pow(2,p*.5),f=t.createBiquadFilter();f.type="bandpass",f.frequency.value=m,f.Q.value=4;const y=t.createBiquadFilter();y.type="bandpass",y.frequency.value=m,y.Q.value=4;const g=t.createGain();g.gain.value=0,r.connect(f),f.connect(g.gain),s.connect(y),y.connect(g),g.connect(d),c.push(f,y,g)}d.connect(a);const u=t.createGain();return u.gain.value=.3-n*.2,r.connect(u),u.connect(a),c.push(u),s.start(),{type:"vocoder",nodes:c,input:r,output:a}}}const Go=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Lt(e){return 12*Math.log2(e/440)+69}function $n(e){const t=Go[Math.round(e)%12],n=Math.floor(Math.round(e)/12)-1;return`${t}${n}`}function cr(e,t){if(e.length===0)return 0;const n=t/100*(e.length-1),r=Math.floor(n),a=Math.ceil(n);return r===a?e[r]:e[r]+(e[a]-e[r])*(n-r)}function Gh(e){const{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:s,difficulty:i,pitchPoints:l,notes:c,verseRatings:d,combo:u,classicScore:p,bonusScore:m,totalScore:f,micSettings:y}=e,g=l.filter(Y=>Y.hz>0),v=g.map(Y=>Lt(Y.hz)),S=[],b=[],x=[],w=[...c].sort((Y,re)=>Y.startTime-re.startTime);function k(Y){let re=0,Ae=w.length-1;for(;re<=Ae;){const Ie=re+Ae>>>1,Be=w[Ie];if(Y<Be.startTime)Ae=Ie-1;else if(Y>Be.startTime+Be.duration)re=Ie+1;else return Be.pitch}return 0}for(const Y of l){const re=Y.hz>0?Lt(Y.hz):0,Ae=k(Y.t);if(b.push({t:Y.t,sung:re,expected:Ae}),re>0&&Ae>0){const Ie=(re-Ae)*100;S.push(Ie)}}let j=0;for(const Y of w){const re=Y.startTime-.3,Ae=Y.startTime+Y.duration;for(;j<g.length&&g[j].t<re;)j++;j<g.length&&g[j].t<=Ae&&x.push((g[j].t-Y.startTime)*1e3)}const T=S.map(Math.abs),D=[...T].sort((Y,re)=>Y-re),C=T.length>0?T.reduce((Y,re)=>Y+re,0)/T.length:0,L=cr(D,50),G=T.length>1?Math.sqrt(T.reduce((Y,re)=>Y+(re-C)**2,0)/(T.length-1)):0,q=T.filter(Y=>Y<=50).length,A=T.filter(Y=>Y<=15).length,V=T.length>0?q/T.length*100:0,te=T.length>0?A/T.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"],W=new Array(10).fill(0);for(const Y of S){const re=Y<-100?0:Y<-50?1:Y<-25?2:Y<-15?3:Y<0?4:Y<15?5:Y<25?6:Y<50?7:Y<100?8:9;W[re]++}const Q=ee.map((Y,re)=>({centRange:Y,count:W[re],pct:S.length>0?W[re]/S.length*100:0})),E=g.map(Y=>Y.hz).sort((Y,re)=>Y-re),F=E.length>0?E[0]:0,N=E.length>0?E[E.length-1]:0,$=F>0?Lt(F):0,M=N>0?Lt(N):0,O=M-$,R=[...v].sort((Y,re)=>Y-re),_=cr(R,10),I=cr(R,90),B=new Array(12).fill(0);for(const Y of v){const re=Math.round(Y)%12;re>=0&&re<12&&B[re]++}const Z=B.reduce((Y,re)=>Y+re,0),z=Go.map((Y,re)=>({note:Y,count:B[re],pct:Z>0?B[re]/Z*100:0})),H=_h(g),ae=x.length>0?x.reduce((Y,re)=>Y+re,0)/x.length:0,le=x.length>1?Math.sqrt(x.reduce((Y,re)=>Y+(re-ae)**2,0)/(x.length-1)):0,ne=le>0?Math.max(0,Math.min(100,100-le/2)):100;let X=0,K=0;for(let Y=1;Y<v.length;Y++){const re=Math.abs(v[Y]-v[Y-1]);X+=re,K++}const J=K>0?X/K*100/12:0,oe=l.filter(Y=>Y.hz<=0).length,ie=l.length>0?(1-oe/l.length)*100:0,ue=new Map;for(const Y of c){const re=Y.line??0;ue.has(re)||ue.set(re,[]),ue.get(re).push(Y)}const U=new Map;for(const Y of g){const re=k(Y.t);if(re<=0)continue;let Ae=0,Ie=w.length-1,Be=-1;for(;Ae<=Ie;){const Pe=Ae+Ie>>>1,wt=w[Pe];if(Y.t<wt.startTime)Ie=Pe-1;else if(Y.t>wt.startTime+wt.duration)Ae=Pe+1;else{Be=wt.line??0;break}}if(Be<0)continue;const pt=Math.abs((Lt(Y.hz)-re)*100);U.has(Be)||U.set(Be,[]),U.get(Be).push(pt)}const fe=d.map(Y=>{const re=ue.get(Y.verseIndex)??[],Ae=U.get(Y.verseIndex)??[],Ie=Ae.length>0?Ae.reduce((Be,pt)=>Be+pt,0)/Ae.length:0;return{verseIndex:Y.verseIndex,label:Y.label,hitFraction:Y.hitFraction,avgCentDeviation:Math.round(Ie*10)/10,noteCount:re.length,notesHit:Math.round(Y.hitFraction*re.length),comboBonus:Y.comboBonus}}),me=2,xe=.5,De=l.length>0?l[l.length-1].t:0,Te=[],Me=b.filter(Y=>Y.sung>0&&Y.expected>0);if(Me.length>0){let Y=0,re=0,Ae=0;for(let Ie=0;Ie<=De;Ie+=xe){const Be=Ie-me/2,pt=Ie+me/2;for(;re<Me.length&&Me[re].t<pt;)Math.abs(Me[re].sung-Me[re].expected)<=.5&&Ae++,re++;for(;Y<re&&Me[Y].t<Be;)Math.abs(Me[Y].sung-Me[Y].expected)<=.5&&Ae--,Y++;const Pe=re-Y;Te.push({t:Ie,accuracy:Pe>0?Ae/Pe*100:0})}}else for(let Y=0;Y<=De;Y+=xe)Te.push({t:Y,accuracy:0});return{playerName:t,playerColor:n,songTitle:r,songArtist:a,songBpm:s,difficulty:i,timestamp:new Date().toISOString(),classicScore:p,bonusScore:m,totalScore:f,maxCombo:(u==null?void 0:u.maxCombo)??0,totalComboBonus:(u==null?void 0:u.totalComboBonus)??0,totalPitchPoints:l.length,avgCentDeviation:Math.round(C*10)/10,medianCentDeviation:Math.round(L*10)/10,stdDevCents:Math.round(G*10)/10,intonationAccuracyPct:Math.round(V*10)/10,perfectHitPct:Math.round(te*10)/10,pitchDeviationHistogram:Q,lowestHz:Math.round(F*10)/10,highestHz:Math.round(N*10)/10,lowestNote:$>0?$n($):"—",highestNote:M>0?$n(M):"—",rangeInSemitones:Math.round(O*10)/10,tessituraLow:_>0?$n(_):"—",tessituraHigh:I>0?$n(I):"—",pitchClassDistribution:z,vibrato:H,avgOnsetDeviationMs:Math.round(ae*10)/10,rhythmStabilityPct:Math.round(ne*10)/10,jitterPct:Math.round(J*100)/100,shimmerProxy:Math.round(ie*10)/10,verseMetrics:fe,micSettings:y,pitchOverTime:b,accuracyOverTime:Te}}function _h(e){if(e.length<20)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const t=e.map(f=>Lt(f.hz)),n=e.map(f=>f.t),r=.5,a=[],s=[];let i=0,l=0,c=0;for(let f=0;f<e.length;f++){for(l+=t[f],c++;i<f&&n[f]-n[i]>=r;)l-=t[i],c--,i++;if(c<6||(f-i)%10!==0)continue;const y=l/c;let g=0,v=t[i]-y,S=Math.abs(v);for(let w=i+1;w<=f;w++){const k=t[w]-y;k*v<0&&g++,v=k;const j=Math.abs(k);j>S&&(S=j)}const b=n[f]-n[i];if(b<=0)continue;const x=g/2/b;x>=3&&x<=12&&(a.push(x),s.push(S*100))}if(a.length<3)return{detected:!1,avgRateHz:0,avgExtentCents:0,regularityPct:0};const d=a.reduce((f,y)=>f+y,0)/a.length,u=s.reduce((f,y)=>f+y,0)/s.length,p=Math.sqrt(a.reduce((f,y)=>f+(y-d)**2,0)/a.length),m=Math.max(0,Math.min(100,100-p*20));return{detected:!0,avgRateHz:Math.round(d*10)/10,avgExtentCents:Math.round(u*10)/10,regularityPct:Math.round(m)}}function _o(e,t,n=50,r=30){const a=Math.round(e/1e3*t),s=Math.round(n/1e3*t),i=Math.max(1,Math.round(r/1e3*t)),l=new Float32Array(a);for(let c=0;c<i;c++){const d=.5*(1-Math.cos(2*Math.PI*c/(i-1))),u=s+c-Math.floor(i/2);u>=0&&u<a&&(l[u]=d)}return l}function Ba(e,t,n=1e3){const r=Math.max(1,Math.round(t/n)),a=Math.ceil(e.length/r),s=new Float32Array(a);for(let l=0;l<a;l++){const c=l*r,d=Math.min(e.length,c+r);let u=0;for(let p=c;p<d;p++)u+=Math.abs(e[p]);s[l]=u/(d-c||1)}let i=0;for(let l=0;l<s.length;l++)s[l]>i&&(i=s[l]);if(i>0)for(let l=0;l<s.length;l++)s[l]=s[l]/i;return{env:s,factor:r}}function Bh(e,t){const n=e.length,r=t.length;if(n===0||r===0)return 0;let a={lag:0,score:-1/0};const s=Math.min(2e3,r);for(let i=-s;i<=s;i++){let l=0,c=0,d=0;for(let m=0;m<n;m++){const f=m+i+Math.floor((r-n)/2);if(f<0||f>=r)continue;const y=e[m],g=t[f];l+=y*g,c+=y*y,d+=g*g}const u=Math.sqrt(Math.max(1e-9,c*d)),p=l/u;p>a.score&&(a={lag:i,score:p})}return a.lag}function zh(e,t,n=50,r=30){try{const a=Math.max(300,Math.round(e.length/t*1e3)),s=_o(a,t,n,r),i=Ba(e,t,1e3),l=Ba(s,t,1e3),d=Bh(l.env,i.env)*1e3/1e3;return Math.round(d)}catch{return null}}var Bo=(e=>(e[e.Ultrastar=0]="Ultrastar",e))(Bo||{}),ht=(e=>(e.Unknown="Unknown",e.Dimmer="Dimmer",e.DimmerWithOff="DimmerWithOff",e.RotationWithOff="RotationWithOff",e.RotationWithOffAndCcw="RotationWithOffAndCcw",e.Options="Options",e))(ht||{}),zo=(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))(zo||{}),Wo=(e=>(e[e.ReadOnly=0]="ReadOnly",e[e.Edit=1]="Edit",e[e.Owner=2]="Owner",e))(Wo||{});const Wh=["#4caf50","#2196f3","#ff9800","#e91e63","#9c27b0","#00bcd4","#8bc34a","#ffc107"],vt=["#2196f3","#e53935","#ffeb3b","#43a047","#ff9800","#9c27b0","#00bcd4","#ffc107","#8bc34a","#f44336","#3f51b5","#607d8b","#795548","#cddc39","#673ab7","#009688"];function Uh(e){for(const t of vt)if(!e.includes(t))return t;return vt[Math.floor(Math.random()*vt.length)]}const An=vt.map((e,t)=>`var(--player-color-${t+1}, ${e})`);function qh(e){for(let t=0;t<vt.length;t++){const n=vt[t],r=An[t];if(!e.includes(n)&&!e.includes(r))return r}return An[Math.floor(Math.random()*An.length)]}const zn=["off","no function","brak"],Vh=e=>e.segments.some(t=>t.isOff||zn.some(n=>t.name.toLowerCase().includes(n))),Kh=e=>e.segments.find(t=>t.isOff||zn.some(n=>t.name.toLowerCase().includes(n))),Uo=e=>Math.floor((e.valueFrom+e.valueTo)/2),Hh=e=>{const t=Kh(e);return t?Uo(t):0},Yh=(e,t)=>e.segments.find(n=>t>=n.valueFrom&&t<=n.valueTo),Qt=(e,t=0,n=255)=>Math.max(t,Math.min(n,Math.round(e))),Ln=({channel:e,value:t,onChange:n,onCommit:r,showDirectionHint:a})=>{const[s,i]=h.useState(Qt(t)),l=h.useMemo(()=>Yh(e,s),[e,s]);h.useEffect(()=>i(Qt(t)),[t]);const c=d=>{const u=Qt(d);i(u),n(u),r==null||r(u)};return o.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid #e5e7eb",borderRadius:8,padding:12},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[o.jsxs("strong",{children:[e.channel,". ",e.name]}),a&&l&&o.jsx("span",{style:{fontSize:12,color:"#6b7280"},children:l.name})]}),o.jsx("input",{type:"range",min:0,max:255,value:s,onChange:d=>{const u=Qt(Number(d.target.value));i(u),n(u)},onMouseUp:()=>r==null?void 0:r(s),onTouchEnd:()=>r==null?void 0:r(s),style:{width:"100%"}}),o.jsx("div",{style:{marginTop:6},children:o.jsx("input",{type:"number",min:0,max:255,value:s,onChange:d=>{const u=Qt(Number(d.target.value));i(u),n(u)},onBlur:()=>r==null?void 0:r(s),style:{width:80,padding:6,border:"1px solid #d1d5db",borderRadius:6}})}),Vh(e)&&o.jsx("button",{type:"button",onClick:()=>c(Hh(e)),style:{width:"100%",marginTop:8,padding:"6px 10px",borderRadius:6,border:"1px solid #d1d5db",background:"#f9fafb",cursor:"pointer"},children:"OFF"})]})},qo=({channel:e,value:t,onChange:n,onCommit:r})=>{const a=h.useMemo(()=>{const i=[...e.segments];return i.sort((l,c)=>{const d=(l.isOff?-1:0)+(zn.some(p=>l.name.toLowerCase().includes(p))?-1:0),u=(c.isOff?-1:0)+(zn.some(p=>c.name.toLowerCase().includes(p))?-1:0);return d!==u?d-u:l.name.localeCompare(c.name,void 0,{sensitivity:"base"})}),i},[e]),s=i=>{const l=Uo(i);n(l),r==null||r(l)};return o.jsxs("div",{className:"ntd-dmx-channel",style:{border:"1px solid #e5e7eb",borderRadius:8,padding:12},children:[o.jsxs("strong",{children:[e.channel,". ",e.name]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))",gap:8,marginTop:8,maxHeight:220,overflowY:"auto"},children:a.map((i,l)=>{const c=t>=i.valueFrom&&t<=i.valueTo;return o.jsx("button",{type:"button",onClick:()=>s(i),style:{padding:"8px 10px",borderRadius:8,border:c?"2px solid #2563eb":"1px solid #d1d5db",background:c?"#eff6ff":"#fff",textAlign:"left",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:`${i.name} [${i.valueFrom}..${i.valueTo}]`,children:i.name},`${i.name}-${l}`)})})]})},Vo=e=>{switch(e.channel.type){case ht.Dimmer:case ht.DimmerWithOff:return o.jsx(Ln,{...e});case ht.RotationWithOff:case ht.RotationWithOffAndCcw:return o.jsx(Ln,{...e,showDirectionHint:!0});case ht.Options:return o.jsx(qo,{...e});default:return o.jsx(Ln,{...e})}},dr=e=>Math.max(0,Math.min(255,Math.round(e)));function Zh({service:e,pollInterval:t=500,className:n,style:r}){const[a,s]=h.useState([]),[i,l]=h.useState(null),[c,d]=h.useState(()=>Array(513).fill(0)),[u,p]=h.useState(30),[m,f]=h.useState(0),[y,g]=h.useState(!1),v=h.useRef(null);h.useEffect(()=>{let C=!1;return e.getDevices().then(L=>{C||(s(L),L.length>0&&l(L[0]))}).catch(()=>{}),()=>{C=!0}},[e]),h.useEffect(()=>{if(v.current&&window.clearInterval(v.current),!(t<=0))return v.current=window.setInterval(async()=>{try{const C=await e.getState();Array.isArray(C.frontSnapshot)&&C.frontSnapshot.length>=513&&d(C.frontSnapshot.slice(0,513)),typeof C.fps=="number"&&p(C.fps),typeof C.startCode=="number"&&f(C.startCode)}catch{}},t),()=>{v.current&&window.clearInterval(v.current)}},[e,t]);const S=async()=>{i&&(await e.openPort(i.serialNumber||i.description),g(!0))},b=async()=>{await e.closePort(),g(!1)},x=async()=>{await e.blackout(),d(C=>{const L=[...C];for(let G=1;G<L.length;G++)L[G]=0;return L})},w=()=>e.configure(u,m),k=(C,L)=>{const G=dr(L);d(q=>{const A=[...q];return A[C]=G,A})},j=(C,L)=>e.setChannel(C,dr(L)),T=(i==null?void 0:i.deviceInfo)??null,D=h.useMemo(()=>{var C;return(C=T==null?void 0:T.channels)!=null&&C.length?T.channels:Array.from({length:16},(L,G)=>({channel:G+1,name:`Channel ${G+1}`,type:ht.Dimmer,segments:[{valueFrom:0,valueTo:255,name:"Intensity"}]}))},[T]);return o.jsxs("div",{className:`ntd-dmx-editor ${n??""}`,style:{padding:16,display:"grid",gap:16,...r},children:[o.jsxs("section",{style:{display:"grid",gap:12,gridTemplateColumns:"1fr auto auto auto",alignItems:"end"},children:[o.jsxs("div",{children:[o.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FTDI Device"}),o.jsx("select",{value:(i==null?void 0:i.serialNumber)||"",onChange:C=>l(a.find(L=>L.serialNumber===C.target.value)??null),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"},children:a.map(C=>{var L,G;return o.jsxs("option",{value:C.serialNumber,children:[((L=C.deviceInfo)==null?void 0:L.manufacturer)??""," ",((G=C.deviceInfo)==null?void 0:G.model)??C.description," (",C.serialNumber||C.description,")"]},C.serialNumber||C.description)})}),T&&o.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6b7280"},children:["Mode: ",o.jsx("b",{children:T.modeName}),", footprint: ",o.jsx("b",{children:T.footprint})]})]}),o.jsx("button",{onClick:S,disabled:!i||y,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #10b981",background:"#ecfdf5",cursor:"pointer"},children:"Open port"}),o.jsx("button",{onClick:b,disabled:!y,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #ef4444",background:"#fef2f2",cursor:"pointer"},children:"Close port"}),o.jsx("button",{onClick:x,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #4b5563",background:"#f3f4f6",cursor:"pointer"},children:"Blackout"})]}),o.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(160px, 100%), 1fr))",gap:12,alignItems:"end"},children:[o.jsxs("div",{children:[o.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"FPS"}),o.jsx("input",{type:"number",min:10,max:44,value:u,onChange:C=>p(Number(C.target.value)),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"}})]}),o.jsxs("div",{children:[o.jsx("label",{style:{display:"block",fontWeight:600,marginBottom:6},children:"Start Code"}),o.jsx("input",{type:"number",min:0,max:255,value:m,onChange:C=>f(dr(Number(C.target.value))),style:{width:"100%",padding:8,borderRadius:6,border:"1px solid #d1d5db"}})]}),o.jsx("div",{children:o.jsx("button",{onClick:w,style:{padding:"10px 14px",borderRadius:8,border:"1px solid #3b82f6",background:"#eff6ff",cursor:"pointer"},children:"Apply configuration"})})]}),o.jsxs("section",{children:[o.jsx("h3",{style:{margin:"8px 0 12px",fontSize:16},children:"Channels"}),o.jsx("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))"},children:D.map(C=>o.jsx(Vo,{channel:C,value:c[C.channel]??0,onChange:L=>k(C.channel,L),onCommit:L=>j(C.channel,L)},C.channel))})]})]})}exports.ALL_CAP_STYLES=fn;exports.ALL_EFFECTS=Oh;exports.ALL_TEXTURES=Ms;exports.ASYMMETRIC_CAPS=fs;exports.ArpeggiatorPanel=Ni;exports.AudioEffectType=zo;exports.AudioPitchAnalyzer=yc;exports.AudioPlaybackEngine=ku;exports.AudioRecorder=ts;exports.AudioTimeline=vi;exports.AutoSavePanel=yl;exports.BarFillEditor=gc;exports.CCAutomationLaneEditor=Ei;exports.CCLane=hi;exports.CollaboratorPermission=Wo;exports.DEFAULT_ARP_CONFIG=Xa;exports.DEFAULT_BAR_FILL=xt;exports.DEFAULT_CAP_STYLE=ms;exports.DEFAULT_EMPTY_BAR_FILL=Un;exports.DEFAULT_FONT_SETTINGS=Kn;exports.DEFAULT_GOLD_EMPTY_BAR_FILL=qn;exports.DEFAULT_GOLD_FILLED_BAR_FILL=Vn;exports.DEFAULT_KARAOKE_SETTINGS=gs;exports.DEFAULT_PLAYER_BAR_STYLE=_t;exports.DEFAULT_SEED_CONFIG=eo;exports.DRUM_PATTERN_NAMES=_u;exports.DefaultScoringPresets=Dr;exports.DmxChannelControl=Vo;exports.DmxChannelType=ht;exports.DmxEditor=Zh;exports.DmxOptionsControl=qo;exports.DmxSliderControl=Ln;exports.DynamicRuleEditor=Ld;exports.DynamicRuleField=Ue;exports.DynamicRuleOperator=qe;exports.EditorTrackProvider=ss;exports.GRADIENT_PRESETS=ks;exports.GROOVE_TEMPLATES=Kr;exports.GenericPlayer=Lc;exports.GenericPlayerControls=Bc;exports.GenericPlayerStage=yd;exports.GenericPlayerStageVisualizer=Sd;exports.GenericPlaylist=Rd;exports.GenericPlaylistItem=Fs;exports.KARAOKE_FONT_OPTIONS=vc;exports.KEY_MAPS=js;exports.KaraokeEditorManager=$c;exports.KaraokeFormat=Bo;exports.KaraokeLyrics=Dl;exports.KaraokePhaserRenderer=jc;exports.KaraokeTimeline=pc;exports.LANE_COLORS=ln;exports.LAYER_COLORS=Wh;exports.LFOPanel=Oi;exports.MasterFXPanel=xl;exports.ModeSwitcher=Ns;exports.NOTE_NAMES=Lu;exports.NiceI18nProvider=si;exports.NoteParticles=Mu;exports.NoteRiver=yu;exports.OVERLAY_PATTERNS=Gn;exports.PLAYER_COLORS=vt;exports.PLAYER_COLOR_VARS=An;exports.PROGRESSION_NAMES=Gu;exports.PadNotePlayer=Cc;exports.PaneSide=Gs;exports.PianoRoll=ui;exports.PlaylistBrowser=Ud;exports.PlaylistDualPane=Fd;exports.PlaylistList=Ks;exports.PlaylistSidebar=Vd;exports.PlaylistTagEditor=jd;exports.PlaylistType=Os;exports.RecordingOptionsPanel=Sl;exports.SCALE_NAMES=Du;exports.SKEW_CAPS=ps;exports.SYMMETRIC_CAPS=Fr;exports.SimpleSynth=Qs;exports.SortDirection=It;exports.SortField=_s;exports.StageVisualizer=Is;exports.StepSequencerPanel=_i;exports.TEXTURE_CATEGORIES=Gr;exports.TrackSource=Bs;exports.UndoRedoPanel=bl;exports.ViewMode=Ds;exports.VocalEffectsEngine=Dh;exports.Waveform=ii;exports.YouTubePlayer=wd;exports.ZoomSnapControls=vl;exports.addEffectToLayer=ph;exports.addMidiNote=bh;exports.analyzeAudioFileWithAlgorithm=Rh;exports.applyGroove=Nh;exports.applyGrooveTemplate=Do;exports.applyHumanize=Oo;exports.applyKaraokeDisplayVars=Br;exports.applySwing=Fo;exports.arrow_L=ft;exports.arrow_R=at;exports.autoCorrelate=ah;exports.bracket_L=Ar;exports.bracket_R=us;exports.buildArpSequence=Ja;exports.buildLanes=Ts;exports.buildNoteDescriptors=sh;exports.buildPadNoteEvents=Es;exports.buildSegmentScores=oh;exports.canRedo=lo;exports.canUndo=io;exports.chamfer_L=In;exports.chamfer_R=Gt;exports.clearMidiNotes=xh;exports.clearPattern=Ro;exports.computeTheoreticalMax=Ao;exports.computeVocalPerformanceReport=Gh;exports.convertBrowserSongToKaraokeSongFile=fh;exports.copyCCEvents=kr;exports.createArpPattern=Ku;exports.createBasslinePattern=Hu;exports.createCCHistory=ro;exports.createDefaultLFO=Wn;exports.createEmptyPattern=St;exports.createEmptyStep=Ur;exports.createHiHatPattern=Vu;exports.createKickPattern=Uu;exports.createSnarePattern=qu;exports.cutCCEvents=uo;exports.deleteCCEventsInRange=ho;exports.deserializeLFO=Ti;exports.deserializePattern=Zu;exports.downsampleAndQuantizePitchPoints=ih;exports.drawGlossyBarOnCanvas=nn;exports.drawTimeline=gr;exports.estimateLatencyMs=lh;exports.estimateLatencyMsFromRecording=zh;exports.evaluateLFO=Rr;exports.evaluateLFOAsCC=jr;exports.exportCCLane=mo;exports.extractBpmFromNotes=is;exports.findTextureByUrl=mc;exports.generateArpEvents=Li;exports.generatePlaceholderWaveform=Ah;exports.generateSeed=Ou;exports.generateUltrastarText=jh;exports.getActiveGradient=Rs;exports.getActiveLyrics=Ll;exports.getActiveWords=Nl;exports.getAlgorithmColor=dh;exports.getAlgorithmCssVar=uh;exports.getAlgorithmLabel=ch;exports.getArpModes=Qa;exports.getArpRates=es;exports.getAudioContext=qt;exports.getBackgroundUrl=rh;exports.getCachedImage=oc;exports.getCapStyleByName=en;exports.getComboMultiplier=Eo;exports.getCoverUrl=nh;exports.getGrooveTemplate=Ih;exports.getGrooveTemplateNames=Fh;exports.getLaneForPitch=Ps;exports.getNextPlayerColor=Uh;exports.getNextPlayerColorCss=qh;exports.getOverlayCanvasPattern=on;exports.getPatternByName=tn;exports.getScoringPreset=ws;exports.getTexturePattern=an;exports.getVerseRatingLabel=Po;exports.handleAddCCEvent=wh;exports.handleRedo=Rl;exports.handleRemoveCCEvent=Mh;exports.handleSelectCCLane=Sh;exports.handleUndo=$l;exports.handleUpdateCCEvent=Ch;exports.hexToHsl=_n;exports.hydrateKaraokeDisplayFromBackend=xc;exports.hydratePlayerKaraokeSettingsFromBackend=tc;exports.hzToUltrastarPitch=ls;exports.importCCLane=go;exports.initKaraokeDisplaySettings=wc;exports.instrumentPresets=$u;exports.isAudioContextRunning=Wa;exports.loadAllKaraokeSettings=nc;exports.loadKaraokeDisplaySettings=$s;exports.loadKaraokeSettings=ys;exports.loadPlayerBarStyle=bs;exports.loadPlayerBarStyles=ac;exports.loadRemoteScoringPresets=hc;exports.makeClickReference=_o;exports.makeClipSelectionId=Th;exports.mergeWaveforms=Eh;exports.midiToHz=yr;exports.normalizeHex=Bn;exports.ornate_L=Nr;exports.ornate_R=Dn;exports.parseLyrics=El;exports.parseNotes=Pr;exports.parseVersesWithSyllables=os;exports.parseVersesWithWords=Al;exports.parseVideoMetadata=No;exports.pasteCCEvents=co;exports.pill_L=yt;exports.pill_R=ut;exports.preloadTexture=Or;exports.preloadTextures=ic;exports.pushCCState=ao;exports.randomizeVelocity=$o;exports.recordCCEvent=fo;exports.redoCC=oo;exports.removeEffectFromLayer=mh;exports.removeMidiNote=vh;exports.renderGlossyBarSvg=vs;exports.resumeAudioContext=Vt;exports.reversePattern=Mo;exports.sampleLFOForDisplay=Ya;exports.sampleLFOToCCEvents=Ha;exports.saveKaraokeDisplaySettings=Sc;exports.saveKaraokeSettings=ec;exports.savePlayerBarStyle=rc;exports.scaleResult=th;exports.scaleTo10k=Lo;exports.scoreNotesWithPitchPoints=eh;exports.selectCCEventsInRange=Bu;exports.serializeLFO=ji;exports.serializePattern=Yu;exports.setProjectWithUndo=rs;exports.setStepGate=xo;exports.setStepNote=bo;exports.setStepProbability=So;exports.setStepVelocity=vo;exports.sharp_L=Ot;exports.sharp_R=Dt;exports.shield_L=Fn;exports.shield_R=ds;exports.shiftPattern=ko;exports.shouldTrigger=To;exports.skewTL_L=Rn;exports.skewTL_R=pr;exports.skewTR_L=fr;exports.skewTR_R=jn;exports.snapToGrid=Ph;exports.soft_L=Er;exports.soft_R=cs;exports.stepDuration=qr;exports.stepTimeOffset=jo;exports.syncDivisionToHz=Va;exports.tab_L=Lr;exports.tab_R=hs;exports.thinCCEvents=po;exports.toTrack=hh;exports.toggleEffectBypass=gh;exports.toggleStep=yo;exports.toggleStepSlide=wo;exports.transposePattern=Co;exports.undoCC=so;exports.updateEffectParams=yh;exports.useAutoSave=wl;exports.useCCAutomation=Wu;exports.useEditorTrack=Pl;exports.useMPE=Pu;exports.useMidiLearn=ju;exports.useNiceTranslation=Ce;exports.useOxygen25=Au;exports.usePitchWorker=Ju;exports.usePlaybackEngine=Cl;exports.useProjectCRUD=Tl;exports.useRecording=Ml;exports.useScoringWorker=Qu;exports.useStepSequencer=Xu;exports.useWebMidi=Zn;exports.useWorker=Vr;exports.wave_L=On;exports.wave_R=Ir;exports.waveformValue=Ka;